diff --git a/README.md b/README.md index 5806289d..2b5866d6 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,7 @@ Check out [**Live Demo**](https://vladmandic.github.io/human/demo/index.html) ap - [**Usage & Functions**](https://github.com/vladmandic/human/wiki/Usage) - [**Configuration Details**](https://github.com/vladmandic/human/wiki/Configuration) - [**Output Details**](https://github.com/vladmandic/human/wiki/Outputs) +- [**Caching & Smoothing**](https://github.com/vladmandic/human/wiki/Caching) - [**Face Recognition & Face Description**](https://github.com/vladmandic/human/wiki/Embedding) - [**Gesture Recognition**](https://github.com/vladmandic/human/wiki/Gesture) - [**Common Issues**](https://github.com/vladmandic/human/wiki/Issues) diff --git a/TODO.md b/TODO.md index 9c405006..e16da45a 100644 --- a/TODO.md +++ b/TODO.md @@ -2,16 +2,14 @@ ## Work in Progress -- `skipTime`: testing, documentation -
### Exploring -- Optical Flow: -- TFLite Models: -- Histogram Equalization: Regular, Adaptive, Contrast Limited - Switch to custom `tfjs` for main `human` ESM bundle +- Optical Flow: +- Histogram Equalization: Regular, Adaptive, Contrast Limited +- TFLite Models: - Body segmentation: `robust-video-matting` #### WebGPU @@ -55,6 +53,7 @@ Object detection using CenterNet or NanoDet models is not working when using WAS ## Pending Release - Update to TFJS 3.10.0 +- Time based caching - Multiple bug fixes - Utility class `human.env` - Add `skipTime` in addition to `skipFrames` diff --git a/demo/index.js b/demo/index.js index e358eebe..1875f21f 100644 --- a/demo/index.js +++ b/demo/index.js @@ -1016,6 +1016,7 @@ async function main() { // create instance of human human = new Human(userConfig); + human.env.perfadd = true; log('human version:', human.version); // we've merged human defaults with user config and now lets store it back so it can be accessed by methods such as menu diff --git a/dist/human.custom.esm.js b/dist/human.custom.esm.js index 4f068824..c64fa574 100644 --- a/dist/human.custom.esm.js +++ b/dist/human.custom.esm.js @@ -4,47 +4,47 @@ author: ' */ -var Og=Object.defineProperty;var vN=(e,t,n)=>t in e?Og(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var wN=e=>Og(e,"__esModule",{value:!0});var xa=(e=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(e,{get:(t,n)=>(typeof require!="undefined"?require:t)[n]}):e)(function(e){if(typeof require!="undefined")return require.apply(this,arguments);throw new Error('Dynamic require of "'+e+'" is not supported')});var qp=(e,t)=>{wN(e);for(var n in t)Og(e,n,{get:t[n],enumerable:!0})};var pe=(e,t,n)=>(vN(e,typeof t!="symbol"?t+"":t,n),n),Qb=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var Ec=(e,t,n)=>(Qb(e,t,"read from private field"),n?n.call(e):t.get(e)),Rc=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},$c=(e,t,n,s)=>(Qb(e,t,"write to private field"),s?s.call(e,n):t.set(e,n),n);function at(e,t){let n=e.endsWith("/")?"":"/",r=t.startsWith(".")||t.startsWith("/")||t.startsWith("http:")||t.startsWith("https:")||t.startsWith("file:")?`${t}`:`${e}${n}${t}`;if(!r.toLocaleLowerCase().includes(".json"))throw new Error(`modelpath error: ${r} expecting json file`);return r}function ae(...e){let t=new Date,n=`${t.getHours().toString().padStart(2,"0")}:${t.getMinutes().toString().padStart(2,"0")}:${t.getSeconds().toString().padStart(2,"0")}.${t.getMilliseconds().toString().padStart(3,"0")}`;e&&console.log(n,"Human:",...e)}var Ae=()=>typeof performance!="undefined"?performance.now():parseInt((Number(process.hrtime.bigint())/1e3/1e3).toString());function Mg(e,t,n="config",s=[]){for(let r of Object.keys(t))if(typeof t[r]=="object")Mg(e[r],t[r],r,s);else{let a=e&&typeof e[r]!="undefined";a||s.push({reason:"unknown property",where:`${n}.${r} = ${t[r]}`});let o=e&&typeof e[r]==typeof t[r];a&&!o&&s.push({reason:"property type mismatch",where:`${n}.${r} = ${t[r]}`,expected:typeof e[r]})}return t.debug&&n==="config"&&s.length>0&&ae("invalid configuration",s),s}function $n(...e){let t=n=>n&&typeof n=="object";return e.reduce((n,s)=>(Object.keys(s||{}).forEach(r=>{let a=n[r],o=s[r];Array.isArray(a)&&Array.isArray(o)?n[r]=a.concat(...o):t(a)&&t(o)?n[r]=$n(a,o):n[r]=o}),n),{})}var Jo={backend:"",modelBasePath:"",wasmPath:"",debug:!0,async:!0,warmup:"full",cacheSensitivity:.75,skipFrame:!1,filter:{enabled:!0,width:0,height:0,flip:!1,return:!0,brightness:0,contrast:0,sharpness:0,blur:0,saturation:0,hue:0,negative:!1,sepia:!1,vintage:!1,kodachrome:!1,technicolor:!1,polaroid:!1,pixelate:0},gesture:{enabled:!0},face:{enabled:!0,detector:{modelPath:"blazeface.json",rotation:!0,maxDetected:1,skipFrames:11,skipTime:2e3,minConfidence:.2,iouThreshold:.1,return:!1},mesh:{enabled:!0,modelPath:"facemesh.json"},iris:{enabled:!0,modelPath:"iris.json"},emotion:{enabled:!0,minConfidence:.1,skipFrames:12,skipTime:2e3,modelPath:"emotion.json"},description:{enabled:!0,modelPath:"faceres.json",skipFrames:13,skipTime:2e3,minConfidence:.1},antispoof:{enabled:!1,skipFrames:14,skipTime:2e3,modelPath:"antispoof.json"}},body:{enabled:!0,modelPath:"movenet-lightning.json",detector:{modelPath:""},maxDetected:-1,minConfidence:.3,skipFrames:1,skipTime:2e3},hand:{enabled:!0,rotation:!0,skipFrames:2,skipTime:2e3,minConfidence:.5,iouThreshold:.2,maxDetected:-1,landmarks:!0,detector:{modelPath:"handtrack.json"},skeleton:{modelPath:"handskeleton.json"}},object:{enabled:!1,modelPath:"mb3-centernet.json",minConfidence:.2,iouThreshold:.4,maxDetected:10,skipFrames:15,skipTime:2e3},segmentation:{enabled:!1,modelPath:"selfie.json",blur:8}};var wl={};qp(wl,{Abs:()=>ni,Acos:()=>Vl,Acosh:()=>Ul,AdadeltaOptimizer:()=>ff,AdagradOptimizer:()=>mf,AdamOptimizer:()=>gf,AdamaxOptimizer:()=>Af,Add:()=>Hr,AddN:()=>wa,All:()=>Gl,Any:()=>Hl,ArgMax:()=>ka,ArgMin:()=>jl,Asin:()=>ql,Asinh:()=>Xl,Atan:()=>Kl,Atan2:()=>Yl,Atanh:()=>Zl,AvgPool:()=>Ia,AvgPool3D:()=>Fc,AvgPool3DGrad:()=>th,AvgPoolGrad:()=>eh,BackendWasm:()=>y6,BatchMatMul:()=>Sa,BatchToSpaceND:()=>si,Bincount:()=>nh,BroadcastArgs:()=>sh,BroadcastTo:()=>m5,Callback:()=>Tk,CallbackList:()=>mw,Cast:()=>Ca,Ceil:()=>Ta,ClipByValue:()=>jr,Complex:()=>Oc,ComplexAbs:()=>Mc,Concat:()=>ri,Conv2D:()=>Na,Conv2DBackpropFilter:()=>rh,Conv2DBackpropInput:()=>Ea,Conv3D:()=>zc,Conv3DBackpropFilterV2:()=>ah,Conv3DBackpropInputV2:()=>oh,Cos:()=>Ra,Cosh:()=>$a,CropAndResize:()=>oi,Cumsum:()=>ai,CustomCallback:()=>Aw,DataStorage:()=>Dc,DenseBincount:()=>ih,DepthToSpace:()=>ii,DepthwiseConv2dNative:()=>Da,DepthwiseConv2dNativeBackpropFilter:()=>lh,DepthwiseConv2dNativeBackpropInput:()=>uh,Diag:()=>ch,Dilation2D:()=>Lc,Dilation2DBackpropFilter:()=>ph,Dilation2DBackpropInput:()=>dh,ENV:()=>Ir,EarlyStopping:()=>Ek,Einsum:()=>Bc,Elu:()=>Pa,EluGrad:()=>hh,Environment:()=>h5,Equal:()=>li,Erf:()=>Jl,Exp:()=>Fa,ExpandDims:()=>ui,Expm1:()=>ci,FFT:()=>fh,Fill:()=>Ql,FlipLeftRight:()=>di,Floor:()=>Oa,FloorDiv:()=>Ma,FromPixels:()=>Kc,FusedBatchNorm:()=>za,FusedConv2D:()=>mo,FusedDepthwiseConv2D:()=>go,GPGPUContext:()=>vm,GatherNd:()=>hi,GatherV2:()=>pi,GraphModel:()=>i7,Greater:()=>fi,GreaterEqual:()=>La,History:()=>gw,IFFT:()=>mh,Identity:()=>Ba,Imag:()=>Wc,InputSpec:()=>Yt,IsFinite:()=>eu,IsInf:()=>tu,IsNan:()=>nu,KernelBackend:()=>Ll,LRN:()=>Uc,LRNGrad:()=>Ah,LayerVariable:()=>cw,LayersModel:()=>na,LeakyRelu:()=>mi,Less:()=>gi,LessEqual:()=>Ai,LinSpace:()=>gh,Log:()=>Wa,Log1p:()=>su,LogSoftmax:()=>g5,LogicalAnd:()=>yi,LogicalNot:()=>ru,LogicalOr:()=>Vc,MathBackendCPU:()=>xy,MathBackendWebGL:()=>Kd,Max:()=>Va,MaxPool:()=>Ga,MaxPool3D:()=>Gc,MaxPool3DGrad:()=>xh,MaxPoolGrad:()=>yh,MaxPoolWithArgmax:()=>bh,Maximum:()=>Ua,Mean:()=>Ha,Min:()=>ja,Minimum:()=>qa,MirrorPad:()=>Xa,Mod:()=>au,MomentumOptimizer:()=>yf,Multinomial:()=>vh,Multiply:()=>Ka,Neg:()=>xi,NonMaxSuppressionV3:()=>vi,NonMaxSuppressionV4:()=>ou,NonMaxSuppressionV5:()=>wi,NotEqual:()=>bi,OP_SCOPE_SUFFIX:()=>$5,OneHot:()=>Ii,OnesLike:()=>ki,Optimizer:()=>Qr,Pack:()=>Si,PadV2:()=>Za,Pool:()=>dE,Pow:()=>Ya,Prelu:()=>Ja,Prod:()=>Ci,RMSPropOptimizer:()=>xf,RNN:()=>sa,Range:()=>iu,Rank:()=>Xg,Real:()=>Hc,RealDiv:()=>_a,Reciprocal:()=>lu,Reduction:()=>Vn,Relu:()=>Qa,Relu6:()=>to,Reshape:()=>Ti,ResizeBilinear:()=>eo,ResizeBilinearGrad:()=>kh,ResizeNearestNeighbor:()=>uu,ResizeNearestNeighborGrad:()=>wh,Reverse:()=>Ni,RotateWithOffset:()=>Vi,Round:()=>Ei,Rsqrt:()=>no,SGDOptimizer:()=>xd,ScatterNd:()=>Ri,Select:()=>$i,Selu:()=>cu,Sequential:()=>Gf,Sigmoid:()=>ro,Sign:()=>du,Sin:()=>so,Sinh:()=>_i,Slice:()=>Di,Softmax:()=>io,Softplus:()=>pu,SpaceToBatchND:()=>Pi,SparseFillEmptyRows:()=>Ih,SparseReshape:()=>Sh,SparseSegmentMean:()=>Ch,SparseSegmentSum:()=>Th,SparseToDense:()=>jc,SplitV:()=>Fi,Sqrt:()=>ao,Square:()=>hu,SquaredDifference:()=>lo,Step:()=>ho,StridedSlice:()=>Oi,StringNGrams:()=>qc,StringSplit:()=>Nh,StringToHashBucketFast:()=>Eh,Sub:()=>uo,Sum:()=>oo,SymbolicTensor:()=>fr,Tan:()=>Mi,Tanh:()=>co,Tensor:()=>Ye,TensorBuffer:()=>sn,Tile:()=>qr,TopK:()=>zi,Transform:()=>Li,Transpose:()=>po,Unique:()=>Rh,Unpack:()=>Bi,UnsortedSegmentSum:()=>Xc,Variable:()=>sd,ZerosLike:()=>Wi,_FusedMatMul:()=>fo,abs:()=>rn,acos:()=>A3,acosh:()=>y3,add:()=>ie,addN:()=>Vh,all:()=>T2,any:()=>Uh,argMax:()=>Hs,argMin:()=>x3,asin:()=>b3,asinh:()=>v3,atan:()=>w3,atan2:()=>k3,atanh:()=>I3,avgPool:()=>Hh,avgPool3d:()=>R2,backend:()=>Tr,backend_util:()=>N,basicLSTMCell:()=>jR,batchNorm:()=>wu,batchNorm2d:()=>N3,batchNorm3d:()=>E3,batchNorm4d:()=>R3,batchToSpaceND:()=>jh,bincount:()=>$2,booleanMaskAsync:()=>aP,broadcastArgs:()=>$3,broadcastTo:()=>ud,browser:()=>Gs,buffer:()=>Le,callbacks:()=>bV,cast:()=>de,ceil:()=>D3,clipByValue:()=>fs,clone:()=>or,complex:()=>yo,concat:()=>It,concat1d:()=>_3,concat2d:()=>ku,concat3d:()=>P3,concat4d:()=>F3,constraints:()=>Uv,conv1d:()=>D2,conv2d:()=>ko,conv2dTranspose:()=>P2,conv3d:()=>F2,conv3dTranspose:()=>M3,copyRegisteredKernels:()=>fE,cos:()=>qh,cosh:()=>O2,cosineWindow:()=>i1,cumsum:()=>M2,customGrad:()=>Er,data:()=>l7,denseBincount:()=>z3,deprecationWarn:()=>I2,depthToSpace:()=>L3,depthwiseConv2d:()=>cd,deregisterOp:()=>wV,device_util:()=>gu,diag:()=>w$,dilation2d:()=>B3,disableDeprecationWarnings:()=>lR,dispose:()=>Q,disposeVariables:()=>uR,div:()=>he,divNoNan:()=>W3,dot:()=>R$,dropout:()=>Av,einsum:()=>V3,elu:()=>dd,enableDebugMode:()=>iR,enableProdMode:()=>m3,enclosingPowerOfTwo:()=>yv,engine:()=>ss,env:()=>K,equal:()=>Cs,erf:()=>U3,exp:()=>Ts,expandDims:()=>Kt,expm1:()=>G3,eye:()=>z2,fft:()=>af,fill:()=>Iu,findBackend:()=>S2,findBackendFactory:()=>hR,floor:()=>pd,floorDiv:()=>C2,forceHalfFloat:()=>zS,fused:()=>So,gather:()=>Su,gatherND:()=>gv,gather_util:()=>A2,getBackend:()=>ir,getGradient:()=>Gg,getKernel:()=>$h,getKernelsForBackend:()=>Xr,getThreadsCount:()=>q0e,gpgpu_util:()=>dS,grad:()=>tD,grads:()=>nD,greater:()=>ms,greaterEqual:()=>Yi,ifft:()=>gd,imag:()=>Xh,image:()=>$e,inTopKAsync:()=>gP,initializers:()=>Zv,input:()=>Bw,io:()=>ns,irfft:()=>t1,isFinite:()=>H$,isInf:()=>q$,isNaN:()=>H3,keep:()=>yn,kernel_impls:()=>Xs,layers:()=>iw,leakyRelu:()=>Kh,less:()=>L2,lessEqual:()=>Ji,linalg:()=>Nv,linspace:()=>j3,loadGraphModel:()=>st,loadLayersModel:()=>$B,localResponseNormalization:()=>q3,log:()=>Ns,log1p:()=>Zh,logSigmoid:()=>lD,logSoftmax:()=>B2,logSumExp:()=>J3,logicalAnd:()=>lr,logicalNot:()=>Jh,logicalOr:()=>U2,logicalXor:()=>bD,losses:()=>eO,matMul:()=>He,math:()=>K5,max:()=>rs,maxPool:()=>Qh,maxPool3d:()=>G2,maxPoolWithArgmax:()=>Q3,maximum:()=>Yr,mean:()=>Wt,memory:()=>Bh,meshgrid:()=>CD,metrics:()=>Ik,min:()=>ef,minimum:()=>hd,mirrorPad:()=>ev,mod:()=>tv,model:()=>EB,models:()=>Sk,moments:()=>tf,movingAverage:()=>lP,mul:()=>W,multiRNNCell:()=>PD,multinomial:()=>nv,neg:()=>Ot,nextFrame:()=>Ev,norm:()=>a1,notEqual:()=>Tu,oneHot:()=>id,ones:()=>gs,onesLike:()=>Es,op:()=>V,outerProduct:()=>LD,pad:()=>qs,pad1d:()=>VD,pad2d:()=>GD,pad3d:()=>jD,pad4d:()=>XD,pool:()=>QD,pow:()=>Io,prelu:()=>sf,print:()=>U5,prod:()=>H2,profile:()=>cR,rand:()=>r_,randomGamma:()=>l_,randomNormal:()=>sv,randomUniform:()=>Nu,range:()=>Eu,ready:()=>Wh,real:()=>fd,reciprocal:()=>rv,registerBackend:()=>Ki,registerCallbackConstructor:()=>DB,registerGradient:()=>A5,registerKernel:()=>Kr,registerOp:()=>vV,regularizers:()=>Ck,relu:()=>Rr,relu6:()=>X2,removeBackend:()=>pR,reshape:()=>G,reverse:()=>Rs,reverse1d:()=>A_,reverse2d:()=>x_,reverse3d:()=>v_,reverse4d:()=>k_,rfft:()=>of,round:()=>K2,rsqrt:()=>Z2,scalar:()=>Ee,scatterND:()=>mv,scatter_util:()=>y2,selu:()=>Y2,separableConv2d:()=>av,sequential:()=>RB,serialization:()=>le,setBackend:()=>g3,setPlatform:()=>fR,setThreadsCount:()=>j0e,setWasmPath:()=>H0e,setWasmPaths:()=>b6,setWebGLContext:()=>pm,setdiff1dAsync:()=>ov,shared:()=>om,sigmoid:()=>hs,sign:()=>iv,signal:()=>QF,sin:()=>J2,sinh:()=>Q2,slice:()=>_e,slice1d:()=>rf,slice2d:()=>e1,slice3d:()=>Ru,slice4d:()=>md,slice_util:()=>An,softmax:()=>$u,softplus:()=>Cu,spaceToBatchND:()=>nf,sparse:()=>yd,sparseToDense:()=>o1,spectral:()=>JF,split:()=>Sn,sqrt:()=>_n,square:()=>xt,squaredDifference:()=>n1,squeeze:()=>pt,stack:()=>Pn,step:()=>Ad,stridedSlice:()=>lv,string:()=>hf,sub:()=>ye,sum:()=>Ie,sumOutType:()=>rd,tan:()=>uv,tanh:()=>vu,tensor:()=>Gt,tensor1d:()=>Zt,tensor2d:()=>ur,tensor3d:()=>Z5,tensor4d:()=>K_,tensor5d:()=>Z_,tensor6d:()=>Y_,tensor_util:()=>rr,test_util:()=>p3,tidy:()=>j,tile:()=>js,time:()=>dR,topk:()=>cv,train:()=>tl,transpose:()=>et,truncatedNormal:()=>lf,unique:()=>s1,unregisterGradient:()=>hE,unregisterKernel:()=>pE,unsortedSegmentSum:()=>dv,unstack:()=>as,upcastType:()=>Bn,util:()=>v,valueAndGrad:()=>sD,valueAndGrads:()=>rD,variable:()=>pv,variableGrads:()=>X3,version:()=>w6,version_converter:()=>SU,version_core:()=>up,version_cpu:()=>dH,version_layers:()=>U1,version_wasm:()=>X0e,version_webgl:()=>zJ,webgl:()=>LJ,webgl_util:()=>FI,webgpu:()=>bC,where:()=>Wn,whereAsync:()=>r1,zeros:()=>Ht,zerosLike:()=>tt});var zl=(e=>typeof xa!="undefined"?xa:typeof Proxy!="undefined"?new Proxy(e,{get:(t,n)=>(typeof xa!="undefined"?xa:t)[n]}):e)(function(e){if(typeof xa!="undefined")return xa.apply(this,arguments);throw new Error('Dynamic require of "'+e+'" is not supported')}),kN=Object.create,Xp=Object.defineProperty,IN=Object.getOwnPropertyDescriptor,SN=Object.getOwnPropertyNames,CN=Object.getPrototypeOf,TN=Object.prototype.hasOwnProperty,e5=e=>Xp(e,"__esModule",{value:!0}),Ws=(e=>typeof zl!="undefined"?zl:typeof Proxy!="undefined"?new Proxy(e,{get:(t,n)=>(typeof zl!="undefined"?zl:t)[n]}):e)(function(e){if(typeof zl!="undefined")return zl.apply(this,arguments);throw new Error('Dynamic require of "'+e+'" is not supported')}),ts=(e,t)=>function(){return t||(0,e[Object.keys(e)[0]])((t={exports:{}}).exports,t),t.exports},ze=(e,t)=>{e5(e);for(var n in t)Xp(e,n,{get:t[n],enumerable:!0})},NN=(e,t,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of SN(t))!TN.call(e,s)&&s!=="default"&&Xp(e,s,{get:()=>t[s],enumerable:!(n=IN(t,s))||n.enumerable});return e},Qo=e=>NN(e5(Xp(e!=null?kN(CN(e)):{},"default",e&&e.__esModule&&"default"in e?{get:()=>e.default,enumerable:!0}:{value:e,enumerable:!0})),e),EN=ts({"node_modules/.pnpm/long@4.0.0/node_modules/long/src/long.js"(e,t){t.exports=s;var n=null;try{n=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(_){}function s(_,T,M){this.low=_|0,this.high=T|0,this.unsigned=!!M}s.prototype.__isLong__,Object.defineProperty(s.prototype,"__isLong__",{value:!0});function r(_){return(_&&_.__isLong__)===!0}s.isLong=r;var a={},o={};function i(_,T){var M,U,H;return T?(_>>>=0,(H=0<=_&&_<256)&&(U=o[_],U)?U:(M=c(_,(_|0)<0?-1:0,!0),H&&(o[_]=M),M)):(_|=0,(H=-128<=_&&_<128)&&(U=a[_],U)?U:(M=c(_,_<0?-1:0,!1),H&&(a[_]=M),M))}s.fromInt=i;function l(_,T){if(isNaN(_))return T?b:x;if(T){if(_<0)return b;if(_>=g)return P}else{if(_<=-A)return F;if(_+1>=A)return E}return _<0?l(-_,T).neg():c(_%m|0,_/m|0,T)}s.fromNumber=l;function c(_,T,M){return new s(_,T,M)}s.fromBits=c;var u=Math.pow;function d(_,T,M){if(_.length===0)throw Error("empty string");if(_==="NaN"||_==="Infinity"||_==="+Infinity"||_==="-Infinity")return x;if(typeof T=="number"?(M=T,T=!1):T=!!T,M=M||10,M<2||360)throw Error("interior hyphen");if(U===0)return d(_.substring(1),T,M).neg();for(var H=l(u(M,8)),z=x,X=0;X<_.length;X+=8){var ee=Math.min(8,_.length-X),Y=parseInt(_.substring(X,X+ee),M);if(ee<8){var se=l(u(M,ee));z=z.mul(se).add(l(Y))}else z=z.mul(H),z=z.add(l(Y))}return z.unsigned=T,z}s.fromString=d;function p(_,T){return typeof _=="number"?l(_,T):typeof _=="string"?d(_,T):c(_.low,_.high,typeof T=="boolean"?T:_.unsigned)}s.fromValue=p;var h=1<<16,f=1<<24,m=h*h,g=m*m,A=g/2,y=i(f),x=i(0);s.ZERO=x;var b=i(0,!0);s.UZERO=b;var w=i(1);s.ONE=w;var k=i(1,!0);s.UONE=k;var S=i(-1);s.NEG_ONE=S;var E=c(4294967295|0,2147483647|0,!1);s.MAX_VALUE=E;var P=c(4294967295|0,4294967295|0,!0);s.MAX_UNSIGNED_VALUE=P;var F=c(0,2147483648|0,!1);s.MIN_VALUE=F;var R=s.prototype;R.toInt=function(){return this.unsigned?this.low>>>0:this.low},R.toNumber=function(){return this.unsigned?(this.high>>>0)*m+(this.low>>>0):this.high*m+(this.low>>>0)},R.toString=function(T){if(T=T||10,T<2||36>>0,ne=se.toString(T);if(X=Y,X.isZero())return ne+ee;for(;ne.length<6;)ne="0"+ne;ee=""+ne+ee}},R.getHighBits=function(){return this.high},R.getHighBitsUnsigned=function(){return this.high>>>0},R.getLowBits=function(){return this.low},R.getLowBitsUnsigned=function(){return this.low>>>0},R.getNumBitsAbs=function(){if(this.isNegative())return this.eq(F)?64:this.neg().getNumBitsAbs();for(var T=this.high!=0?this.high:this.low,M=31;M>0&&(T&1<=0},R.isOdd=function(){return(this.low&1)==1},R.isEven=function(){return(this.low&1)==0},R.equals=function(T){return r(T)||(T=p(T)),this.unsigned!==T.unsigned&&this.high>>>31==1&&T.high>>>31==1?!1:this.high===T.high&&this.low===T.low},R.eq=R.equals,R.notEquals=function(T){return!this.eq(T)},R.neq=R.notEquals,R.ne=R.notEquals,R.lessThan=function(T){return this.comp(T)<0},R.lt=R.lessThan,R.lessThanOrEqual=function(T){return this.comp(T)<=0},R.lte=R.lessThanOrEqual,R.le=R.lessThanOrEqual,R.greaterThan=function(T){return this.comp(T)>0},R.gt=R.greaterThan,R.greaterThanOrEqual=function(T){return this.comp(T)>=0},R.gte=R.greaterThanOrEqual,R.ge=R.greaterThanOrEqual,R.compare=function(T){if(r(T)||(T=p(T)),this.eq(T))return 0;var M=this.isNegative(),U=T.isNegative();return M&&!U?-1:!M&&U?1:this.unsigned?T.high>>>0>this.high>>>0||T.high===this.high&&T.low>>>0>this.low>>>0?-1:1:this.sub(T).isNegative()?-1:1},R.comp=R.compare,R.negate=function(){return!this.unsigned&&this.eq(F)?F:this.not().add(w)},R.neg=R.negate,R.add=function(T){r(T)||(T=p(T));var M=this.high>>>16,U=this.high&65535,H=this.low>>>16,z=this.low&65535,X=T.high>>>16,ee=T.high&65535,Y=T.low>>>16,se=T.low&65535,ne=0,J=0,te=0,ue=0;return ue+=z+se,te+=ue>>>16,ue&=65535,te+=H+Y,J+=te>>>16,te&=65535,J+=U+ee,ne+=J>>>16,J&=65535,ne+=M+X,ne&=65535,c(te<<16|ue,ne<<16|J,this.unsigned)},R.subtract=function(T){return r(T)||(T=p(T)),this.add(T.neg())},R.sub=R.subtract,R.multiply=function(T){if(this.isZero())return x;if(r(T)||(T=p(T)),n){var M=n.mul(this.low,this.high,T.low,T.high);return c(M,n.get_high(),this.unsigned)}if(T.isZero())return x;if(this.eq(F))return T.isOdd()?F:x;if(T.eq(F))return this.isOdd()?F:x;if(this.isNegative())return T.isNegative()?this.neg().mul(T.neg()):this.neg().mul(T).neg();if(T.isNegative())return this.mul(T.neg()).neg();if(this.lt(y)&&T.lt(y))return l(this.toNumber()*T.toNumber(),this.unsigned);var U=this.high>>>16,H=this.high&65535,z=this.low>>>16,X=this.low&65535,ee=T.high>>>16,Y=T.high&65535,se=T.low>>>16,ne=T.low&65535,J=0,te=0,ue=0,ce=0;return ce+=X*ne,ue+=ce>>>16,ce&=65535,ue+=z*ne,te+=ue>>>16,ue&=65535,ue+=X*se,te+=ue>>>16,ue&=65535,te+=H*ne,J+=te>>>16,te&=65535,te+=z*se,J+=te>>>16,te&=65535,te+=X*Y,J+=te>>>16,te&=65535,J+=U*ne+H*se+z*Y+X*ee,J&=65535,c(ue<<16|ce,J<<16|te,this.unsigned)},R.mul=R.multiply,R.divide=function(T){if(r(T)||(T=p(T)),T.isZero())throw Error("division by zero");if(n){if(!this.unsigned&&this.high===-2147483648&&T.low===-1&&T.high===-1)return this;var M=(this.unsigned?n.div_u:n.div_s)(this.low,this.high,T.low,T.high);return c(M,n.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?b:x;var U,H,z;if(this.unsigned){if(T.unsigned||(T=T.toUnsigned()),T.gt(this))return b;if(T.gt(this.shru(1)))return k;z=b}else{if(this.eq(F)){if(T.eq(w)||T.eq(S))return F;if(T.eq(F))return w;var X=this.shr(1);return U=X.div(T).shl(1),U.eq(x)?T.isNegative()?w:S:(H=this.sub(T.mul(U)),z=U.add(H.div(T)),z)}else if(T.eq(F))return this.unsigned?b:x;if(this.isNegative())return T.isNegative()?this.neg().div(T.neg()):this.neg().div(T).neg();if(T.isNegative())return this.div(T.neg()).neg();z=x}for(H=this;H.gte(T);){U=Math.max(1,Math.floor(H.toNumber()/T.toNumber()));for(var ee=Math.ceil(Math.log(U)/Math.LN2),Y=ee<=48?1:u(2,ee-48),se=l(U),ne=se.mul(T);ne.isNegative()||ne.gt(H);)U-=Y,se=l(U,this.unsigned),ne=se.mul(T);se.isZero()&&(se=w),z=z.add(se),H=H.sub(ne)}return z},R.div=R.divide,R.modulo=function(T){if(r(T)||(T=p(T)),n){var M=(this.unsigned?n.rem_u:n.rem_s)(this.low,this.high,T.low,T.high);return c(M,n.get_high(),this.unsigned)}return this.sub(this.div(T).mul(T))},R.mod=R.modulo,R.rem=R.modulo,R.not=function(){return c(~this.low,~this.high,this.unsigned)},R.and=function(T){return r(T)||(T=p(T)),c(this.low&T.low,this.high&T.high,this.unsigned)},R.or=function(T){return r(T)||(T=p(T)),c(this.low|T.low,this.high|T.high,this.unsigned)},R.xor=function(T){return r(T)||(T=p(T)),c(this.low^T.low,this.high^T.high,this.unsigned)},R.shiftLeft=function(T){return r(T)&&(T=T.toInt()),(T&=63)==0?this:T<32?c(this.low<>>32-T,this.unsigned):c(0,this.low<>>T|this.high<<32-T,this.high>>T,this.unsigned):c(this.high>>T-32,this.high>=0?0:-1,this.unsigned)},R.shr=R.shiftRight,R.shiftRightUnsigned=function(T){if(r(T)&&(T=T.toInt()),T&=63,T===0)return this;var M=this.high;if(T<32){var U=this.low;return c(U>>>T|M<<32-T,M>>>T,this.unsigned)}else return T===32?c(M,0,this.unsigned):c(M>>>T-32,0,this.unsigned)},R.shru=R.shiftRightUnsigned,R.shr_u=R.shiftRightUnsigned,R.toSigned=function(){return this.unsigned?c(this.low,this.high,!1):this},R.toUnsigned=function(){return this.unsigned?this:c(this.low,this.high,!0)},R.toBytes=function(T){return T?this.toBytesLE():this.toBytesBE()},R.toBytesLE=function(){var T=this.high,M=this.low;return[M&255,M>>>8&255,M>>>16&255,M>>>24,T&255,T>>>8&255,T>>>16&255,T>>>24]},R.toBytesBE=function(){var T=this.high,M=this.low;return[T>>>24,T>>>16&255,T>>>8&255,T&255,M>>>24,M>>>16&255,M>>>8&255,M&255]},s.fromBytes=function(T,M,U){return U?s.fromBytesLE(T,M):s.fromBytesBE(T,M)},s.fromBytesLE=function(T,M){return new s(T[0]|T[1]<<8|T[2]<<16|T[3]<<24,T[4]|T[5]<<8|T[6]<<16|T[7]<<24,M)},s.fromBytesBE=function(T,M){return new s(T[4]<<24|T[5]<<16|T[6]<<8|T[7],T[0]<<24|T[1]<<16|T[2]<<8|T[3],M)}}}),RN=ts({"(disabled):node-fetch"(){}}),$N=ts({"(disabled):util"(){}}),DN=ts({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/alea.js"(e,t){(function(n,s,r){function a(c){var u=this,d=l();u.next=function(){var p=2091639*u.s0+u.c*23283064365386963e-26;return u.s0=u.s1,u.s1=u.s2,u.s2=p-(u.c=p|0)},u.c=1,u.s0=d(" "),u.s1=d(" "),u.s2=d(" "),u.s0-=d(c),u.s0<0&&(u.s0+=1),u.s1-=d(c),u.s1<0&&(u.s1+=1),u.s2-=d(c),u.s2<0&&(u.s2+=1),d=null}function o(c,u){return u.c=c.c,u.s0=c.s0,u.s1=c.s1,u.s2=c.s2,u}function i(c,u){var d=new a(c),p=u&&u.state,h=d.next;return h.int32=function(){return d.next()*4294967296|0},h.double=function(){return h()+(h()*2097152|0)*11102230246251565e-32},h.quick=h,p&&(typeof p=="object"&&o(p,d),h.state=function(){return o(d,{})}),h}function l(){var c=4022871197,u=function(d){d=String(d);for(var p=0;p>>0,h-=c,h*=c,c=h>>>0,h-=c,c+=h*4294967296}return(c>>>0)*23283064365386963e-26};return u}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.alea=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),_N=ts({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor128.js"(e,t){(function(n,s,r){function a(l){var c=this,u="";c.x=0,c.y=0,c.z=0,c.w=0,c.next=function(){var p=c.x^c.x<<11;return c.x=c.y,c.y=c.z,c.z=c.w,c.w^=c.w>>>19^p^p>>>8},l===(l|0)?c.x=l:u+=l;for(var d=0;d>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(typeof d=="object"&&o(d,u),p.state=function(){return o(u,{})}),p}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.xor128=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),PN=ts({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorwow.js"(e,t){(function(n,s,r){function a(l){var c=this,u="";c.next=function(){var p=c.x^c.x>>>2;return c.x=c.y,c.y=c.z,c.z=c.w,c.w=c.v,(c.d=c.d+362437|0)+(c.v=c.v^c.v<<4^(p^p<<1))|0},c.x=0,c.y=0,c.z=0,c.w=0,c.v=0,l===(l|0)?c.x=l:u+=l;for(var d=0;d>>4),c.next()}function o(l,c){return c.x=l.x,c.y=l.y,c.z=l.z,c.w=l.w,c.v=l.v,c.d=l.d,c}function i(l,c){var u=new a(l),d=c&&c.state,p=function(){return(u.next()>>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(typeof d=="object"&&o(d,u),p.state=function(){return o(u,{})}),p}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.xorwow=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),FN=ts({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorshift7.js"(e,t){(function(n,s,r){function a(l){var c=this;c.next=function(){var d=c.x,p=c.i,h,f,m;return h=d[p],h^=h>>>7,f=h^h<<24,h=d[p+1&7],f^=h^h>>>10,h=d[p+3&7],f^=h^h>>>3,h=d[p+4&7],f^=h^h<<7,h=d[p+7&7],h=h^h<<13,f^=h^h<<9,d[p]=f,c.i=p+1&7,f};function u(d,p){var h,f,m=[];if(p===(p|0))f=m[0]=p;else for(p=""+p,h=0;h0;--h)d.next()}u(c,l)}function o(l,c){return c.x=l.x.slice(),c.i=l.i,c}function i(l,c){l==null&&(l=+new Date);var u=new a(l),d=c&&c.state,p=function(){return(u.next()>>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(d.x&&o(d,u),p.state=function(){return o(u,{})}),p}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.xorshift7=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),ON=ts({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor4096.js"(e,t){(function(n,s,r){function a(l){var c=this;c.next=function(){var d=c.w,p=c.X,h=c.i,f,m;return c.w=d=d+1640531527|0,m=p[h+34&127],f=p[h=h+1&127],m^=m<<13,f^=f<<17,m^=m>>>15,f^=f>>>12,m=p[h]=m^f,c.i=h,m+(d^d>>>16)|0};function u(d,p){var h,f,m,g,A,y=[],x=128;for(p===(p|0)?(f=p,p=null):(p=p+"\0",f=0,x=Math.max(x,p.length)),m=0,g=-32;g>>15,f^=f<<4,f^=f>>>13,g>=0&&(A=A+1640531527|0,h=y[g&127]^=f+A,m=h==0?m+1:0);for(m>=128&&(y[(p&&p.length||0)&127]=-1),m=127,g=4*128;g>0;--g)f=y[m+34&127],h=y[m=m+1&127],f^=f<<13,h^=h<<17,f^=f>>>15,h^=h>>>12,y[m]=f^h;d.w=A,d.X=y,d.i=m}u(c,l)}function o(l,c){return c.i=l.i,c.w=l.w,c.X=l.X.slice(),c}function i(l,c){l==null&&(l=+new Date);var u=new a(l),d=c&&c.state,p=function(){return(u.next()>>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(d.X&&o(d,u),p.state=function(){return o(u,{})}),p}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.xor4096=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),MN=ts({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/tychei.js"(e,t){(function(n,s,r){function a(l){var c=this,u="";c.next=function(){var p=c.b,h=c.c,f=c.d,m=c.a;return p=p<<25^p>>>7^h,h=h-f|0,f=f<<24^f>>>8^m,m=m-p|0,c.b=p=p<<20^p>>>12^h,c.c=h=h-f|0,c.d=f<<16^h>>>16^m,c.a=m-p|0},c.a=0,c.b=0,c.c=2654435769|0,c.d=1367130551,l===Math.floor(l)?(c.a=l/4294967296|0,c.b=l|0):u+=l;for(var d=0;d>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(typeof d=="object"&&o(d,u),p.state=function(){return o(u,{})}),p}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.tychei=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),zN=ts({"(disabled):crypto"(){}}),LN=ts({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/seedrandom.js"(e,t){(function(n,s,r){var a=256,o=6,i=52,l="random",c=r.pow(a,o),u=r.pow(2,i),d=u*2,p=a-1,h;function f(w,k,S){var E=[];k=k==!0?{entropy:!0}:k||{};var P=y(A(k.entropy?[w,b(s)]:w==null?x():w,3),E),F=new m(E),R=function(){for(var _=F.g(o),T=c,M=0;_=d;)_/=2,T/=2,M>>>=1;return(_+M)/T};return R.int32=function(){return F.g(4)|0},R.quick=function(){return F.g(4)/4294967296},R.double=R,y(b(F.S),s),(k.pass||S||function(_,T,M,U){return U&&(U.S&&g(U,F),_.state=function(){return g(F,{})}),M?(r[l]=_,T):_})(R,P,"global"in k?k.global:this==r,k.state)}function m(w){var k,S=w.length,E=this,P=0,F=E.i=E.j=0,R=E.S=[];for(S||(w=[S++]);P1&&(g=process.argv[1].replace(/\\/g,"/")),m=process.argv.slice(2),process.on("uncaughtException",function(C){if(!(C instanceof Nc))throw C}),process.on("unhandledRejection",Wr),A=function(C){process.exit(C)},u.inspect=function(){return"[Emscripten Module object]"};var U;try{U=Ws("worker_threads")}catch(C){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),C}global.Worker=U.Worker}else w?(typeof read!="undefined"&&(P=function($){return read($)}),R=function($){var L;return typeof readbuffer=="function"?new Uint8Array(readbuffer($)):(L=read($,"binary"),we(typeof L=="object"),L)},typeof scriptArgs!="undefined"?m=scriptArgs:typeof arguments!="undefined"&&(m=arguments),typeof quit=="function"&&(A=function(C){quit(C)}),typeof print!="undefined"&&(typeof console=="undefined"&&(console={}),console.log=print,console.warn=console.error=typeof printErr!="undefined"?printErr:print)):(y||x)&&(x?S=self.location.href:typeof document!="undefined"&&document.currentScript&&(S=document.currentScript.src),typeof s!="undefined"&&s&&(S=s),S.indexOf("blob:")!==0?S=S.substr(0,S.lastIndexOf("/")+1):S="",b?(P=function($,L){return T||(T=Ws("fs")),M||(M=Ws("path")),$=M.normalize($),T.readFileSync($,L?null:"utf8")},R=function($){var L=P($,!0);return L.buffer||(L=new Uint8Array(L)),we(L.buffer),L}):(P=function(C){var $=new XMLHttpRequest;return $.open("GET",C,!1),$.send(null),$.responseText},x&&(R=function(C){var $=new XMLHttpRequest;return $.open("GET",C,!1),$.responseType="arraybuffer",$.send(null),new Uint8Array($.response)}),F=function(C,$,L){var Z=new XMLHttpRequest;Z.open("GET",C,!0),Z.responseType="arraybuffer",Z.onload=function(){if(Z.status==200||Z.status==0&&Z.response){$(Z.response);return}L()},Z.onerror=L,Z.send(null)}),_=function(C){document.title=C});b&&typeof performance=="undefined"&&(global.performance=Ws("perf_hooks").performance);var H=u.print||console.log.bind(console),z=u.printErr||console.warn.bind(console);for(f in h)h.hasOwnProperty(f)&&(u[f]=h[f]);h=null,u.arguments&&(m=u.arguments),u.thisProgram&&(g=u.thisProgram),u.quit&&(A=u.quit);function X(C){X.shown||(X.shown={}),X.shown[C]||(X.shown[C]=1,z(C))}var ee=Atomics.load,Y=Atomics.store,se=Atomics.compareExchange,ne;u.wasmBinary&&(ne=u.wasmBinary);var J=u.noExitRuntime||!0;typeof WebAssembly!="object"&&Wr("no native wasm support detected");var te,ue,ce=!1,xe;function we(C,$){C||Wr("Assertion failed: "+$)}function Ce(C){var $=u["_"+C];return we($,"Cannot call unknown function "+C+", make sure it is exported"),$}function Oe(C,$,L,Z,ge){var fe={string:function(Mn){var Ml=0;if(Mn!=null&&Mn!==0){var Jb=(Mn.length<<2)+1;Ml=Pl(Jb),ut(Mn,Ml,Jb)}return Ml},array:function(Mn){var Ml=Pl(Mn.length);return At(Mn,Ml),Ml}};function me(Mn){return $==="string"?rt(Mn):$==="boolean"?Boolean(Mn):Mn}var Te=Ce(C),ht=[],fn=0;if(Z)for(var nn=0;nn=Z);){var fe=C[$++];if(!fe)return ge;if(!(fe&128)){ge+=String.fromCharCode(fe);continue}var me=C[$++]&63;if((fe&224)==192){ge+=String.fromCharCode((fe&31)<<6|me);continue}var Te=C[$++]&63;if((fe&240)==224?fe=(fe&15)<<12|me<<6|Te:fe=(fe&7)<<18|me<<12|Te<<6|C[$++]&63,fe<65536)ge+=String.fromCharCode(fe);else{var ht=fe-65536;ge+=String.fromCharCode(55296|ht>>10,56320|ht&1023)}}return ge}function rt(C,$){return C?Xe(o(),C,$):""}function ft(C,$,L,Z){if(!(Z>0))return 0;for(var ge=L,fe=L+Z-1,me=0;me=55296&&Te<=57343){var ht=C.charCodeAt(++me);Te=65536+((Te&1023)<<10)|ht&1023}if(Te<=127){if(L>=fe)break;$[L++]=Te}else if(Te<=2047){if(L+1>=fe)break;$[L++]=192|Te>>6,$[L++]=128|Te&63}else if(Te<=65535){if(L+2>=fe)break;$[L++]=224|Te>>12,$[L++]=128|Te>>6&63,$[L++]=128|Te&63}else{if(L+3>=fe)break;$[L++]=240|Te>>18,$[L++]=128|Te>>12&63,$[L++]=128|Te>>6&63,$[L++]=128|Te&63}}return $[L]=0,L-ge}function ut(C,$,L){return ft(C,o(),$,L)}function ct(C){for(var $=0,L=0;L=55296&&Z<=57343&&(Z=65536+((Z&1023)<<10)|C.charCodeAt(++L)&1023),Z<=127?++$:Z<=2047?$+=2:Z<=65535?$+=3:$+=4}return $}function At(C,$){a().set(C,$)}function yt(C,$){return C%$>0&&(C+=$-C%$),C}var Et,Pt,Jn,wn,nr,On,ds,Ls,Is;function kn(C){Et=C,u.HEAP8=Pt=new Int8Array(C),u.HEAP16=wn=new Int16Array(C),u.HEAP32=On=new Int32Array(C),u.HEAPU8=Jn=new Uint8Array(C),u.HEAPU16=nr=new Uint16Array(C),u.HEAPU32=ds=new Uint32Array(C),u.HEAPF32=Ls=new Float32Array(C),u.HEAPF64=Is=new Float64Array(C)}var br=u.INITIAL_MEMORY||16777216;if(k)te=u.wasmMemory,Et=u.buffer;else if(u.wasmMemory)te=u.wasmMemory;else if(te=new WebAssembly.Memory({initial:br/65536,maximum:2147483648/65536,shared:!0}),!(te.buffer instanceof SharedArrayBuffer))throw z("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),b&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");te&&(Et=te.buffer),br=Et.byteLength,kn(Et);var Rn,vr=[],wr=[],pa=[],Ac=[],sr=[],wp=!1,f0=!1;k||wr.push({func:function(){Bp()}});function kp(){if(!k){if(u.preRun)for(typeof u.preRun=="function"&&(u.preRun=[u.preRun]);u.preRun.length;)m0(u.preRun.shift());Rl(vr)}}function Ip(){wp=!0,!k&&Rl(wr)}function Sp(){k||Rl(pa)}function Qn(){k||(f0=!0)}function Cp(){if(!k){if(u.postRun)for(typeof u.postRun=="function"&&(u.postRun=[u.postRun]);u.postRun.length;)g0(u.postRun.shift());Rl(sr)}}function m0(C){vr.unshift(C)}function g0(C){sr.unshift(C)}var Bs=0,yc=null,Xo=null;function A0(C){we(!k,"addRunDependency cannot be used in a pthread worker"),Bs++,u.monitorRunDependencies&&u.monitorRunDependencies(Bs)}function y0(C){if(Bs--,u.monitorRunDependencies&&u.monitorRunDependencies(Bs),Bs==0&&(yc!==null&&(clearInterval(yc),yc=null),Xo)){var $=Xo;Xo=null,$()}}u.preloadedImages={},u.preloadedAudios={};function Wr(C){u.onAbort&&u.onAbort(C),k&&console.error("Pthread aborting at "+new Error().stack),C+="",z(C),ce=!0,xe=1,C="abort("+C+"). Build with -s ASSERTIONS=1 for more info.";var $=new WebAssembly.RuntimeError(C);throw p($),$}function Ko(C,$){return String.prototype.startsWith?C.startsWith($):C.indexOf($)===0}var x0="data:application/octet-stream;base64,";function Tp(C){return Ko(C,x0)}var b0="file://";function Np(C){return Ko(C,b0)}var es="tfjs-backend-wasm-threaded-simd.wasm";Tp(es)||(es=E(es));function v0(C){try{if(C==es&&ne)return new Uint8Array(ne);if(R)return R(C);throw"both async and sync fetching of the wasm failed"}catch($){Wr($)}}function Ep(){if(!ne&&(y||x)){if(typeof fetch=="function"&&!Np(es))return fetch(es,{credentials:"same-origin"}).then(function(C){if(!C.ok)throw"failed to load wasm binary file at '"+es+"'";return C.arrayBuffer()}).catch(function(){return v0(es)});if(F)return new Promise(function(C,$){F(es,function(L){C(new Uint8Array(L))},$)})}return Promise.resolve().then(function(){return v0(es)})}function w0(){var C={a:fg};function $(me,Te){var ht=me.exports;if(u.asm=ht,Rn=u.asm.kb,ue=Te,!k){var fn=Re.unusedWorkers.length;Re.unusedWorkers.forEach(function(nn){Re.loadWasmModuleToWorker(nn,function(){--fn||y0("wasm-instantiate")})})}}k||A0("wasm-instantiate");function L(me){$(me.instance,me.module)}function Z(me){return Ep().then(function(Te){return WebAssembly.instantiate(Te,C)}).then(me,function(Te){z("failed to asynchronously prepare wasm: "+Te),Wr(Te)})}function ge(){return!ne&&typeof WebAssembly.instantiateStreaming=="function"&&!Tp(es)&&!Np(es)&&typeof fetch=="function"?fetch(es,{credentials:"same-origin"}).then(function(me){var Te=WebAssembly.instantiateStreaming(me,C);return Te.then(L,function(ht){return z("wasm streaming compile failed: "+ht),z("falling back to ArrayBuffer instantiation"),Z(L)})}):Z(L)}if(u.instantiateWasm)try{var fe=u.instantiateWasm(C,$);return fe}catch(me){return z("Module.instantiateWasm callback failed with error: "+me),!1}return ge().catch(p),{}}var Rp={10072:function(){throw"Canceled!"},10090:function(C,$){setTimeout(function(){jb(C,$)},0)}};function k0(){Re.initRuntime()}function Rl(C){for(;C.length>0;){var $=C.shift();if(typeof $=="function"){$(u);continue}var L=$.func;typeof L=="number"?$.arg===void 0?Rn.get(L)():Rn.get(L)($.arg):L($.arg===void 0?null:$.arg)}}var ha={EPERM:63,ENOENT:44,ESRCH:71,EINTR:27,EIO:29,ENXIO:60,E2BIG:1,ENOEXEC:45,EBADF:8,ECHILD:12,EAGAIN:6,EWOULDBLOCK:6,ENOMEM:48,EACCES:2,EFAULT:21,ENOTBLK:105,EBUSY:10,EEXIST:20,EXDEV:75,ENODEV:43,ENOTDIR:54,EISDIR:31,EINVAL:28,ENFILE:41,EMFILE:33,ENOTTY:59,ETXTBSY:74,EFBIG:22,ENOSPC:51,ESPIPE:70,EROFS:69,EMLINK:34,EPIPE:64,EDOM:18,ERANGE:68,ENOMSG:49,EIDRM:24,ECHRNG:106,EL2NSYNC:156,EL3HLT:107,EL3RST:108,ELNRNG:109,EUNATCH:110,ENOCSI:111,EL2HLT:112,EDEADLK:16,ENOLCK:46,EBADE:113,EBADR:114,EXFULL:115,ENOANO:104,EBADRQC:103,EBADSLT:102,EDEADLOCK:16,EBFONT:101,ENOSTR:100,ENODATA:116,ETIME:117,ENOSR:118,ENONET:119,ENOPKG:120,EREMOTE:121,ENOLINK:47,EADV:122,ESRMNT:123,ECOMM:124,EPROTO:65,EMULTIHOP:36,EDOTDOT:125,EBADMSG:9,ENOTUNIQ:126,EBADFD:127,EREMCHG:128,ELIBACC:129,ELIBBAD:130,ELIBSCN:131,ELIBMAX:132,ELIBEXEC:133,ENOSYS:52,ENOTEMPTY:55,ENAMETOOLONG:37,ELOOP:32,EOPNOTSUPP:138,EPFNOSUPPORT:139,ECONNRESET:15,ENOBUFS:42,EAFNOSUPPORT:5,EPROTOTYPE:67,ENOTSOCK:57,ENOPROTOOPT:50,ESHUTDOWN:140,ECONNREFUSED:14,EADDRINUSE:3,ECONNABORTED:13,ENETUNREACH:40,ENETDOWN:38,ETIMEDOUT:73,EHOSTDOWN:142,EHOSTUNREACH:23,EINPROGRESS:26,EALREADY:7,EDESTADDRREQ:17,EMSGSIZE:35,EPROTONOSUPPORT:66,ESOCKTNOSUPPORT:137,EADDRNOTAVAIL:4,ENETRESET:39,EISCONN:30,ENOTCONN:53,ETOOMANYREFS:141,EUSERS:136,EDQUOT:19,ESTALE:72,ENOTSUP:138,ENOMEDIUM:148,EILSEQ:25,EOVERFLOW:61,ECANCELED:11,ENOTRECOVERABLE:56,EOWNERDEAD:62,ESTRPIPE:135};function xc(C,$){if(C<=0||C>a().length||C&!0||$<0)return-28;if($==0)return 0;$>=2147483647&&($=1/0);var L=Atomics.load(i(),Fl>>2),Z=0;if(L==C){var ge=Atomics.compareExchange(i(),Fl>>2,L,0);if(ge==L&&(--$,Z=1,$<=0))return 1}var fe=Atomics.notify(i(),C>>2,$);if(fe>=0)return fe+Z;throw"Atomics.notify returned an unexpected value "+fe}u._emscripten_futex_wake=xc;function I0(C){if(k)throw"Internal Error! killThread() can only ever be called from main application thread!";if(!C)throw"Internal Error! Null pthread_ptr in killThread!";i()[C+12>>2]=0;var $=Re.pthreads[C];$.worker.terminate(),Re.freeThreadData($),Re.runningWorkers.splice(Re.runningWorkers.indexOf($.worker),1),$.worker.pthread=void 0}function S0(C){if(k)throw"Internal Error! cancelThread() can only ever be called from main application thread!";if(!C)throw"Internal Error! Null pthread_ptr in cancelThread!";var $=Re.pthreads[C];$.worker.postMessage({cmd:"cancel"})}function $p(C){if(k)throw"Internal Error! cleanupThread() can only ever be called from main application thread!";if(!C)throw"Internal Error! Null pthread_ptr in cleanupThread!";var $=Re.pthreads[C];if($){i()[C+12>>2]=0;var L=$.worker;Re.returnWorkerToPool(L)}}var Re={unusedWorkers:[],runningWorkers:[],initMainThreadBlock:function(){for(var C=8,$=0;$>2]=C;var L=C+152;i()[L>>2]=L;for(var Z=Yo(512),$=0;$<128;++$)l()[Z/4+$]=0;Atomics.store(l(),C+100>>2,Z),Atomics.store(l(),C+40>>2,C),Pg(C,!x,1),Gb(C)},initWorker:function(){},pthreads:{},threadExitHandlers:[],setThreadStatus:function(){},runExitHandlers:function(){for(;Re.threadExitHandlers.length>0;)Re.threadExitHandlers.pop()();k&&Aa()&&Ub()},runExitHandlersAndDeinitThread:function(C,$){Atomics.store(l(),C+56>>2,1),Atomics.store(l(),C+60>>2,0),Re.runExitHandlers(),Atomics.store(l(),C+4>>2,$),Atomics.store(l(),C+0>>2,1),xc(C+0,2147483647),Pg(0,0,0)},threadExit:function(C){var $=Aa();$&&(Re.runExitHandlersAndDeinitThread($,C),k&&postMessage({cmd:"exit"}))},threadCancel:function(){Re.runExitHandlersAndDeinitThread(Aa(),-1),postMessage({cmd:"cancelDone"})},terminateAllThreads:function(){for(var C in Re.pthreads){var $=Re.pthreads[C];$&&$.worker&&Re.returnWorkerToPool($.worker)}Re.pthreads={};for(var L=0;L>2];i()[C.threadInfoStruct+100>>2]=0,Cc($),Cc(C.threadInfoStruct)}C.threadInfoStruct=0,C.allocatedOwnStack&&C.stackBase&&Cc(C.stackBase),C.stackBase=0,C.worker&&(C.worker.pthread=null)}},returnWorkerToPool:function(C){Re.runWithoutMainThreadQueuedCalls(function(){delete Re.pthreads[C.pthread.threadInfoStruct],Re.unusedWorkers.push(C),Re.runningWorkers.splice(Re.runningWorkers.indexOf(C),1),Re.freeThreadData(C.pthread),C.pthread=void 0})},runWithoutMainThreadQueuedCalls:function(C){i()[Yb>>2]=0;try{C()}finally{i()[Yb>>2]=1}},receiveObjectTransfer:function(C){},loadWasmModuleToWorker:function(C,$){C.onmessage=function(L){var Z=L.data,ge=Z.cmd;if(C.pthread&&(Re.currentProxiedOperationCallerThread=C.pthread.threadInfoStruct),Z.targetThread&&Z.targetThread!=Aa()){var fe=Re.pthreads[Z.targetThread];fe?fe.worker.postMessage(L.data,Z.transferList):console.error('Internal error! Worker sent a message "'+ge+'" to target pthread '+Z.targetThread+", but that thread no longer exists!"),Re.currentProxiedOperationCallerThread=void 0;return}if(ge==="processQueuedMainThreadWork")Hp();else if(ge==="spawnThread")zp(L.data);else if(ge==="cleanupThread")$p(Z.thread);else if(ge==="killThread")I0(Z.thread);else if(ge==="cancelThread")S0(Z.thread);else if(ge==="loaded")C.loaded=!0,$&&$(C),C.runPthread&&(C.runPthread(),delete C.runPthread);else if(ge==="print")H("Thread "+Z.threadId+": "+Z.text);else if(ge==="printErr")z("Thread "+Z.threadId+": "+Z.text);else if(ge==="alert")alert("Thread "+Z.threadId+": "+Z.text);else if(ge==="exit"){var me=C.pthread&&Atomics.load(l(),C.pthread.threadInfoStruct+64>>2);me&&Re.returnWorkerToPool(C)}else if(ge==="exitProcess")try{bN(Z.returnCode)}catch(Te){if(Te instanceof Nc)return;throw Te}else ge==="cancelDone"?Re.returnWorkerToPool(C):ge==="objectTransfer"?Re.receiveObjectTransfer(L.data):L.data.target==="setimmediate"?C.postMessage(L.data):z("worker sent an unknown command "+ge);Re.currentProxiedOperationCallerThread=void 0},C.onerror=function(L){z("pthread sent an error! "+L.filename+":"+L.lineno+": "+L.message)},b&&(C.on("message",function(L){C.onmessage({data:L})}),C.on("error",function(L){C.onerror(L)}),C.on("exit",function(L){})),C.postMessage({cmd:"load",urlOrBlob:u.mainScriptUrlOrBlob||s,wasmMemory:te,wasmModule:ue})},allocateUnusedWorker:function(){var C=E("tfjs-backend-wasm-threaded-simd.worker.js");Re.unusedWorkers.push(new Worker(C))},getNewWorker:function(){return Re.unusedWorkers.length==0&&(Re.allocateUnusedWorker(),Re.loadWasmModuleToWorker(Re.unusedWorkers[0])),Re.unusedWorkers.length>0?Re.unusedWorkers.pop():null},busySpinWait:function(C){for(var $=performance.now()+C;performance.now()<$;);}};function C0(C,$){Kb(C,$),_l(C)}u.establishStackSpace=C0;function T0(){return J}u.getNoExitRuntime=T0;function N0(C,$){return Rn.get(C)($)}u.invokeEntryPoint=N0;function E0(C,$,L,Z){Wr("Assertion failed: "+rt(C)+", at: "+[$?rt($):"unknown filename",L,Z?rt(Z):"unknown function"])}function R0(C,$){var L=_main(C,$)}var Zo;b?Zo=function(){var C=process.hrtime();return C[0]*1e3+C[1]/1e6}:k?Zo=function(){return performance.now()-u.__performance_now_clock_drift}:typeof dateNow!="undefined"?Zo=dateNow:Zo=function(){return performance.now()};function $0(C){return i()[Wb()>>2]=C,C}function D0(C,$){if(k)return fa(1,1,C,$)}function _0(C,$){if(C==$)postMessage({cmd:"processQueuedMainThreadWork"});else if(k)postMessage({targetThread:C,cmd:"processThreadQueue"});else{var L=Re.pthreads[C],Z=L&&L.worker;if(!Z)return;Z.postMessage({cmd:"processThreadQueue"})}return 1}function P0(){Wr()}function F0(C,$,L){var Z=L0($,L);return Rp[C].apply(null,Z)}function O0(C,$){}function Dp(C,$,L){if(C<=0||C>a().length||C&!0)return-28;if(y){if(Atomics.load(i(),C>>2)!=$)return-6;for(var ge=performance.now(),fe=ge+L,me=Atomics.exchange(i(),Fl>>2,C);;){if(ge=performance.now(),ge>fe)return me=Atomics.exchange(i(),Fl>>2,0),-73;if(me=Atomics.exchange(i(),Fl>>2,0),me==0)break;if(Hp(),Atomics.load(i(),C>>2)!=$)return-6;me=Atomics.exchange(i(),Fl>>2,C)}return 0}else{var Z=Atomics.wait(i(),C>>2,$,L);if(Z==="timed-out")return-73;if(Z==="not-equal")return-6;if(Z==="ok")return 0;throw"Atomics.wait returned an unexpected value "+Z}}function M0(C,$,L){o().copyWithin(C,$,$+L)}function z0(){return b?Ws("os").cpus().length:navigator.hardwareConcurrency}function fa(C,$){for(var L=arguments.length-2,Z=Tc(),ge=L,fe=Pl(ge*8),me=fe>>3,Te=0;Te>=2;L=o()[C++];){var Z=L<105;Z&&$&1&&$++,vc.push(Z?c()[$++>>1]:i()[$]),++$}return vc}function B0(C,$,L){bc.length=$;for(var Z=L>>3,ge=0;ge<$;ge++)bc[ge]=c()[Z+ge];var fe=C<0,me=fe?Rp[-C-1]:hg[C];return me.apply(null,bc)}function W0(){return o().length}function V0(C){try{return te.grow(C-Et.byteLength+65535>>>16),kn(te.buffer),1}catch($){}}function U0(C){var $=W0();if(C<=$)return!1;var L=2147483648;if(C>L)return!1;for(var Z=1;Z<=4;Z*=2){var ge=$*(1+.2/Z);ge=Math.min(ge,C+100663296);var fe=Math.min(L,yt(Math.max(C,ge),65536)),me=V0(fe);if(me)return!0}return!1}var Ge={inEventHandler:0,removeAllEventListeners:function(){for(var C=Ge.eventHandlers.length-1;C>=0;--C)Ge._removeHandler(C);Ge.eventHandlers=[],Ge.deferredCalls=[]},registerRemoveEventListeners:function(){Ge.removeEventListenersRegistered||(Ac.push(Ge.removeAllEventListeners),Ge.removeEventListenersRegistered=!0)},deferredCalls:[],deferCall:function(C,$,L){function Z(me,Te){if(me.length!=Te.length)return!1;for(var ht in me)if(me[ht]!=Te[ht])return!1;return!0}for(var ge in Ge.deferredCalls){var fe=Ge.deferredCalls[ge];if(fe.targetFunction==C&&Z(fe.argsList,L))return}Ge.deferredCalls.push({targetFunction:C,precedence:$,argsList:L}),Ge.deferredCalls.sort(function(me,Te){return me.precedence>2]=L,i()[me+4>>2]=Z,i()[me+8>>2]=ge,_g(0,C,637534208,$,Z,me),_l(fe)},getTargetThreadForEventCallback:function(C){switch(C){case 1:return 0;case 2:return Re.currentProxiedOperationCallerThread;default:return C}},getNodeNameForTarget:function(C){return C?C==window?"#window":C==screen?"#screen":C&&C.nodeName?C.nodeName:"":""},fullscreenEnabled:function(){return document.fullscreenEnabled||document.webkitFullscreenEnabled}};function G0(C){var $=ct(C)+1,L=Yo($);return ut(C,L,$),L}function H0(C,$,L,Z){var ge=Tc(),fe=Pl(12),me=0;$&&(me=G0($)),i()[fe>>2]=me,i()[fe+4>>2]=L,i()[fe+8>>2]=Z,_g(0,C,657457152,0,me,fe),_l(ge)}function j0(C,$,L,Z){$=$?rt($):"",H0(C,$,L,Z)}function q0(C){return C>2?rt(C):C}var X0=[0,typeof document!="undefined"?document:0,typeof window!="undefined"?window:0];function K0(C){C=q0(C);var $=X0[C]||(typeof document!="undefined"?document.querySelector(C):void 0);return $}function wc(C){return K0(C)}function _p(C,$,L){var Z=wc(C);if(!Z)return-4;if(Z.canvasSharedPtr&&(i()[Z.canvasSharedPtr>>2]=$,i()[Z.canvasSharedPtr+4>>2]=L),Z.offscreenCanvas||!Z.controlTransferredOffscreen){Z.offscreenCanvas&&(Z=Z.offscreenCanvas);var ge=!1;if(Z.GLctxObject&&Z.GLctxObject.GLctx){var fe=Z.GLctxObject.GLctx.getParameter(2978);ge=fe[0]===0&&fe[1]===0&&fe[2]===Z.width&&fe[3]===Z.height}Z.width=$,Z.height=L,ge&&Z.GLctxObject.GLctx.viewport(0,0,$,L)}else if(Z.canvasSharedPtr){var me=i()[Z.canvasSharedPtr+8>>2];return j0(me,C,$,L),1}else return-4;return 0}function Pp(C,$,L){return k?fa(2,1,C,$,L):_p(C,$,L)}function Z0(C,$,L){var Z=wc(C);return Z?_p(C,$,L):Pp(C,$,L)}function Y0(C){}function J0(C,$){}function Q0(C){var $=C.getExtension("ANGLE_instanced_arrays");if($)return C.vertexAttribDivisor=function(L,Z){$.vertexAttribDivisorANGLE(L,Z)},C.drawArraysInstanced=function(L,Z,ge,fe){$.drawArraysInstancedANGLE(L,Z,ge,fe)},C.drawElementsInstanced=function(L,Z,ge,fe,me){$.drawElementsInstancedANGLE(L,Z,ge,fe,me)},1}function eg(C){var $=C.getExtension("OES_vertex_array_object");if($)return C.createVertexArray=function(){return $.createVertexArrayOES()},C.deleteVertexArray=function(L){$.deleteVertexArrayOES(L)},C.bindVertexArray=function(L){$.bindVertexArrayOES(L)},C.isVertexArray=function(L){return $.isVertexArrayOES(L)},1}function tg(C){var $=C.getExtension("WEBGL_draw_buffers");if($)return C.drawBuffers=function(L,Z){$.drawBuffersWEBGL(L,Z)},1}function ng(C){return!!(C.multiDrawWebgl=C.getExtension("WEBGL_multi_draw"))}var dt={counter:1,buffers:[],programs:[],framebuffers:[],renderbuffers:[],textures:[],uniforms:[],shaders:[],vaos:[],contexts:{},offscreenCanvases:{},timerQueriesEXT:[],programInfos:{},stringCache:{},unpackAlignment:4,recordError:function($){dt.lastError||(dt.lastError=$)},getNewId:function(C){for(var $=dt.counter++,L=C.length;L<$;L++)C[L]=null;return $},getSource:function(C,$,L,Z){for(var ge="",fe=0;fe<$;++fe){var me=Z?i()[Z+fe*4>>2]:-1;ge+=rt(i()[L+fe*4>>2],me<0?void 0:me)}return ge},createContext:function(C,$){var L=C.getContext("webgl",$);if(!L)return 0;var Z=dt.registerContext(L,$);return Z},registerContext:function(C,$){var L=Yo(8);i()[L+4>>2]=Aa();var Z={handle:L,attributes:$,version:$.majorVersion,GLctx:C};return C.canvas&&(C.canvas.GLctxObject=Z),dt.contexts[L]=Z,(typeof $.enableExtensionsByDefault=="undefined"||$.enableExtensionsByDefault)&&dt.initExtensions(Z),L},makeContextCurrent:function(C){return dt.currentContext=dt.contexts[C],u.ctx=ma=dt.currentContext&&dt.currentContext.GLctx,!(C&&!ma)},getContext:function(C){return dt.contexts[C]},deleteContext:function(C){dt.currentContext===dt.contexts[C]&&(dt.currentContext=null),typeof Ge=="object"&&Ge.removeAllHandlersOnTarget(dt.contexts[C].GLctx.canvas),dt.contexts[C]&&dt.contexts[C].GLctx.canvas&&(dt.contexts[C].GLctx.canvas.GLctxObject=void 0),Cc(dt.contexts[C].handle),dt.contexts[C]=null},initExtensions:function(C){if(C||(C=dt.currentContext),!C.initExtensionsDone){C.initExtensionsDone=!0;var $=C.GLctx;Q0($),eg($),tg($),$.disjointTimerQueryExt=$.getExtension("EXT_disjoint_timer_query"),ng($);var L=$.getSupportedExtensions()||[];L.forEach(function(Z){Z.indexOf("lose_context")<0&&Z.indexOf("debug")<0&&$.getExtension(Z)})}},populateUniformTable:function(C){for(var $=dt.programs[C],L=dt.programInfos[C]={uniforms:{},maxUniformLength:0,maxAttributeLength:-1,maxUniformBlockNameLength:-1},Z=L.uniforms,ge=ma.getProgramParameter($,35718),fe=0;fe>2,Z=i()[L+(24>>2)],ge={alpha:!!i()[L+(0>>2)],depth:!!i()[L+(4>>2)],stencil:!!i()[L+(8>>2)],antialias:!!i()[L+(12>>2)],premultipliedAlpha:!!i()[L+(16>>2)],preserveDrawingBuffer:!!i()[L+(20>>2)],powerPreference:sg[Z],failIfMajorPerformanceCaveat:!!i()[L+(28>>2)],majorVersion:i()[L+(32>>2)],minorVersion:i()[L+(36>>2)],enableExtensionsByDefault:i()[L+(40>>2)],explicitSwapControl:i()[L+(44>>2)],proxyContextToMainThread:i()[L+(48>>2)],renderViaOffscreenBackBuffer:i()[L+(52>>2)]},fe=wc(C);if(!fe||ge.explicitSwapControl)return 0;var me=dt.createContext(fe,ge);return me}function ag(C,$){return rg(C,$)}var $l={mappings:{},buffers:[null,[],[]],printChar:function(C,$){var L=$l.buffers[C];$===0||$===10?((C===1?H:z)(Xe(L,0)),L.length=0):L.push($)},varargs:void 0,get:function(){$l.varargs+=4;var C=i()[$l.varargs-4>>2];return C},getStr:function(C){var $=rt(C);return $},get64:function(C,$){return C}};function Fp(C){return k?fa(3,1,C):0}function Op(C,$,L,Z,ge){if(k)return fa(4,1,C,$,L,Z,ge)}function Mp(C,$,L,Z){if(k)return fa(5,1,C,$,L,Z);for(var ge=0,fe=0;fe>2],Te=i()[$+(fe*8+4)>>2],ht=0;ht>2]=ge,0}function og(C){var $=Re.threadExitHandlers.pop();C&&$()}function ig(C,$){Re.threadExitHandlers.push(function(){Rn.get(C)($)})}function zp(C){if(k)throw"Internal Error! spawnThread() can only ever be called from main application thread!";var $=Re.getNewWorker();if($.pthread!==void 0)throw"Internal error!";if(!C.pthread_ptr)throw"Internal error, no pthread ptr!";Re.runningWorkers.push($);for(var L=Yo(128*4),Z=0;Z<128;++Z)i()[L+Z*4>>2]=0;var ge=C.stackBase+C.stackSize,fe=Re.pthreads[C.pthread_ptr]={worker:$,stackBase:C.stackBase,stackSize:C.stackSize,allocatedOwnStack:C.allocatedOwnStack,threadInfoStruct:C.pthread_ptr},me=fe.threadInfoStruct>>2;Atomics.store(l(),me+(64>>2),C.detached),Atomics.store(l(),me+(100>>2),L),Atomics.store(l(),me+(40>>2),fe.threadInfoStruct),Atomics.store(l(),me+(80>>2),C.stackSize),Atomics.store(l(),me+(76>>2),ge),Atomics.store(l(),me+(104>>2),C.stackSize),Atomics.store(l(),me+(104+8>>2),ge),Atomics.store(l(),me+(104+12>>2),C.detached);var Te=Vb(),ht=Te+40;Atomics.store(l(),me+(172>>2),ht),$.pthread=fe;var fn={cmd:"run",start_routine:C.startRoutine,arg:C.arg,threadInfoStruct:C.pthread_ptr,stackBase:C.stackBase,stackSize:C.stackSize};$.runPthread=function(){fn.time=performance.now(),$.postMessage(fn,C.transferList)},$.loaded&&($.runPthread(),delete $.runPthread)}function lg(C,$,L,Z){if(typeof SharedArrayBuffer=="undefined")return z("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;if(!C)return z("pthread_create called with a null thread pointer!"),28;var ge=[],fe=0;if(k&&(ge.length===0||fe))return qb(687865856,C,$,L,Z);if(fe)return fe;var me=0,Te=0,ht=0;$&&$!=-1?(me=i()[$>>2],me+=81920,Te=i()[$+8>>2],ht=i()[$+12>>2]!==0):me=2097152;var fn=Te==0;fn?Te=Zb(16,me):(Te-=me,we(Te>0));for(var nn=Yo(228),ya=0;ya<228>>2;++ya)l()[(nn>>2)+ya]=0;i()[C>>2]=nn,i()[nn+12>>2]=nn;var Ol=nn+152;i()[Ol>>2]=Ol;var Mn={stackBase:Te,stackSize:me,allocatedOwnStack:fn,detached:ht,startRoutine:L,pthread_ptr:nn,arg:Z,transferList:ge};return k?(Mn.cmd="spawnThread",postMessage(Mn,ge)):zp(Mn),0}function ug(){if(!!k){var C=Aa();if(!!C){var $=Atomics.load(l(),C+56>>2);if(!$){var L=Atomics.load(l(),C+0>>2);if(L==2)throw"Canceled!"}}}}function cg(){b||x||X("Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread")}function dg(C,$,L){if(!C)return z("pthread_join attempted on a null thread pointer!"),ha.ESRCH;if(k&&Aa()==C)return z("PThread "+C+" is attempting to join to itself!"),ha.EDEADLK;if(!k&&Hb()==C)return z("Main thread "+C+" is attempting to join to itself!"),ha.EDEADLK;var Z=i()[C+12>>2];if(Z!==C)return z("pthread_join attempted on thread "+C+", which does not point to a valid thread, or does not exist anymore!"),ha.ESRCH;var ge=Atomics.load(l(),C+64>>2);if(ge)return z("Attempted to join thread "+C+", which was already detached!"),ha.EINVAL;for(L&&cg();;){var fe=Atomics.load(l(),C+0>>2);if(fe==1){var me=Atomics.load(l(),C+4>>2);return $&&(i()[$>>2]=me),Atomics.store(l(),C+64>>2,1),k?postMessage({cmd:"cleanupThread",thread:C}):$p(C),0}if(!L)return ha.EBUSY;ug(),k||Hp(),Dp(C+0,fe,k?100:1)}}function pg(C,$){return dg(C,$,!0)}function Lp(C){if(k)return fa(6,1,C);switch(C){case 30:return 16384;case 85:var $=2147483648;return $/16384;case 132:case 133:case 12:case 137:case 138:case 15:case 235:case 16:case 17:case 18:case 19:case 20:case 149:case 13:case 10:case 236:case 153:case 9:case 21:case 22:case 159:case 154:case 14:case 77:case 78:case 139:case 82:case 68:case 67:case 164:case 11:case 29:case 47:case 48:case 95:case 52:case 51:case 46:return 200809;case 27:case 246:case 127:case 128:case 23:case 24:case 160:case 161:case 181:case 182:case 242:case 183:case 184:case 243:case 244:case 245:case 165:case 178:case 179:case 49:case 50:case 168:case 169:case 175:case 170:case 171:case 172:case 97:case 76:case 32:case 173:case 35:case 80:case 81:case 79:return-1;case 176:case 177:case 7:case 155:case 8:case 157:case 125:case 126:case 92:case 93:case 129:case 130:case 131:case 94:case 91:return 1;case 74:case 60:case 69:case 70:case 4:return 1024;case 31:case 42:case 72:return 32;case 87:case 26:case 33:return 2147483647;case 34:case 1:return 47839;case 38:case 36:return 99;case 43:case 37:return 2048;case 0:return 2097152;case 3:return 65536;case 28:return 32768;case 44:return 32767;case 75:return 16384;case 39:return 1e3;case 89:return 700;case 71:return 256;case 40:return 255;case 2:return 100;case 180:return 64;case 25:return 20;case 5:return 16;case 6:return 6;case 73:return 4;case 84:return typeof navigator=="object"&&navigator.hardwareConcurrency||1}return $0(28),-1}k||Re.initMainThreadBlock();var ma,hg=[null,D0,Pp,Fp,Op,Mp,Lp],fg={e:E0,r:R0,x:_0,b:P0,y:F0,j:O0,d:Dp,c:xc,f:Zo,p:M0,A:z0,u:B0,q:U0,v:Z0,i:Y0,s:J0,w:ag,l:Fp,n:Op,g:Mp,o:k0,a:te||u.wasmMemory,z:og,k:ig,h:lg,m:pg,t:Lp},Bb=w0(),Bp=u.___wasm_call_ctors=function(){return(Bp=u.___wasm_call_ctors=u.asm.B).apply(null,arguments)},mg=u._init=function(){return(mg=u._init=u.asm.C).apply(null,arguments)},gg=u._init_with_threads_count=function(){return(gg=u._init_with_threads_count=u.asm.D).apply(null,arguments)},Ag=u._get_threads_count=function(){return(Ag=u._get_threads_count=u.asm.E).apply(null,arguments)},yg=u._register_tensor=function(){return(yg=u._register_tensor=u.asm.F).apply(null,arguments)},xg=u._dispose_data=function(){return(xg=u._dispose_data=u.asm.G).apply(null,arguments)},bg=u._dispose=function(){return(bg=u._dispose=u.asm.H).apply(null,arguments)},vg=u._Abs=function(){return(vg=u._Abs=u.asm.I).apply(null,arguments)},wg=u._Add=function(){return(wg=u._Add=u.asm.J).apply(null,arguments)},kg=u._AddN=function(){return(kg=u._AddN=u.asm.K).apply(null,arguments)},Ig=u._All=function(){return(Ig=u._All=u.asm.L).apply(null,arguments)},Sg=u._Any=function(){return(Sg=u._Any=u.asm.M).apply(null,arguments)},Cg=u._ArgMax=function(){return(Cg=u._ArgMax=u.asm.N).apply(null,arguments)},Tg=u._AvgPool=function(){return(Tg=u._AvgPool=u.asm.O).apply(null,arguments)},Ng=u._BatchMatMul=function(){return(Ng=u._BatchMatMul=u.asm.P).apply(null,arguments)},Eg=u._Ceil=function(){return(Eg=u._Ceil=u.asm.Q).apply(null,arguments)},Rg=u._ClipByValue=function(){return(Rg=u._ClipByValue=u.asm.R).apply(null,arguments)},$g=u._Conv2D=function(){return($g=u._Conv2D=u.asm.S).apply(null,arguments)},Wp=u._Conv2DBackpropInput=function(){return(Wp=u._Conv2DBackpropInput=u.asm.T).apply(null,arguments)},Vp=u._Cos=function(){return(Vp=u._Cos=u.asm.U).apply(null,arguments)},kc=u._Cosh=function(){return(kc=u._Cosh=u.asm.V).apply(null,arguments)},Dl=u._CropAndResize=function(){return(Dl=u._CropAndResize=u.asm.W).apply(null,arguments)},Dg=u._Cumsum=function(){return(Dg=u._Cumsum=u.asm.X).apply(null,arguments)},Ic=u._DepthToSpace=function(){return(Ic=u._DepthToSpace=u.asm.Y).apply(null,arguments)},re=u._DepthwiseConv2dNative=function(){return(re=u._DepthwiseConv2dNative=u.asm.Z).apply(null,arguments)},oe=u._Elu=function(){return(oe=u._Elu=u.asm._).apply(null,arguments)},ke=u._Equal=function(){return(ke=u._Equal=u.asm.$).apply(null,arguments)},it=u._Exp=function(){return(it=u._Exp=u.asm.aa).apply(null,arguments)},Lt=u._FlipLeftRight=function(){return(Lt=u._FlipLeftRight=u.asm.ba).apply(null,arguments)},Rt=u._Floor=function(){return(Rt=u._Floor=u.asm.ca).apply(null,arguments)},Je=u._FloorDiv=function(){return(Je=u._FloorDiv=u.asm.da).apply(null,arguments)},Qe=u._FusedBatchNorm=function(){return(Qe=u._FusedBatchNorm=u.asm.ea).apply(null,arguments)},In=u._FusedConv2D=function(){return(In=u._FusedConv2D=u.asm.fa).apply(null,arguments)},Vr=u._FusedDepthwiseConv2D=function(){return(Vr=u._FusedDepthwiseConv2D=u.asm.ga).apply(null,arguments)},Ur=u._Gather=function(){return(Ur=u._Gather=u.asm.ha).apply(null,arguments)},Up=u._GatherNd=function(){return(Up=u._GatherNd=u.asm.ia).apply(null,arguments)},Sc=u._Greater=function(){return(Sc=u._Greater=u.asm.ja).apply(null,arguments)},ps=u._GreaterEqual=function(){return(ps=u._GreaterEqual=u.asm.ka).apply(null,arguments)},ga=u._LeakyRelu=function(){return(ga=u._LeakyRelu=u.asm.la).apply(null,arguments)},Gp=u._Less=function(){return(Gp=u._Less=u.asm.ma).apply(null,arguments)},IT=u._LessEqual=function(){return(IT=u._LessEqual=u.asm.na).apply(null,arguments)},ST=u._Log=function(){return(ST=u._Log=u.asm.oa).apply(null,arguments)},CT=u._LogicalAnd=function(){return(CT=u._LogicalAnd=u.asm.pa).apply(null,arguments)},TT=u._Max=function(){return(TT=u._Max=u.asm.qa).apply(null,arguments)},NT=u._MaxPool=function(){return(NT=u._MaxPool=u.asm.ra).apply(null,arguments)},ET=u._Maximum=function(){return(ET=u._Maximum=u.asm.sa).apply(null,arguments)},RT=u._Mean=function(){return(RT=u._Mean=u.asm.ta).apply(null,arguments)},$T=u._Min=function(){return($T=u._Min=u.asm.ua).apply(null,arguments)},DT=u._Minimum=function(){return(DT=u._Minimum=u.asm.va).apply(null,arguments)},_T=u._MirrorPad=function(){return(_T=u._MirrorPad=u.asm.wa).apply(null,arguments)},PT=u._Multiply=function(){return(PT=u._Multiply=u.asm.xa).apply(null,arguments)},FT=u._Neg=function(){return(FT=u._Neg=u.asm.ya).apply(null,arguments)},OT=u._NonMaxSuppressionV3=function(){return(OT=u._NonMaxSuppressionV3=u.asm.za).apply(null,arguments)},MT=u._NonMaxSuppressionV4=function(){return(MT=u._NonMaxSuppressionV4=u.asm.Aa).apply(null,arguments)},zT=u._NonMaxSuppressionV5=function(){return(zT=u._NonMaxSuppressionV5=u.asm.Ba).apply(null,arguments)},LT=u._NotEqual=function(){return(LT=u._NotEqual=u.asm.Ca).apply(null,arguments)},BT=u._OneHot=function(){return(BT=u._OneHot=u.asm.Da).apply(null,arguments)},WT=u._PadV2=function(){return(WT=u._PadV2=u.asm.Ea).apply(null,arguments)},VT=u._Pow=function(){return(VT=u._Pow=u.asm.Fa).apply(null,arguments)},UT=u._Prelu=function(){return(UT=u._Prelu=u.asm.Ga).apply(null,arguments)},GT=u._Prod=function(){return(GT=u._Prod=u.asm.Ha).apply(null,arguments)},HT=u._RealDiv=function(){return(HT=u._RealDiv=u.asm.Ia).apply(null,arguments)},jT=u._Relu=function(){return(jT=u._Relu=u.asm.Ja).apply(null,arguments)},qT=u._Relu6=function(){return(qT=u._Relu6=u.asm.Ka).apply(null,arguments)},XT=u._ResizeBilinear=function(){return(XT=u._ResizeBilinear=u.asm.La).apply(null,arguments)},KT=u._Reverse=function(){return(KT=u._Reverse=u.asm.Ma).apply(null,arguments)},ZT=u._RotateWithOffset=function(){return(ZT=u._RotateWithOffset=u.asm.Na).apply(null,arguments)},YT=u._Round=function(){return(YT=u._Round=u.asm.Oa).apply(null,arguments)},JT=u._Rsqrt=function(){return(JT=u._Rsqrt=u.asm.Pa).apply(null,arguments)},QT=u._ScatterNd=function(){return(QT=u._ScatterNd=u.asm.Qa).apply(null,arguments)},eN=u._SelectV2=function(){return(eN=u._SelectV2=u.asm.Ra).apply(null,arguments)},tN=u._Sigmoid=function(){return(tN=u._Sigmoid=u.asm.Sa).apply(null,arguments)},nN=u._Sin=function(){return(nN=u._Sin=u.asm.Ta).apply(null,arguments)},sN=u._Softmax=function(){return(sN=u._Softmax=u.asm.Ua).apply(null,arguments)},rN=u._Sqrt=function(){return(rN=u._Sqrt=u.asm.Va).apply(null,arguments)},aN=u._Square=function(){return(aN=u._Square=u.asm.Wa).apply(null,arguments)},oN=u._SquaredDifference=function(){return(oN=u._SquaredDifference=u.asm.Xa).apply(null,arguments)},iN=u._Step=function(){return(iN=u._Step=u.asm.Ya).apply(null,arguments)},lN=u._StridedSlice=function(){return(lN=u._StridedSlice=u.asm.Za).apply(null,arguments)},uN=u._Sub=function(){return(uN=u._Sub=u.asm._a).apply(null,arguments)},cN=u._Sum=function(){return(cN=u._Sum=u.asm.$a).apply(null,arguments)},dN=u._Tan=function(){return(dN=u._Tan=u.asm.ab).apply(null,arguments)},pN=u._Tanh=function(){return(pN=u._Tanh=u.asm.bb).apply(null,arguments)},hN=u._Tile=function(){return(hN=u._Tile=u.asm.cb).apply(null,arguments)},fN=u._TopK=function(){return(fN=u._TopK=u.asm.db).apply(null,arguments)},mN=u._Transform=function(){return(mN=u._Transform=u.asm.eb).apply(null,arguments)},gN=u._Transpose=function(){return(gN=u._Transpose=u.asm.fb).apply(null,arguments)},AN=u.__FusedMatMul=function(){return(AN=u.__FusedMatMul=u.asm.gb).apply(null,arguments)},Yo=u._malloc=function(){return(Yo=u._malloc=u.asm.hb).apply(null,arguments)},Cc=u._free=function(){return(Cc=u._free=u.asm.ib).apply(null,arguments)},Wb=u.___errno_location=function(){return(Wb=u.___errno_location=u.asm.jb).apply(null,arguments)},Vb=u._emscripten_get_global_libc=function(){return(Vb=u._emscripten_get_global_libc=u.asm.lb).apply(null,arguments)},Aa=u._pthread_self=function(){return(Aa=u._pthread_self=u.asm.mb).apply(null,arguments)},Ub=u.___pthread_tsd_run_dtors=function(){return(Ub=u.___pthread_tsd_run_dtors=u.asm.nb).apply(null,arguments)},Hp=u._emscripten_main_thread_process_queued_calls=function(){return(Hp=u._emscripten_main_thread_process_queued_calls=u.asm.ob).apply(null,arguments)},yN=u._emscripten_current_thread_process_queued_calls=function(){return(yN=u._emscripten_current_thread_process_queued_calls=u.asm.pb).apply(null,arguments)},Gb=u._emscripten_register_main_browser_thread_id=function(){return(Gb=u._emscripten_register_main_browser_thread_id=u.asm.qb).apply(null,arguments)},Hb=u._emscripten_main_browser_thread_id=function(){return(Hb=u._emscripten_main_browser_thread_id=u.asm.rb).apply(null,arguments)},jb=u.__emscripten_do_dispatch_to_thread=function(){return(jb=u.__emscripten_do_dispatch_to_thread=u.asm.sb).apply(null,arguments)},qb=u._emscripten_sync_run_in_main_thread_4=function(){return(qb=u._emscripten_sync_run_in_main_thread_4=u.asm.tb).apply(null,arguments)},Xb=u._emscripten_run_in_main_runtime_thread_js=function(){return(Xb=u._emscripten_run_in_main_runtime_thread_js=u.asm.ub).apply(null,arguments)},_g=u.__emscripten_call_on_thread=function(){return(_g=u.__emscripten_call_on_thread=u.asm.vb).apply(null,arguments)},xN=u._emscripten_tls_init=function(){return(xN=u._emscripten_tls_init=u.asm.wb).apply(null,arguments)},Pg=u.__emscripten_thread_init=function(){return(Pg=u.__emscripten_thread_init=u.asm.xb).apply(null,arguments)},Tc=u.stackSave=function(){return(Tc=u.stackSave=u.asm.yb).apply(null,arguments)},_l=u.stackRestore=function(){return(_l=u.stackRestore=u.asm.zb).apply(null,arguments)},Pl=u.stackAlloc=function(){return(Pl=u.stackAlloc=u.asm.Ab).apply(null,arguments)},Kb=u._emscripten_stack_set_limits=function(){return(Kb=u._emscripten_stack_set_limits=u.asm.Bb).apply(null,arguments)},Zb=u._memalign=function(){return(Zb=u._memalign=u.asm.Cb).apply(null,arguments)},Yb=u.__emscripten_allow_main_runtime_queued_calls=10064,Fl=u.__emscripten_main_thread_futex=10268;u.cwrap=Ue,u.PThread=Re,u.PThread=Re,u.wasmMemory=te,u.ExitStatus=Nc;var jp;function Nc(C){this.name="ExitStatus",this.message="Program terminated with exit("+C+")",this.status=C}Xo=function C(){jp||Fg(),jp||(Xo=C)};function Fg(C){if(C=C||m,Bs>0)return;if(k){d(u),Ip(),postMessage({cmd:"loaded"});return}if(kp(),Bs>0)return;function $(){jp||(jp=!0,u.calledRun=!0,!ce&&(Ip(),Sp(),d(u),u.onRuntimeInitialized&&u.onRuntimeInitialized(),Cp()))}u.setStatus?(u.setStatus("Running..."),setTimeout(function(){setTimeout(function(){u.setStatus("")},1),$()},1)):$()}u.run=Fg;function bN(C,$){if(!($&&J&&C===0)){if(!$&&k)throw postMessage({cmd:"exitProcess",returnCode:C}),new Nc(C);J||(Re.terminateAllThreads(),xe=C,Qn(),u.onExit&&u.onExit(C),ce=!0),A(C,new Nc(C))}}if(u.preInit)for(typeof u.preInit=="function"&&(u.preInit=[u.preInit]);u.preInit.length>0;)u.preInit.pop()();return k&&(J=!1,Re.initWorker()),Fg(),r.ready}}();typeof e=="object"&&typeof t=="object"?t.exports=n:typeof define=="function"&&define.amd?define([],function(){return n}):typeof e=="object"&&(e.WasmBackendModuleThreadedSimd=n)}}),WN=ts({"src/tfjs-backend-wasm/wasm-out/tfjs-backend-wasm.js"(e,t){var n=function(){var s=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename!="undefined"&&(s=s||__filename),function(r){r=r||{};var a=typeof r!="undefined"?r:{},o,i;a.ready=new Promise(function(re,oe){o=re,i=oe});var l={},c;for(c in a)a.hasOwnProperty(c)&&(l[c]=a[c]);var u=[],d="./this.program",p=function(re,oe){throw oe},h=!1,f=!1,m=!1,g=!1;h=typeof window=="object",f=typeof importScripts=="function",m=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",g=!h&&!m&&!f;var A="";function y(re){return a.locateFile?a.locateFile(re,A):A+re}var x,b,w,k,S,E;m?(f?A=Ws("path").dirname(A)+"/":A=__dirname+"/",x=function(oe,ke){return S||(S=Ws("fs")),E||(E=Ws("path")),oe=E.normalize(oe),S.readFileSync(oe,ke?null:"utf8")},w=function(oe){var ke=x(oe,!0);return ke.buffer||(ke=new Uint8Array(ke)),H(ke.buffer),ke},process.argv.length>1&&(d=process.argv[1].replace(/\\/g,"/")),u=process.argv.slice(2),process.on("uncaughtException",function(re){if(!(re instanceof Dg))throw re}),process.on("unhandledRejection",sr),p=function(re){process.exit(re)},a.inspect=function(){return"[Emscripten Module object]"}):g?(typeof read!="undefined"&&(x=function(oe){return read(oe)}),w=function(oe){var ke;return typeof readbuffer=="function"?new Uint8Array(readbuffer(oe)):(ke=read(oe,"binary"),H(typeof ke=="object"),ke)},typeof scriptArgs!="undefined"?u=scriptArgs:typeof arguments!="undefined"&&(u=arguments),typeof quit=="function"&&(p=function(re){quit(re)}),typeof print!="undefined"&&(typeof console=="undefined"&&(console={}),console.log=print,console.warn=console.error=typeof printErr!="undefined"?printErr:print)):(h||f)&&(f?A=self.location.href:typeof document!="undefined"&&document.currentScript&&(A=document.currentScript.src),s&&(A=s),A.indexOf("blob:")!==0?A=A.substr(0,A.lastIndexOf("/")+1):A="",x=function(re){var oe=new XMLHttpRequest;return oe.open("GET",re,!1),oe.send(null),oe.responseText},f&&(w=function(re){var oe=new XMLHttpRequest;return oe.open("GET",re,!1),oe.responseType="arraybuffer",oe.send(null),new Uint8Array(oe.response)}),b=function(re,oe,ke){var it=new XMLHttpRequest;it.open("GET",re,!0),it.responseType="arraybuffer",it.onload=function(){if(it.status==200||it.status==0&&it.response){oe(it.response);return}ke()},it.onerror=ke,it.send(null)},k=function(re){document.title=re});var P=a.print||console.log.bind(console),F=a.printErr||console.warn.bind(console);for(c in l)l.hasOwnProperty(c)&&(a[c]=l[c]);l=null,a.arguments&&(u=a.arguments),a.thisProgram&&(d=a.thisProgram),a.quit&&(p=a.quit);var R;a.wasmBinary&&(R=a.wasmBinary);var _=a.noExitRuntime||!0;typeof WebAssembly!="object"&&sr("no native wasm support detected");var T,M=!1,U;function H(re,oe){re||sr("Assertion failed: "+oe)}function z(re){var oe=a["_"+re];return H(oe,"Cannot call unknown function "+re+", make sure it is exported"),oe}function X(re,oe,ke,it,Lt){var Rt={string:function(ps){var ga=0;if(ps!=null&&ps!==0){var Gp=(ps.length<<2)+1;ga=kc(Gp),te(ps,ga,Gp)}return ga},array:function(ps){var ga=kc(ps.length);return ue(ps,ga),ga}};function Je(ps){return oe==="string"?ne(ps):oe==="boolean"?Boolean(ps):ps}var Qe=z(re),In=[],Vr=0;if(it)for(var Ur=0;Ur=it);)++Lt;if(Lt-oe>16&&re.subarray&&Y)return Y.decode(re.subarray(oe,Lt));for(var Rt="";oe>10,56320|Vr&1023)}}return Rt}function ne(re,oe){return re?se(Ce,re,oe):""}function J(re,oe,ke,it){if(!(it>0))return 0;for(var Lt=ke,Rt=ke+it-1,Je=0;Je=55296&&Qe<=57343){var In=re.charCodeAt(++Je);Qe=65536+((Qe&1023)<<10)|In&1023}if(Qe<=127){if(ke>=Rt)break;oe[ke++]=Qe}else if(Qe<=2047){if(ke+1>=Rt)break;oe[ke++]=192|Qe>>6,oe[ke++]=128|Qe&63}else if(Qe<=65535){if(ke+2>=Rt)break;oe[ke++]=224|Qe>>12,oe[ke++]=128|Qe>>6&63,oe[ke++]=128|Qe&63}else{if(ke+3>=Rt)break;oe[ke++]=240|Qe>>18,oe[ke++]=128|Qe>>12&63,oe[ke++]=128|Qe>>6&63,oe[ke++]=128|Qe&63}}return oe[ke]=0,ke-Lt}function te(re,oe,ke){return J(re,Ce,oe,ke)}function ue(re,oe){we.set(re,oe)}function ce(re,oe){return re%oe>0&&(re+=oe-re%oe),re}var xe,we,Ce,Oe,Ue,Xe,rt,ft,ut;function ct(re){xe=re,a.HEAP8=we=new Int8Array(re),a.HEAP16=Oe=new Int16Array(re),a.HEAP32=Xe=new Int32Array(re),a.HEAPU8=Ce=new Uint8Array(re),a.HEAPU16=Ue=new Uint16Array(re),a.HEAPU32=rt=new Uint32Array(re),a.HEAPF32=ft=new Float32Array(re),a.HEAPF64=ut=new Float64Array(re)}var At=a.INITIAL_MEMORY||16777216,yt,Et=[],Pt=[],Jn=[],wn=[],nr=!1;Pt.push({func:function(){Ep()}});function On(){if(a.preRun)for(typeof a.preRun=="function"&&(a.preRun=[a.preRun]);a.preRun.length;)kn(a.preRun.shift());Bs(Et)}function ds(){nr=!0,Bs(Pt)}function Ls(){Bs(Jn)}function Is(){if(a.postRun)for(typeof a.postRun=="function"&&(a.postRun=[a.postRun]);a.postRun.length;)br(a.postRun.shift());Bs(wn)}function kn(re){Et.unshift(re)}function br(re){wn.unshift(re)}var Rn=0,vr=null,wr=null;function pa(re){Rn++,a.monitorRunDependencies&&a.monitorRunDependencies(Rn)}function Ac(re){if(Rn--,a.monitorRunDependencies&&a.monitorRunDependencies(Rn),Rn==0&&(vr!==null&&(clearInterval(vr),vr=null),wr)){var oe=wr;wr=null,oe()}}a.preloadedImages={},a.preloadedAudios={};function sr(re){a.onAbort&&a.onAbort(re),re+="",F(re),M=!0,U=1,re="abort("+re+"). Build with -s ASSERTIONS=1 for more info.";var oe=new WebAssembly.RuntimeError(re);throw i(oe),oe}function wp(re,oe){return String.prototype.startsWith?re.startsWith(oe):re.indexOf(oe)===0}var f0="data:application/octet-stream;base64,";function kp(re){return wp(re,f0)}var Ip="file://";function Sp(re){return wp(re,Ip)}var Qn="tfjs-backend-wasm.wasm";kp(Qn)||(Qn=y(Qn));function Cp(re){try{if(re==Qn&&R)return new Uint8Array(R);if(w)return w(re);throw"both async and sync fetching of the wasm failed"}catch(oe){sr(oe)}}function m0(){if(!R&&(h||f)){if(typeof fetch=="function"&&!Sp(Qn))return fetch(Qn,{credentials:"same-origin"}).then(function(re){if(!re.ok)throw"failed to load wasm binary file at '"+Qn+"'";return re.arrayBuffer()}).catch(function(){return Cp(Qn)});if(b)return new Promise(function(re,oe){b(Qn,function(ke){re(new Uint8Array(ke))},oe)})}return Promise.resolve().then(function(){return Cp(Qn)})}function g0(){var re={a:es};function oe(Je,Qe){var In=Je.exports;a.asm=In,T=a.asm.h,ct(T.buffer),yt=a.asm.Sa,Ac("wasm-instantiate")}pa("wasm-instantiate");function ke(Je){oe(Je.instance)}function it(Je){return m0().then(function(Qe){return WebAssembly.instantiate(Qe,re)}).then(Je,function(Qe){F("failed to asynchronously prepare wasm: "+Qe),sr(Qe)})}function Lt(){return!R&&typeof WebAssembly.instantiateStreaming=="function"&&!kp(Qn)&&!Sp(Qn)&&typeof fetch=="function"?fetch(Qn,{credentials:"same-origin"}).then(function(Je){var Qe=WebAssembly.instantiateStreaming(Je,re);return Qe.then(ke,function(In){return F("wasm streaming compile failed: "+In),F("falling back to ArrayBuffer instantiation"),it(ke)})}):it(ke)}if(a.instantiateWasm)try{var Rt=a.instantiateWasm(re,oe);return Rt}catch(Je){return F("Module.instantiateWasm callback failed with error: "+Je),!1}return Lt().catch(i),{}}function Bs(re){for(;re.length>0;){var oe=re.shift();if(typeof oe=="function"){oe(a);continue}var ke=oe.func;typeof ke=="number"?oe.arg===void 0?yt.get(ke)():yt.get(ke)(oe.arg):ke(oe.arg===void 0?null:oe.arg)}}function yc(){sr()}function Xo(re,oe,ke){Ce.copyWithin(re,oe,oe+ke)}function A0(){return Ce.length}function y0(re){try{return T.grow(re-xe.byteLength+65535>>>16),ct(T.buffer),1}catch(oe){}}function Wr(re){var oe=A0(),ke=2147483648;if(re>ke)return!1;for(var it=1;it<=4;it*=2){var Lt=oe*(1+.2/it);Lt=Math.min(Lt,re+100663296);var Rt=Math.min(ke,ce(Math.max(re,Lt),65536)),Je=y0(Rt);if(Je)return!0}return!1}var Ko={mappings:{},buffers:[null,[],[]],printChar:function(re,oe){var ke=Ko.buffers[re];oe===0||oe===10?((re===1?P:F)(se(ke,0)),ke.length=0):ke.push(oe)},varargs:void 0,get:function(){Ko.varargs+=4;var re=Xe[Ko.varargs-4>>2];return re},getStr:function(re){var oe=ne(re);return oe},get64:function(re,oe){return re}};function x0(re){return 0}function Tp(re,oe,ke,it,Lt){}function b0(re,oe,ke,it){for(var Lt=0,Rt=0;Rt>2],Qe=Xe[oe+(Rt*8+4)>>2],In=0;In>2]=Lt,0}function Np(){return 28}var es={a:yc,d:Xo,e:Wr,f:x0,c:Tp,b:b0,g:Np},v0=g0(),Ep=a.___wasm_call_ctors=function(){return(Ep=a.___wasm_call_ctors=a.asm.i).apply(null,arguments)},w0=a._init=function(){return(w0=a._init=a.asm.j).apply(null,arguments)},Rp=a._init_with_threads_count=function(){return(Rp=a._init_with_threads_count=a.asm.k).apply(null,arguments)},k0=a._get_threads_count=function(){return(k0=a._get_threads_count=a.asm.l).apply(null,arguments)},Rl=a._register_tensor=function(){return(Rl=a._register_tensor=a.asm.m).apply(null,arguments)},ha=a._dispose_data=function(){return(ha=a._dispose_data=a.asm.n).apply(null,arguments)},xc=a._dispose=function(){return(xc=a._dispose=a.asm.o).apply(null,arguments)},I0=a._Abs=function(){return(I0=a._Abs=a.asm.p).apply(null,arguments)},S0=a._Add=function(){return(S0=a._Add=a.asm.q).apply(null,arguments)},$p=a._AddN=function(){return($p=a._AddN=a.asm.r).apply(null,arguments)},Re=a._All=function(){return(Re=a._All=a.asm.s).apply(null,arguments)},C0=a._Any=function(){return(C0=a._Any=a.asm.t).apply(null,arguments)},T0=a._ArgMax=function(){return(T0=a._ArgMax=a.asm.u).apply(null,arguments)},N0=a._AvgPool=function(){return(N0=a._AvgPool=a.asm.v).apply(null,arguments)},E0=a._BatchMatMul=function(){return(E0=a._BatchMatMul=a.asm.w).apply(null,arguments)},R0=a._Ceil=function(){return(R0=a._Ceil=a.asm.x).apply(null,arguments)},Zo=a._ClipByValue=function(){return(Zo=a._ClipByValue=a.asm.y).apply(null,arguments)},$0=a._Conv2D=function(){return($0=a._Conv2D=a.asm.z).apply(null,arguments)},D0=a._Conv2DBackpropInput=function(){return(D0=a._Conv2DBackpropInput=a.asm.A).apply(null,arguments)},_0=a._Cos=function(){return(_0=a._Cos=a.asm.B).apply(null,arguments)},P0=a._Cosh=function(){return(P0=a._Cosh=a.asm.C).apply(null,arguments)},F0=a._CropAndResize=function(){return(F0=a._CropAndResize=a.asm.D).apply(null,arguments)},O0=a._Cumsum=function(){return(O0=a._Cumsum=a.asm.E).apply(null,arguments)},Dp=a._DepthToSpace=function(){return(Dp=a._DepthToSpace=a.asm.F).apply(null,arguments)},M0=a._DepthwiseConv2dNative=function(){return(M0=a._DepthwiseConv2dNative=a.asm.G).apply(null,arguments)},z0=a._Elu=function(){return(z0=a._Elu=a.asm.H).apply(null,arguments)},fa=a._Equal=function(){return(fa=a._Equal=a.asm.I).apply(null,arguments)},bc=a._Exp=function(){return(bc=a._Exp=a.asm.J).apply(null,arguments)},vc=a._FlipLeftRight=function(){return(vc=a._FlipLeftRight=a.asm.K).apply(null,arguments)},L0=a._Floor=function(){return(L0=a._Floor=a.asm.L).apply(null,arguments)},B0=a._FloorDiv=function(){return(B0=a._FloorDiv=a.asm.M).apply(null,arguments)},W0=a._FusedBatchNorm=function(){return(W0=a._FusedBatchNorm=a.asm.N).apply(null,arguments)},V0=a._FusedConv2D=function(){return(V0=a._FusedConv2D=a.asm.O).apply(null,arguments)},U0=a._FusedDepthwiseConv2D=function(){return(U0=a._FusedDepthwiseConv2D=a.asm.P).apply(null,arguments)},Ge=a._Gather=function(){return(Ge=a._Gather=a.asm.Q).apply(null,arguments)},G0=a._GatherNd=function(){return(G0=a._GatherNd=a.asm.R).apply(null,arguments)},H0=a._Greater=function(){return(H0=a._Greater=a.asm.S).apply(null,arguments)},j0=a._GreaterEqual=function(){return(j0=a._GreaterEqual=a.asm.T).apply(null,arguments)},q0=a._LeakyRelu=function(){return(q0=a._LeakyRelu=a.asm.U).apply(null,arguments)},X0=a._Less=function(){return(X0=a._Less=a.asm.V).apply(null,arguments)},K0=a._LessEqual=function(){return(K0=a._LessEqual=a.asm.W).apply(null,arguments)},wc=a._Log=function(){return(wc=a._Log=a.asm.X).apply(null,arguments)},_p=a._LogicalAnd=function(){return(_p=a._LogicalAnd=a.asm.Y).apply(null,arguments)},Pp=a._Max=function(){return(Pp=a._Max=a.asm.Z).apply(null,arguments)},Z0=a._MaxPool=function(){return(Z0=a._MaxPool=a.asm._).apply(null,arguments)},Y0=a._Maximum=function(){return(Y0=a._Maximum=a.asm.$).apply(null,arguments)},J0=a._Mean=function(){return(J0=a._Mean=a.asm.aa).apply(null,arguments)},Q0=a._Min=function(){return(Q0=a._Min=a.asm.ba).apply(null,arguments)},eg=a._Minimum=function(){return(eg=a._Minimum=a.asm.ca).apply(null,arguments)},tg=a._MirrorPad=function(){return(tg=a._MirrorPad=a.asm.da).apply(null,arguments)},ng=a._Multiply=function(){return(ng=a._Multiply=a.asm.ea).apply(null,arguments)},dt=a._Neg=function(){return(dt=a._Neg=a.asm.fa).apply(null,arguments)},sg=a._NonMaxSuppressionV3=function(){return(sg=a._NonMaxSuppressionV3=a.asm.ga).apply(null,arguments)},rg=a._NonMaxSuppressionV4=function(){return(rg=a._NonMaxSuppressionV4=a.asm.ha).apply(null,arguments)},ag=a._NonMaxSuppressionV5=function(){return(ag=a._NonMaxSuppressionV5=a.asm.ia).apply(null,arguments)},$l=a._NotEqual=function(){return($l=a._NotEqual=a.asm.ja).apply(null,arguments)},Fp=a._OneHot=function(){return(Fp=a._OneHot=a.asm.ka).apply(null,arguments)},Op=a._PadV2=function(){return(Op=a._PadV2=a.asm.la).apply(null,arguments)},Mp=a._Pow=function(){return(Mp=a._Pow=a.asm.ma).apply(null,arguments)},og=a._Prelu=function(){return(og=a._Prelu=a.asm.na).apply(null,arguments)},ig=a._Prod=function(){return(ig=a._Prod=a.asm.oa).apply(null,arguments)},zp=a._RealDiv=function(){return(zp=a._RealDiv=a.asm.pa).apply(null,arguments)},lg=a._Relu=function(){return(lg=a._Relu=a.asm.qa).apply(null,arguments)},ug=a._Relu6=function(){return(ug=a._Relu6=a.asm.ra).apply(null,arguments)},cg=a._ResizeBilinear=function(){return(cg=a._ResizeBilinear=a.asm.sa).apply(null,arguments)},dg=a._Reverse=function(){return(dg=a._Reverse=a.asm.ta).apply(null,arguments)},pg=a._RotateWithOffset=function(){return(pg=a._RotateWithOffset=a.asm.ua).apply(null,arguments)},Lp=a._Round=function(){return(Lp=a._Round=a.asm.va).apply(null,arguments)},ma=a._Rsqrt=function(){return(ma=a._Rsqrt=a.asm.wa).apply(null,arguments)},hg=a._ScatterNd=function(){return(hg=a._ScatterNd=a.asm.xa).apply(null,arguments)},fg=a._SelectV2=function(){return(fg=a._SelectV2=a.asm.ya).apply(null,arguments)},Bb=a._Sigmoid=function(){return(Bb=a._Sigmoid=a.asm.za).apply(null,arguments)},Bp=a._Sin=function(){return(Bp=a._Sin=a.asm.Aa).apply(null,arguments)},mg=a._Softmax=function(){return(mg=a._Softmax=a.asm.Ba).apply(null,arguments)},gg=a._Sqrt=function(){return(gg=a._Sqrt=a.asm.Ca).apply(null,arguments)},Ag=a._Square=function(){return(Ag=a._Square=a.asm.Da).apply(null,arguments)},yg=a._SquaredDifference=function(){return(yg=a._SquaredDifference=a.asm.Ea).apply(null,arguments)},xg=a._Step=function(){return(xg=a._Step=a.asm.Fa).apply(null,arguments)},bg=a._StridedSlice=function(){return(bg=a._StridedSlice=a.asm.Ga).apply(null,arguments)},vg=a._Sub=function(){return(vg=a._Sub=a.asm.Ha).apply(null,arguments)},wg=a._Sum=function(){return(wg=a._Sum=a.asm.Ia).apply(null,arguments)},kg=a._Tan=function(){return(kg=a._Tan=a.asm.Ja).apply(null,arguments)},Ig=a._Tanh=function(){return(Ig=a._Tanh=a.asm.Ka).apply(null,arguments)},Sg=a._Tile=function(){return(Sg=a._Tile=a.asm.La).apply(null,arguments)},Cg=a._TopK=function(){return(Cg=a._TopK=a.asm.Ma).apply(null,arguments)},Tg=a._Transform=function(){return(Tg=a._Transform=a.asm.Na).apply(null,arguments)},Ng=a._Transpose=function(){return(Ng=a._Transpose=a.asm.Oa).apply(null,arguments)},Eg=a.__FusedMatMul=function(){return(Eg=a.__FusedMatMul=a.asm.Pa).apply(null,arguments)},Rg=a._malloc=function(){return(Rg=a._malloc=a.asm.Qa).apply(null,arguments)},$g=a._free=function(){return($g=a._free=a.asm.Ra).apply(null,arguments)},Wp=a.stackSave=function(){return(Wp=a.stackSave=a.asm.Ta).apply(null,arguments)},Vp=a.stackRestore=function(){return(Vp=a.stackRestore=a.asm.Ua).apply(null,arguments)},kc=a.stackAlloc=function(){return(kc=a.stackAlloc=a.asm.Va).apply(null,arguments)};a.cwrap=ee;var Dl;function Dg(re){this.name="ExitStatus",this.message="Program terminated with exit("+re+")",this.status=re}wr=function re(){Dl||Ic(),Dl||(wr=re)};function Ic(re){if(re=re||u,Rn>0||(On(),Rn>0))return;function oe(){Dl||(Dl=!0,a.calledRun=!0,!M&&(ds(),Ls(),o(a),a.onRuntimeInitialized&&a.onRuntimeInitialized(),Is()))}a.setStatus?(a.setStatus("Running..."),setTimeout(function(){setTimeout(function(){a.setStatus("")},1),oe()},1)):oe()}if(a.run=Ic,a.preInit)for(typeof a.preInit=="function"&&(a.preInit=[a.preInit]);a.preInit.length>0;)a.preInit.pop()();return Ic(),r.ready}}();typeof e=="object"&&typeof t=="object"?t.exports=n:typeof define=="function"&&define.amd?define([],function(){return n}):typeof e=="object"&&(e.WasmBackendModule=n)}}),VN=1e-7,UN=1e-4,Dc=class{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}},Ll=class{refCount(e){return Vs("refCount")}incRef(e){return Vs("incRef")}timerAvailable(){return!0}time(e){return Vs("time")}read(e){return Vs("read")}readSync(e){return Vs("readSync")}numDataIds(){return Vs("numDataIds")}disposeData(e,t){return Vs("disposeData")}write(e,t,n){return Vs("write")}move(e,t,n,s,r){return Vs("move")}memory(){return Vs("memory")}floatPrecision(){return Vs("floatPrecision")}epsilon(){return this.floatPrecision()===32?VN:UN}dispose(){return Vs("dispose")}};function Vs(e){throw new Error(`'${e}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}function n5(e){let t=e.length,n=0;for(;t>0;)n=Math.random()*t|0,t--,Zp(e,t,n)}function GN(e,t){if(e.length!==t.length)throw new Error(`Array sizes must match to be shuffled together First array length was ${e.length}Second array length was ${t.length}`);let n=e.length,s=0;for(;n>0;)s=Math.random()*n|0,n--,Zp(e,n,s),Zp(t,n,s)}function _c(e,t,n){return Math.max(e,Math.min(t,n))}function HN(e){return e%2==0?e:e+1}function Zp(e,t,n){let s=e[t];e[t]=e[n],e[n]=s}function jN(e){let t=0;for(let n=0;nn+` Shapes ${e} and ${t} must match`)}function ei(e){O(e!=null,()=>"The input to the tensor constructor must be a non-null value.")}function ti(e,t=[],n=!1){if(t==null&&(t=[]),Array.isArray(e)||Dn(e)&&!n)for(let s=0;s0,n){return new Promise((s,r)=>{let a=0,o=()=>{if(e()){s();return}a++;let i=t(a);if(n!=null&&a>=n){r();return}setTimeout(o,i)};o()})}function eE(e,t){let n=1,s=-1;for(let a=0;a=0)n*=e[a];else if(e[a]===-1){if(s!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${s} and dim ${a}`);s=a}else if(e[a]<0)throw Error(`Shapes can not be < 0. Found ${e[a]} at dim ${a}`);if(s===-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}`);let r=e.slice();return r[s]=t/n,r}function Us(e,t){let n=t.length;return e=e==null?t.map((s,r)=>r):[].concat(e),O(e.every(s=>s>=-n&&s`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`),O(e.every(s=>mn(s)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(s=>s<0?n+s:s)}function s5(e,t){let n=[],s=[],r=t!=null&&Array.isArray(t)&&t.length===0,a=t==null||r?null:Us(t,e).sort(),o=0;for(let i=0;ii)&&e[i]===1&&(n.push(e[i]),s.push(i)),a[o]<=i&&o++}e[i]!==1&&(n.push(e[i]),s.push(i))}return{newShape:n,keptDims:s}}function r5(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 a5(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 o5(e,t){for(let n=0;nt+=n.length),t}function ba(e){return typeof e=="string"||e instanceof String}function u5(e){return typeof e=="boolean"}function c5(e){return typeof e=="number"}function Yp(e){return Array.isArray(e)?Yp(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":c5(e)?"float32":ba(e)?"string":u5(e)?"bool":"float32"}function va(e){return!!(e&&e.constructor&&e.call&&e.apply)}function Jp(e,t){for(let n=t;n=0;--s)n[s]=n[s+1]*e[s+1];return n}function d5(e,t,n,s=!1){let r=new Array;if(t.length===1){let a=t[0]*(s?2:1);for(let o=0;ol*c)*(s?2:1);for(let l=0;lr*a)*(n?2:1);if(s===0)return[];if(s!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${n?" for a complex tensor":""}.`);return d5(0,e,t,n)}function Lg(e,t){let n=Qp(e,t);for(let s=0;ss*r,1);if(t==null||t==="float32")return Wl(e,new Float32Array(n));if(t==="int32")return Wl(e,new Int32Array(n));if(t==="bool")return Wl(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function Bg(e){e.forEach(t=>{O(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function sE(e,t,n){if(t===0)return 0;if(t===1)return e[0];let s=e[e.length-1];for(let r=0;r{let[s,r]=n.split(":");this.urlFlags[s]=lE(s,r)})}};function oE(e){let t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(n,...s)=>(iE(t,s[0],s[1]),s.join("="))),t}function iE(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}function lE(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 K(){return Ir}var Ir=null;function uE(e){Ir=e}var Vg;function f5(){if(Vg==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");Vg=e}return Vg}function cE(){let e=f5();return e._tfGlobals==null&&(e._tfGlobals=new Map),e._tfGlobals}function Ug(e,t){let n=cE();if(n.has(e))return n.get(e);{let s=t();return n.set(e,s),n.get(e)}}var ni="Abs",Vl="Acos",Ul="Acosh",Hr="Add",wa="AddN",Gl="All",Hl="Any",ka="ArgMax",jl="ArgMin",ql="Asin",Xl="Asinh",Kl="Atan",Zl="Atanh",Yl="Atan2",Ia="AvgPool",eh="AvgPoolGrad",Fc="AvgPool3D",th="AvgPool3DGrad",Sa="BatchMatMul",si="BatchToSpaceND",nh="Bincount",m5="BroadcastTo",sh="BroadcastArgs",Ca="Cast",Ta="Ceil",jr="ClipByValue",Oc="Complex",Mc="ComplexAbs",ri="Concat",Na="Conv2D",rh="Conv2DBackpropFilter",Ea="Conv2DBackpropInput",zc="Conv3D",ah="Conv3DBackpropFilterV2",oh="Conv3DBackpropInputV2",Ra="Cos",$a="Cosh",ai="Cumsum",oi="CropAndResize",ih="DenseBincount",ii="DepthToSpace",Da="DepthwiseConv2dNative",lh="DepthwiseConv2dNativeBackpropFilter",uh="DepthwiseConv2dNativeBackpropInput",ch="Diag",Lc="Dilation2D",dh="Dilation2DBackpropInput",ph="Dilation2DBackpropFilter",_a="RealDiv",Bc="Einsum",Pa="Elu",hh="EluGrad",Jl="Erf",li="Equal",Fa="Exp",ui="ExpandDims",ci="Expm1",fh="FFT",Ql="Fill",di="FlipLeftRight",Oa="Floor",Ma="FloorDiv",za="FusedBatchNorm",pi="GatherV2",hi="GatherNd",fi="Greater",La="GreaterEqual",Ba="Identity",mh="IFFT",Wc="Imag",eu="IsFinite",tu="IsInf",nu="IsNan",mi="LeakyRelu",gi="Less",Ai="LessEqual",gh="LinSpace",Wa="Log",su="Log1p",yi="LogicalAnd",ru="LogicalNot",Vc="LogicalOr",g5="LogSoftmax",Uc="LRN",Ah="LRNGrad",Va="Max",Ua="Maximum",Ga="MaxPool",yh="MaxPoolGrad",Gc="MaxPool3D",xh="MaxPool3DGrad",bh="MaxPoolWithArgmax",Ha="Mean",ja="Min",qa="Minimum",Xa="MirrorPad",au="Mod",vh="Multinomial",Ka="Multiply",xi="Neg",bi="NotEqual",vi="NonMaxSuppressionV3",ou="NonMaxSuppressionV4",wi="NonMaxSuppressionV5",ki="OnesLike",Ii="OneHot",Si="Pack",Za="PadV2",dE="Pool",Ya="Pow",Ja="Prelu",Ci="Prod",iu="Range",Hc="Real",lu="Reciprocal",Qa="Relu",Ti="Reshape",uu="ResizeNearestNeighbor",wh="ResizeNearestNeighborGrad",eo="ResizeBilinear",kh="ResizeBilinearGrad",to="Relu6",Ni="Reverse",Ei="Round",no="Rsqrt",Ri="ScatterNd",$i="Select",cu="Selu",Di="Slice",so="Sin",_i="Sinh",du="Sign",ro="Sigmoid",pu="Softplus",ao="Sqrt",oo="Sum",Pi="SpaceToBatchND",Fi="SplitV",io="Softmax",Ih="SparseFillEmptyRows",Sh="SparseReshape",Ch="SparseSegmentMean",Th="SparseSegmentSum",jc="SparseToDense",lo="SquaredDifference",hu="Square",Oi="StridedSlice",qc="StringNGrams",Nh="StringSplit",Eh="StringToHashBucketFast",uo="Sub",Mi="Tan",co="Tanh",qr="Tile",zi="TopK",Li="Transform",po="Transpose",Rh="Unique",Bi="Unpack",Xc="UnsortedSegmentSum",Wi="ZerosLike",ho="Step",Kc="FromPixels",Vi="RotateWithOffset",fo="_FusedMatMul",mo="FusedConv2D",go="FusedDepthwiseConv2D",fu=Ug("kernelRegistry",()=>new Map),Zc=Ug("gradRegistry",()=>new Map);function $h(e,t){let n=Hg(e,t);return fu.get(n)}function Gg(e){return Zc.get(e)}function Xr(e){let t=fu.entries(),n=[];for(;;){let{done:s,value:r}=t.next();if(s)break;let[a,o]=r,[i]=a.split("_");i===e&&n.push(o)}return n}function Kr(e){let{kernelName:t,backendName:n}=e,s=Hg(t,n);fu.has(s)&&kr(`The kernel '${t}' for backend '${n}' is already registered`),fu.set(s,e)}function A5(e){let{kernelName:t}=e;Zc.has(t)&&K().getBool("DEBUG")&&kr(`Overriding the gradient for '${t}'`),Zc.set(t,e)}function pE(e,t){let n=Hg(e,t);if(!fu.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);fu.delete(n)}function hE(e){if(!Zc.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);Zc.delete(e)}function fE(e,t){Xr(e).forEach(s=>{let r=Object.assign({},s,{backendName:t});Kr(r)})}function Hg(e,t){return`${t}_${e}`}var v={};ze(v,{arraysEqual:()=>Gr,assert:()=>O,assertNonNegativeIntegerDimensions:()=>Bg,assertNonNull:()=>ei,assertShapesMatch:()=>zn,bytesFromStringArray:()=>l5,bytesPerElement:()=>zg,checkConversionForErrors:()=>o5,clamp:()=>_c,computeStrides:()=>Bl,createScalarValue:()=>bE,createShuffledIndices:()=>JN,decodeString:()=>Ph,distSquared:()=>XN,encodeString:()=>Qc,fetch:()=>wE,fingerPrint64:()=>xE,flatten:()=>ti,getArrayFromDType:()=>a5,getTypedArrayFromDType:()=>r5,hasEncodingLoss:()=>tE,hexToLong:()=>Yc,indexToLoc:()=>rE,inferDtype:()=>Yp,inferFromImplicitShape:()=>eE,isBoolean:()=>u5,isFunction:()=>va,isInt:()=>mn,isNumber:()=>c5,isPromise:()=>Wg,isScalarShape:()=>KN,isString:()=>ba,isTypedArray:()=>Dn,isValidDtype:()=>i5,locToIndex:()=>sE,makeOnesTypedArray:()=>Lg,makeZerosNestedTypedArray:()=>nE,makeZerosTypedArray:()=>Qp,nearestDivisor:()=>Jp,nearestLargerEven:()=>HN,now:()=>Jc,parseAxisParam:()=>Us,randUniform:()=>qN,repeatedTry:()=>QN,rightPad:()=>Pc,shuffle:()=>n5,shuffleCombo:()=>GN,sizeFromShape:()=>Ut,sizeToSquarishShape:()=>YN,squeezeShape:()=>s5,sum:()=>jN,swap:()=>Zp,tanh:()=>ZN,toNestedArray:()=>Wl,toTypedArray:()=>_h});var y5=Qo(EN()),Ui=y5.default||y5;function Yc(e){return Ui.fromString(e,!0,16)}var x5=Yc("c3a5c85c97cb3127"),Gi=Yc("b492b66fbe98f273"),Ln=Yc("9ae16a3b2f90404f");function jg(e){return e.xor(e.shru(47))}function b5(e,t,n){let s=e.slice(t,t+n);return Ui.fromBytes(Array.from(s),!0,!0)}function kt(e,t){return b5(e,t,8)}function v5(e,t){return b5(e,t,4)}function gn(e,t){return t===0?e:e.shru(t).or(e.shl(64-t))}function Ao(e,t,n=Yc("9ddfea08eb382d69")){let s=e.xor(t).mul(n);s=s.xor(s.shru(47));let r=t.xor(s).mul(n);return r=r.xor(r.shru(47)),r=r.mul(n),r}function mE(e,t,n,s,r,a){r=r.add(e),a=gn(a.add(r).add(s),21);let o=r;return r=r.add(t),r=r.add(n),a=a.add(gn(r,44)),[r.add(s),a.add(o)]}function Dh(e,t,n,s){return mE(kt(e,t),kt(e,t+8),kt(e,t+16),kt(e,t+24),n,s)}function gE(e,t=e.length){if(t>=8){let n=Ln.add(t*2),s=kt(e,0).add(Ln),r=kt(e,t-8),a=gn(r,37).mul(n).add(s),o=gn(s,25).add(r).mul(n);return Ao(a,o,n)}if(t>=4){let n=Ln.add(t*2),s=v5(e,0);return Ao(s.shl(3).add(t),v5(e,t-4),n)}if(t>0){let n=e[0],s=e[t>>1],r=e[t-1],a=n+(s<<8),o=t+(r<<2);return jg(Ln.mul(a).xor(x5.mul(o))).mul(Ln)}return Ln}function AE(e,t=e.length){let n=Ln.add(t*2),s=kt(e,0).mul(Gi),r=kt(e,8),a=kt(e,t-8).mul(n),o=kt(e,t-16).mul(Ln);return Ao(gn(s.add(r),43).add(gn(a,30)).add(o),s.add(gn(r.add(Ln),18)).add(a),n)}function yE(e,t=e.length){let n=Ln.add(t*2),s=kt(e,0).mul(Ln),r=kt(e,8),a=kt(e,t-8).mul(n),o=kt(e,t-16).mul(Ln),i=gn(s.add(r),43).add(gn(a,30)).add(o),l=Ao(i,s.add(gn(r.add(Ln),18)).add(a),n),c=kt(e,16).mul(n),u=kt(e,24),d=i.add(kt(e,t-32)).mul(n),p=l.add(kt(e,t-24)).mul(n);return Ao(gn(c.add(u),43).add(gn(d,30)).add(p),c.add(gn(u.add(s),18)).add(d),n)}function xE(e,t=e.length){let n=Ui.fromNumber(81,!0);if(t<=32)return t<=16?gE(e,t):AE(e,t);if(t<=64)return yE(e,t);let s=n,r=n.mul(Gi).add(113),a=jg(r.mul(Ln).add(113)).mul(Ln),o=[Ui.UZERO,Ui.UZERO],i=[Ui.UZERO,Ui.UZERO];s=s.mul(Ln).add(kt(e,0));let l=0,c=(t-1>>6)*64,u=c+(t-1&63)-63;do s=gn(s.add(r).add(o[0]).add(kt(e,l+8)),37).mul(Gi),r=gn(r.add(o[1]).add(kt(e,l+48)),42).mul(Gi),s=s.xor(i[1]),r=r.add(o[0]).add(kt(e,l+40)),a=gn(a.add(i[0]),33).mul(Gi),o=Dh(e,l,o[1].mul(Gi),s.add(i[0])),i=Dh(e,l+32,a.add(i[1]),r.add(kt(e,l+16))),[a,s]=[s,a],l+=64;while(l!==c);let d=Gi.add(a.and(255).shl(1));return l=u,i[0]=i[0].add(t-1&63),o[0]=o[0].add(i[0]),i[0]=i[0].add(o[0]),s=gn(s.add(r).add(o[0]).add(kt(e,l+8)),37).mul(d),r=gn(r.add(o[1]).add(kt(e,l+48)),42).mul(d),s=s.xor(i[1].mul(9)),r=r.add(o[0].mul(9).add(kt(e,l+40))),a=gn(a.add(i[0]),33).mul(d),o=Dh(e,l,o[1].mul(d),s.add(i[0])),i=Dh(e,l+32,a.add(i[1]),r.add(kt(e,l+16))),[a,s]=[s,a],Ao(Ao(o[0],i[0],d).add(jg(r).mul(x5)).add(a),Ao(o[1],i[1],d).add(s),d)}function bE(e,t){return t==="string"?Qc(e):_h([e],t)}function vE(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function _h(e,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=ti(e)),K().getBool("DEBUG")&&o5(e,t),vE(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"){let n=new Uint8Array(e.length);for(let s=0;s{s=n()},a,o=Jc();if(this.backendTimer.timerAvailable())a=this.backendTimer.time(r);else{r();for(let l of s)l.dataSync();a=Promise.resolve({kernelMs:Jc()-o})}if(K().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let l=0;l{IE(u,c.dtype,e)})}return{kernelName:e,outputs:s,inputs:t,timeMs:a.then(l=>l.kernelMs),extraInfo:a.then(l=>l.getExtraProfileInfo!=null?l.getExtraProfileInfo():"")}}logKernelProfile(e){let{kernelName:t,outputs:n,timeMs:s,inputs:r,extraInfo:a}=e;n.forEach(o=>{Promise.all([o.data(),s,a]).then(i=>{this.logger.logKernelProfile(t,o,i[0],i[1],r,i[2])})})}};function IE(e,t,n){if(t!=="float32")return!1;for(let s=0;s0?f:""} `}}console.log(`%c${i} %c${o} %c${l}D ${u} %c${c} %c${d} %c${a}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}};function CE(e,t,n){let s={},r={};for(let l=0;ls[m.id]=!0),h=!0,r[c.id]=!0;break}if(h)break}}let a={};a[n.id]=!0;let o={};for(let l=e.length-1;l>=0;l--){let c=e[l],u=c.inputs;for(let d=0;d=0;r--){let a=t[r],o=[];if(a.outputs.forEach(l=>{let c=e[l.id];c!=null?o.push(c):o.push(null)}),a.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${a.kernelName}.`);let i=a.gradient(o);for(let l in a.inputs){if(!(l in i))throw new Error(`Cannot backprop through input ${l}. Available gradients found: ${Object.keys(i)}.`);let c=n(()=>i[l]());if(c.dtype!=="float32")throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input ${l} must have 'float32' dtype, but has '${c.dtype}'`);let u=a.inputs[l];if(!Gr(c.shape,u.shape))throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input '${l}' has shape '${c.shape}', which does not match the shape of the input '${u.shape}'`);if(e[u.id]==null)e[u.id]=c;else{let d=e[u.id];e[u.id]=s(d,c),d.dispose()}}}}var w5=20,ed=3,qg=7;function NE(e,t,n,s){let r=Bl(t),a=EE(e,t,n,r),o=t.length,i=Fh(e,t,n,r,a),l=["Tensor"];return s&&(l.push(` dtype: ${n}`),l.push(` rank: ${o}`),l.push(` shape: [${t}]`),l.push(" values:")),l.push(i.map(c=>" "+c).join(` +var Og=Object.defineProperty;var vN=(e,t,n)=>t in e?Og(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var wN=e=>Og(e,"__esModule",{value:!0});var xa=(e=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(e,{get:(t,n)=>(typeof require!="undefined"?require:t)[n]}):e)(function(e){if(typeof require!="undefined")return require.apply(this,arguments);throw new Error('Dynamic require of "'+e+'" is not supported')});var qp=(e,t)=>{wN(e);for(var n in t)Og(e,n,{get:t[n],enumerable:!0})};var de=(e,t,n)=>(vN(e,typeof t!="symbol"?t+"":t,n),n),Qb=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var Ec=(e,t,n)=>(Qb(e,t,"read from private field"),n?n.call(e):t.get(e)),Rc=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},$c=(e,t,n,s)=>(Qb(e,t,"write to private field"),s?s.call(e,n):t.set(e,n),n);function at(e,t){let n=e.endsWith("/")?"":"/",r=t.startsWith(".")||t.startsWith("/")||t.startsWith("http:")||t.startsWith("https:")||t.startsWith("file:")?`${t}`:`${e}${n}${t}`;if(!r.toLocaleLowerCase().includes(".json"))throw new Error(`modelpath error: ${r} expecting json file`);return r}function ae(...e){let t=new Date,n=`${t.getHours().toString().padStart(2,"0")}:${t.getMinutes().toString().padStart(2,"0")}:${t.getSeconds().toString().padStart(2,"0")}.${t.getMilliseconds().toString().padStart(3,"0")}`;e&&console.log(n,"Human:",...e)}var pe=()=>typeof performance!="undefined"?performance.now():parseInt((Number(process.hrtime.bigint())/1e3/1e3).toString());function Mg(e,t,n="config",s=[]){for(let r of Object.keys(t))if(typeof t[r]=="object")Mg(e[r],t[r],r,s);else{let a=e&&typeof e[r]!="undefined";a||s.push({reason:"unknown property",where:`${n}.${r} = ${t[r]}`});let o=e&&typeof e[r]==typeof t[r];a&&!o&&s.push({reason:"property type mismatch",where:`${n}.${r} = ${t[r]}`,expected:typeof e[r]})}return t.debug&&n==="config"&&s.length>0&&ae("invalid configuration",s),s}function $n(...e){let t=n=>n&&typeof n=="object";return e.reduce((n,s)=>(Object.keys(s||{}).forEach(r=>{let a=n[r],o=s[r];Array.isArray(a)&&Array.isArray(o)?n[r]=a.concat(...o):t(a)&&t(o)?n[r]=$n(a,o):n[r]=o}),n),{})}var Jo={backend:"",modelBasePath:"",wasmPath:"",debug:!0,async:!0,warmup:"full",cacheSensitivity:.7,skipAllowed:!1,filter:{enabled:!0,width:0,height:0,flip:!1,return:!0,brightness:0,contrast:0,sharpness:0,blur:0,saturation:0,hue:0,negative:!1,sepia:!1,vintage:!1,kodachrome:!1,technicolor:!1,polaroid:!1,pixelate:0},gesture:{enabled:!0},face:{enabled:!0,detector:{modelPath:"blazeface.json",rotation:!0,maxDetected:1,skipFrames:99,skipTime:2500,minConfidence:.2,iouThreshold:.1,return:!1},mesh:{enabled:!0,modelPath:"facemesh.json"},iris:{enabled:!0,modelPath:"iris.json"},emotion:{enabled:!0,minConfidence:.1,skipFrames:99,skipTime:1500,modelPath:"emotion.json"},description:{enabled:!0,modelPath:"faceres.json",skipFrames:99,skipTime:3e3,minConfidence:.1},antispoof:{enabled:!1,skipFrames:99,skipTime:4e3,modelPath:"antispoof.json"}},body:{enabled:!0,modelPath:"movenet-lightning.json",detector:{modelPath:""},maxDetected:-1,minConfidence:.3,skipFrames:1,skipTime:200},hand:{enabled:!0,rotation:!0,skipFrames:99,skipTime:2e3,minConfidence:.5,iouThreshold:.2,maxDetected:-1,landmarks:!0,detector:{modelPath:"handtrack.json"},skeleton:{modelPath:"handskeleton.json"}},object:{enabled:!1,modelPath:"mb3-centernet.json",minConfidence:.2,iouThreshold:.4,maxDetected:10,skipFrames:99,skipTime:1e3},segmentation:{enabled:!1,modelPath:"selfie.json",blur:8}};var wl={};qp(wl,{Abs:()=>ni,Acos:()=>Vl,Acosh:()=>Ul,AdadeltaOptimizer:()=>ff,AdagradOptimizer:()=>mf,AdamOptimizer:()=>gf,AdamaxOptimizer:()=>Af,Add:()=>Hr,AddN:()=>wa,All:()=>Gl,Any:()=>Hl,ArgMax:()=>ka,ArgMin:()=>jl,Asin:()=>ql,Asinh:()=>Xl,Atan:()=>Kl,Atan2:()=>Yl,Atanh:()=>Zl,AvgPool:()=>Ia,AvgPool3D:()=>Fc,AvgPool3DGrad:()=>th,AvgPoolGrad:()=>eh,BackendWasm:()=>y6,BatchMatMul:()=>Sa,BatchToSpaceND:()=>si,Bincount:()=>nh,BroadcastArgs:()=>sh,BroadcastTo:()=>m5,Callback:()=>Tk,CallbackList:()=>mw,Cast:()=>Ca,Ceil:()=>Ta,ClipByValue:()=>jr,Complex:()=>Oc,ComplexAbs:()=>Mc,Concat:()=>ri,Conv2D:()=>Na,Conv2DBackpropFilter:()=>rh,Conv2DBackpropInput:()=>Ea,Conv3D:()=>zc,Conv3DBackpropFilterV2:()=>ah,Conv3DBackpropInputV2:()=>oh,Cos:()=>Ra,Cosh:()=>$a,CropAndResize:()=>oi,Cumsum:()=>ai,CustomCallback:()=>Aw,DataStorage:()=>Dc,DenseBincount:()=>ih,DepthToSpace:()=>ii,DepthwiseConv2dNative:()=>Da,DepthwiseConv2dNativeBackpropFilter:()=>lh,DepthwiseConv2dNativeBackpropInput:()=>uh,Diag:()=>ch,Dilation2D:()=>Lc,Dilation2DBackpropFilter:()=>ph,Dilation2DBackpropInput:()=>dh,ENV:()=>Ir,EarlyStopping:()=>Ek,Einsum:()=>Bc,Elu:()=>Pa,EluGrad:()=>hh,Environment:()=>h5,Equal:()=>li,Erf:()=>Jl,Exp:()=>Fa,ExpandDims:()=>ui,Expm1:()=>ci,FFT:()=>fh,Fill:()=>Ql,FlipLeftRight:()=>di,Floor:()=>Oa,FloorDiv:()=>Ma,FromPixels:()=>Kc,FusedBatchNorm:()=>za,FusedConv2D:()=>mo,FusedDepthwiseConv2D:()=>go,GPGPUContext:()=>vm,GatherNd:()=>hi,GatherV2:()=>pi,GraphModel:()=>i7,Greater:()=>fi,GreaterEqual:()=>La,History:()=>gw,IFFT:()=>mh,Identity:()=>Ba,Imag:()=>Wc,InputSpec:()=>Yt,IsFinite:()=>eu,IsInf:()=>tu,IsNan:()=>nu,KernelBackend:()=>Ll,LRN:()=>Uc,LRNGrad:()=>Ah,LayerVariable:()=>cw,LayersModel:()=>na,LeakyRelu:()=>mi,Less:()=>gi,LessEqual:()=>Ai,LinSpace:()=>gh,Log:()=>Wa,Log1p:()=>su,LogSoftmax:()=>g5,LogicalAnd:()=>yi,LogicalNot:()=>ru,LogicalOr:()=>Vc,MathBackendCPU:()=>xy,MathBackendWebGL:()=>Kd,Max:()=>Va,MaxPool:()=>Ga,MaxPool3D:()=>Gc,MaxPool3DGrad:()=>xh,MaxPoolGrad:()=>yh,MaxPoolWithArgmax:()=>bh,Maximum:()=>Ua,Mean:()=>Ha,Min:()=>ja,Minimum:()=>qa,MirrorPad:()=>Xa,Mod:()=>au,MomentumOptimizer:()=>yf,Multinomial:()=>vh,Multiply:()=>Ka,Neg:()=>xi,NonMaxSuppressionV3:()=>vi,NonMaxSuppressionV4:()=>ou,NonMaxSuppressionV5:()=>wi,NotEqual:()=>bi,OP_SCOPE_SUFFIX:()=>$5,OneHot:()=>Ii,OnesLike:()=>ki,Optimizer:()=>Qr,Pack:()=>Si,PadV2:()=>Za,Pool:()=>dE,Pow:()=>Ya,Prelu:()=>Ja,Prod:()=>Ci,RMSPropOptimizer:()=>xf,RNN:()=>sa,Range:()=>iu,Rank:()=>Xg,Real:()=>Hc,RealDiv:()=>_a,Reciprocal:()=>lu,Reduction:()=>Vn,Relu:()=>Qa,Relu6:()=>to,Reshape:()=>Ti,ResizeBilinear:()=>eo,ResizeBilinearGrad:()=>kh,ResizeNearestNeighbor:()=>uu,ResizeNearestNeighborGrad:()=>wh,Reverse:()=>Ni,RotateWithOffset:()=>Vi,Round:()=>Ei,Rsqrt:()=>no,SGDOptimizer:()=>xd,ScatterNd:()=>Ri,Select:()=>$i,Selu:()=>cu,Sequential:()=>Gf,Sigmoid:()=>ro,Sign:()=>du,Sin:()=>so,Sinh:()=>_i,Slice:()=>Di,Softmax:()=>io,Softplus:()=>pu,SpaceToBatchND:()=>Pi,SparseFillEmptyRows:()=>Ih,SparseReshape:()=>Sh,SparseSegmentMean:()=>Ch,SparseSegmentSum:()=>Th,SparseToDense:()=>jc,SplitV:()=>Fi,Sqrt:()=>ao,Square:()=>hu,SquaredDifference:()=>lo,Step:()=>ho,StridedSlice:()=>Oi,StringNGrams:()=>qc,StringSplit:()=>Nh,StringToHashBucketFast:()=>Eh,Sub:()=>uo,Sum:()=>oo,SymbolicTensor:()=>fr,Tan:()=>Mi,Tanh:()=>co,Tensor:()=>Ye,TensorBuffer:()=>sn,Tile:()=>qr,TopK:()=>zi,Transform:()=>Li,Transpose:()=>po,Unique:()=>Rh,Unpack:()=>Bi,UnsortedSegmentSum:()=>Xc,Variable:()=>sd,ZerosLike:()=>Wi,_FusedMatMul:()=>fo,abs:()=>rn,acos:()=>A3,acosh:()=>y3,add:()=>ie,addN:()=>Vh,all:()=>T2,any:()=>Uh,argMax:()=>Hs,argMin:()=>x3,asin:()=>b3,asinh:()=>v3,atan:()=>w3,atan2:()=>k3,atanh:()=>I3,avgPool:()=>Hh,avgPool3d:()=>R2,backend:()=>Tr,backend_util:()=>N,basicLSTMCell:()=>jR,batchNorm:()=>wu,batchNorm2d:()=>N3,batchNorm3d:()=>E3,batchNorm4d:()=>R3,batchToSpaceND:()=>jh,bincount:()=>$2,booleanMaskAsync:()=>aP,broadcastArgs:()=>$3,broadcastTo:()=>ud,browser:()=>Gs,buffer:()=>Le,callbacks:()=>bV,cast:()=>he,ceil:()=>D3,clipByValue:()=>fs,clone:()=>or,complex:()=>yo,concat:()=>It,concat1d:()=>_3,concat2d:()=>ku,concat3d:()=>P3,concat4d:()=>F3,constraints:()=>Uv,conv1d:()=>D2,conv2d:()=>ko,conv2dTranspose:()=>P2,conv3d:()=>F2,conv3dTranspose:()=>M3,copyRegisteredKernels:()=>fE,cos:()=>qh,cosh:()=>O2,cosineWindow:()=>i1,cumsum:()=>M2,customGrad:()=>Er,data:()=>l7,denseBincount:()=>z3,deprecationWarn:()=>I2,depthToSpace:()=>L3,depthwiseConv2d:()=>cd,deregisterOp:()=>wV,device_util:()=>gu,diag:()=>w$,dilation2d:()=>B3,disableDeprecationWarnings:()=>lR,dispose:()=>Q,disposeVariables:()=>uR,div:()=>fe,divNoNan:()=>W3,dot:()=>R$,dropout:()=>Av,einsum:()=>V3,elu:()=>dd,enableDebugMode:()=>iR,enableProdMode:()=>m3,enclosingPowerOfTwo:()=>yv,engine:()=>ss,env:()=>K,equal:()=>Cs,erf:()=>U3,exp:()=>Ts,expandDims:()=>Kt,expm1:()=>G3,eye:()=>z2,fft:()=>af,fill:()=>Iu,findBackend:()=>S2,findBackendFactory:()=>hR,floor:()=>pd,floorDiv:()=>C2,forceHalfFloat:()=>zS,fused:()=>So,gather:()=>Su,gatherND:()=>gv,gather_util:()=>A2,getBackend:()=>ir,getGradient:()=>Gg,getKernel:()=>$h,getKernelsForBackend:()=>Xr,getThreadsCount:()=>q0e,gpgpu_util:()=>dS,grad:()=>tD,grads:()=>nD,greater:()=>ms,greaterEqual:()=>Yi,ifft:()=>gd,imag:()=>Xh,image:()=>$e,inTopKAsync:()=>gP,initializers:()=>Zv,input:()=>Bw,io:()=>ns,irfft:()=>t1,isFinite:()=>H$,isInf:()=>q$,isNaN:()=>H3,keep:()=>yn,kernel_impls:()=>Xs,layers:()=>iw,leakyRelu:()=>Kh,less:()=>L2,lessEqual:()=>Ji,linalg:()=>Nv,linspace:()=>j3,loadGraphModel:()=>st,loadLayersModel:()=>$B,localResponseNormalization:()=>q3,log:()=>Ns,log1p:()=>Zh,logSigmoid:()=>lD,logSoftmax:()=>B2,logSumExp:()=>J3,logicalAnd:()=>lr,logicalNot:()=>Jh,logicalOr:()=>U2,logicalXor:()=>bD,losses:()=>eO,matMul:()=>He,math:()=>K5,max:()=>rs,maxPool:()=>Qh,maxPool3d:()=>G2,maxPoolWithArgmax:()=>Q3,maximum:()=>Yr,mean:()=>Wt,memory:()=>Bh,meshgrid:()=>CD,metrics:()=>Ik,min:()=>ef,minimum:()=>hd,mirrorPad:()=>ev,mod:()=>tv,model:()=>EB,models:()=>Sk,moments:()=>tf,movingAverage:()=>lP,mul:()=>W,multiRNNCell:()=>PD,multinomial:()=>nv,neg:()=>Ot,nextFrame:()=>Ev,norm:()=>a1,notEqual:()=>Tu,oneHot:()=>id,ones:()=>gs,onesLike:()=>Es,op:()=>V,outerProduct:()=>LD,pad:()=>qs,pad1d:()=>VD,pad2d:()=>GD,pad3d:()=>jD,pad4d:()=>XD,pool:()=>QD,pow:()=>Io,prelu:()=>sf,print:()=>U5,prod:()=>H2,profile:()=>cR,rand:()=>r_,randomGamma:()=>l_,randomNormal:()=>sv,randomUniform:()=>Nu,range:()=>Eu,ready:()=>Wh,real:()=>fd,reciprocal:()=>rv,registerBackend:()=>Ki,registerCallbackConstructor:()=>DB,registerGradient:()=>A5,registerKernel:()=>Kr,registerOp:()=>vV,regularizers:()=>Ck,relu:()=>Rr,relu6:()=>X2,removeBackend:()=>pR,reshape:()=>G,reverse:()=>Rs,reverse1d:()=>A_,reverse2d:()=>x_,reverse3d:()=>v_,reverse4d:()=>k_,rfft:()=>of,round:()=>K2,rsqrt:()=>Z2,scalar:()=>Ee,scatterND:()=>mv,scatter_util:()=>y2,selu:()=>Y2,separableConv2d:()=>av,sequential:()=>RB,serialization:()=>le,setBackend:()=>g3,setPlatform:()=>fR,setThreadsCount:()=>j0e,setWasmPath:()=>H0e,setWasmPaths:()=>b6,setWebGLContext:()=>pm,setdiff1dAsync:()=>ov,shared:()=>om,sigmoid:()=>hs,sign:()=>iv,signal:()=>QF,sin:()=>J2,sinh:()=>Q2,slice:()=>_e,slice1d:()=>rf,slice2d:()=>e1,slice3d:()=>Ru,slice4d:()=>md,slice_util:()=>An,softmax:()=>$u,softplus:()=>Cu,spaceToBatchND:()=>nf,sparse:()=>yd,sparseToDense:()=>o1,spectral:()=>JF,split:()=>Sn,sqrt:()=>_n,square:()=>xt,squaredDifference:()=>n1,squeeze:()=>pt,stack:()=>Pn,step:()=>Ad,stridedSlice:()=>lv,string:()=>hf,sub:()=>xe,sum:()=>Ie,sumOutType:()=>rd,tan:()=>uv,tanh:()=>vu,tensor:()=>Gt,tensor1d:()=>Zt,tensor2d:()=>ur,tensor3d:()=>Z5,tensor4d:()=>K_,tensor5d:()=>Z_,tensor6d:()=>Y_,tensor_util:()=>rr,test_util:()=>p3,tidy:()=>j,tile:()=>js,time:()=>dR,topk:()=>cv,train:()=>tl,transpose:()=>et,truncatedNormal:()=>lf,unique:()=>s1,unregisterGradient:()=>hE,unregisterKernel:()=>pE,unsortedSegmentSum:()=>dv,unstack:()=>as,upcastType:()=>Bn,util:()=>v,valueAndGrad:()=>sD,valueAndGrads:()=>rD,variable:()=>pv,variableGrads:()=>X3,version:()=>w6,version_converter:()=>SU,version_core:()=>up,version_cpu:()=>dH,version_layers:()=>U1,version_wasm:()=>X0e,version_webgl:()=>zJ,webgl:()=>LJ,webgl_util:()=>FI,webgpu:()=>bC,where:()=>Wn,whereAsync:()=>r1,zeros:()=>Ht,zerosLike:()=>tt});var zl=(e=>typeof xa!="undefined"?xa:typeof Proxy!="undefined"?new Proxy(e,{get:(t,n)=>(typeof xa!="undefined"?xa:t)[n]}):e)(function(e){if(typeof xa!="undefined")return xa.apply(this,arguments);throw new Error('Dynamic require of "'+e+'" is not supported')}),kN=Object.create,Xp=Object.defineProperty,IN=Object.getOwnPropertyDescriptor,SN=Object.getOwnPropertyNames,CN=Object.getPrototypeOf,TN=Object.prototype.hasOwnProperty,e5=e=>Xp(e,"__esModule",{value:!0}),Ws=(e=>typeof zl!="undefined"?zl:typeof Proxy!="undefined"?new Proxy(e,{get:(t,n)=>(typeof zl!="undefined"?zl:t)[n]}):e)(function(e){if(typeof zl!="undefined")return zl.apply(this,arguments);throw new Error('Dynamic require of "'+e+'" is not supported')}),ts=(e,t)=>function(){return t||(0,e[Object.keys(e)[0]])((t={exports:{}}).exports,t),t.exports},ze=(e,t)=>{e5(e);for(var n in t)Xp(e,n,{get:t[n],enumerable:!0})},NN=(e,t,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of SN(t))!TN.call(e,s)&&s!=="default"&&Xp(e,s,{get:()=>t[s],enumerable:!(n=IN(t,s))||n.enumerable});return e},Qo=e=>NN(e5(Xp(e!=null?kN(CN(e)):{},"default",e&&e.__esModule&&"default"in e?{get:()=>e.default,enumerable:!0}:{value:e,enumerable:!0})),e),EN=ts({"node_modules/.pnpm/long@4.0.0/node_modules/long/src/long.js"(e,t){t.exports=s;var n=null;try{n=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(P){}function s(P,T,M){this.low=P|0,this.high=T|0,this.unsigned=!!M}s.prototype.__isLong__,Object.defineProperty(s.prototype,"__isLong__",{value:!0});function r(P){return(P&&P.__isLong__)===!0}s.isLong=r;var a={},o={};function i(P,T){var M,U,H;return T?(P>>>=0,(H=0<=P&&P<256)&&(U=o[P],U)?U:(M=c(P,(P|0)<0?-1:0,!0),H&&(o[P]=M),M)):(P|=0,(H=-128<=P&&P<128)&&(U=a[P],U)?U:(M=c(P,P<0?-1:0,!1),H&&(a[P]=M),M))}s.fromInt=i;function l(P,T){if(isNaN(P))return T?b:x;if(T){if(P<0)return b;if(P>=g)return $}else{if(P<=-A)return F;if(P+1>=A)return E}return P<0?l(-P,T).neg():c(P%m|0,P/m|0,T)}s.fromNumber=l;function c(P,T,M){return new s(P,T,M)}s.fromBits=c;var u=Math.pow;function d(P,T,M){if(P.length===0)throw Error("empty string");if(P==="NaN"||P==="Infinity"||P==="+Infinity"||P==="-Infinity")return x;if(typeof T=="number"?(M=T,T=!1):T=!!T,M=M||10,M<2||360)throw Error("interior hyphen");if(U===0)return d(P.substring(1),T,M).neg();for(var H=l(u(M,8)),z=x,X=0;X>>0:this.low},R.toNumber=function(){return this.unsigned?(this.high>>>0)*m+(this.low>>>0):this.high*m+(this.low>>>0)},R.toString=function(T){if(T=T||10,T<2||36>>0,se=ne.toString(T);if(X=Y,X.isZero())return se+ee;for(;se.length<6;)se="0"+se;ee=""+se+ee}},R.getHighBits=function(){return this.high},R.getHighBitsUnsigned=function(){return this.high>>>0},R.getLowBits=function(){return this.low},R.getLowBitsUnsigned=function(){return this.low>>>0},R.getNumBitsAbs=function(){if(this.isNegative())return this.eq(F)?64:this.neg().getNumBitsAbs();for(var T=this.high!=0?this.high:this.low,M=31;M>0&&(T&1<=0},R.isOdd=function(){return(this.low&1)==1},R.isEven=function(){return(this.low&1)==0},R.equals=function(T){return r(T)||(T=p(T)),this.unsigned!==T.unsigned&&this.high>>>31==1&&T.high>>>31==1?!1:this.high===T.high&&this.low===T.low},R.eq=R.equals,R.notEquals=function(T){return!this.eq(T)},R.neq=R.notEquals,R.ne=R.notEquals,R.lessThan=function(T){return this.comp(T)<0},R.lt=R.lessThan,R.lessThanOrEqual=function(T){return this.comp(T)<=0},R.lte=R.lessThanOrEqual,R.le=R.lessThanOrEqual,R.greaterThan=function(T){return this.comp(T)>0},R.gt=R.greaterThan,R.greaterThanOrEqual=function(T){return this.comp(T)>=0},R.gte=R.greaterThanOrEqual,R.ge=R.greaterThanOrEqual,R.compare=function(T){if(r(T)||(T=p(T)),this.eq(T))return 0;var M=this.isNegative(),U=T.isNegative();return M&&!U?-1:!M&&U?1:this.unsigned?T.high>>>0>this.high>>>0||T.high===this.high&&T.low>>>0>this.low>>>0?-1:1:this.sub(T).isNegative()?-1:1},R.comp=R.compare,R.negate=function(){return!this.unsigned&&this.eq(F)?F:this.not().add(w)},R.neg=R.negate,R.add=function(T){r(T)||(T=p(T));var M=this.high>>>16,U=this.high&65535,H=this.low>>>16,z=this.low&65535,X=T.high>>>16,ee=T.high&65535,Y=T.low>>>16,ne=T.low&65535,se=0,J=0,te=0,ue=0;return ue+=z+ne,te+=ue>>>16,ue&=65535,te+=H+Y,J+=te>>>16,te&=65535,J+=U+ee,se+=J>>>16,J&=65535,se+=M+X,se&=65535,c(te<<16|ue,se<<16|J,this.unsigned)},R.subtract=function(T){return r(T)||(T=p(T)),this.add(T.neg())},R.sub=R.subtract,R.multiply=function(T){if(this.isZero())return x;if(r(T)||(T=p(T)),n){var M=n.mul(this.low,this.high,T.low,T.high);return c(M,n.get_high(),this.unsigned)}if(T.isZero())return x;if(this.eq(F))return T.isOdd()?F:x;if(T.eq(F))return this.isOdd()?F:x;if(this.isNegative())return T.isNegative()?this.neg().mul(T.neg()):this.neg().mul(T).neg();if(T.isNegative())return this.mul(T.neg()).neg();if(this.lt(y)&&T.lt(y))return l(this.toNumber()*T.toNumber(),this.unsigned);var U=this.high>>>16,H=this.high&65535,z=this.low>>>16,X=this.low&65535,ee=T.high>>>16,Y=T.high&65535,ne=T.low>>>16,se=T.low&65535,J=0,te=0,ue=0,ce=0;return ce+=X*se,ue+=ce>>>16,ce&=65535,ue+=z*se,te+=ue>>>16,ue&=65535,ue+=X*ne,te+=ue>>>16,ue&=65535,te+=H*se,J+=te>>>16,te&=65535,te+=z*ne,J+=te>>>16,te&=65535,te+=X*Y,J+=te>>>16,te&=65535,J+=U*se+H*ne+z*Y+X*ee,J&=65535,c(ue<<16|ce,J<<16|te,this.unsigned)},R.mul=R.multiply,R.divide=function(T){if(r(T)||(T=p(T)),T.isZero())throw Error("division by zero");if(n){if(!this.unsigned&&this.high===-2147483648&&T.low===-1&&T.high===-1)return this;var M=(this.unsigned?n.div_u:n.div_s)(this.low,this.high,T.low,T.high);return c(M,n.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?b:x;var U,H,z;if(this.unsigned){if(T.unsigned||(T=T.toUnsigned()),T.gt(this))return b;if(T.gt(this.shru(1)))return k;z=b}else{if(this.eq(F)){if(T.eq(w)||T.eq(S))return F;if(T.eq(F))return w;var X=this.shr(1);return U=X.div(T).shl(1),U.eq(x)?T.isNegative()?w:S:(H=this.sub(T.mul(U)),z=U.add(H.div(T)),z)}else if(T.eq(F))return this.unsigned?b:x;if(this.isNegative())return T.isNegative()?this.neg().div(T.neg()):this.neg().div(T).neg();if(T.isNegative())return this.div(T.neg()).neg();z=x}for(H=this;H.gte(T);){U=Math.max(1,Math.floor(H.toNumber()/T.toNumber()));for(var ee=Math.ceil(Math.log(U)/Math.LN2),Y=ee<=48?1:u(2,ee-48),ne=l(U),se=ne.mul(T);se.isNegative()||se.gt(H);)U-=Y,ne=l(U,this.unsigned),se=ne.mul(T);ne.isZero()&&(ne=w),z=z.add(ne),H=H.sub(se)}return z},R.div=R.divide,R.modulo=function(T){if(r(T)||(T=p(T)),n){var M=(this.unsigned?n.rem_u:n.rem_s)(this.low,this.high,T.low,T.high);return c(M,n.get_high(),this.unsigned)}return this.sub(this.div(T).mul(T))},R.mod=R.modulo,R.rem=R.modulo,R.not=function(){return c(~this.low,~this.high,this.unsigned)},R.and=function(T){return r(T)||(T=p(T)),c(this.low&T.low,this.high&T.high,this.unsigned)},R.or=function(T){return r(T)||(T=p(T)),c(this.low|T.low,this.high|T.high,this.unsigned)},R.xor=function(T){return r(T)||(T=p(T)),c(this.low^T.low,this.high^T.high,this.unsigned)},R.shiftLeft=function(T){return r(T)&&(T=T.toInt()),(T&=63)==0?this:T<32?c(this.low<>>32-T,this.unsigned):c(0,this.low<>>T|this.high<<32-T,this.high>>T,this.unsigned):c(this.high>>T-32,this.high>=0?0:-1,this.unsigned)},R.shr=R.shiftRight,R.shiftRightUnsigned=function(T){if(r(T)&&(T=T.toInt()),T&=63,T===0)return this;var M=this.high;if(T<32){var U=this.low;return c(U>>>T|M<<32-T,M>>>T,this.unsigned)}else return T===32?c(M,0,this.unsigned):c(M>>>T-32,0,this.unsigned)},R.shru=R.shiftRightUnsigned,R.shr_u=R.shiftRightUnsigned,R.toSigned=function(){return this.unsigned?c(this.low,this.high,!1):this},R.toUnsigned=function(){return this.unsigned?this:c(this.low,this.high,!0)},R.toBytes=function(T){return T?this.toBytesLE():this.toBytesBE()},R.toBytesLE=function(){var T=this.high,M=this.low;return[M&255,M>>>8&255,M>>>16&255,M>>>24,T&255,T>>>8&255,T>>>16&255,T>>>24]},R.toBytesBE=function(){var T=this.high,M=this.low;return[T>>>24,T>>>16&255,T>>>8&255,T&255,M>>>24,M>>>16&255,M>>>8&255,M&255]},s.fromBytes=function(T,M,U){return U?s.fromBytesLE(T,M):s.fromBytesBE(T,M)},s.fromBytesLE=function(T,M){return new s(T[0]|T[1]<<8|T[2]<<16|T[3]<<24,T[4]|T[5]<<8|T[6]<<16|T[7]<<24,M)},s.fromBytesBE=function(T,M){return new s(T[4]<<24|T[5]<<16|T[6]<<8|T[7],T[0]<<24|T[1]<<16|T[2]<<8|T[3],M)}}}),RN=ts({"(disabled):node-fetch"(){}}),$N=ts({"(disabled):util"(){}}),DN=ts({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/alea.js"(e,t){(function(n,s,r){function a(c){var u=this,d=l();u.next=function(){var p=2091639*u.s0+u.c*23283064365386963e-26;return u.s0=u.s1,u.s1=u.s2,u.s2=p-(u.c=p|0)},u.c=1,u.s0=d(" "),u.s1=d(" "),u.s2=d(" "),u.s0-=d(c),u.s0<0&&(u.s0+=1),u.s1-=d(c),u.s1<0&&(u.s1+=1),u.s2-=d(c),u.s2<0&&(u.s2+=1),d=null}function o(c,u){return u.c=c.c,u.s0=c.s0,u.s1=c.s1,u.s2=c.s2,u}function i(c,u){var d=new a(c),p=u&&u.state,h=d.next;return h.int32=function(){return d.next()*4294967296|0},h.double=function(){return h()+(h()*2097152|0)*11102230246251565e-32},h.quick=h,p&&(typeof p=="object"&&o(p,d),h.state=function(){return o(d,{})}),h}function l(){var c=4022871197,u=function(d){d=String(d);for(var p=0;p>>0,h-=c,h*=c,c=h>>>0,h-=c,c+=h*4294967296}return(c>>>0)*23283064365386963e-26};return u}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.alea=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),_N=ts({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor128.js"(e,t){(function(n,s,r){function a(l){var c=this,u="";c.x=0,c.y=0,c.z=0,c.w=0,c.next=function(){var p=c.x^c.x<<11;return c.x=c.y,c.y=c.z,c.z=c.w,c.w^=c.w>>>19^p^p>>>8},l===(l|0)?c.x=l:u+=l;for(var d=0;d>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(typeof d=="object"&&o(d,u),p.state=function(){return o(u,{})}),p}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.xor128=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),PN=ts({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorwow.js"(e,t){(function(n,s,r){function a(l){var c=this,u="";c.next=function(){var p=c.x^c.x>>>2;return c.x=c.y,c.y=c.z,c.z=c.w,c.w=c.v,(c.d=c.d+362437|0)+(c.v=c.v^c.v<<4^(p^p<<1))|0},c.x=0,c.y=0,c.z=0,c.w=0,c.v=0,l===(l|0)?c.x=l:u+=l;for(var d=0;d>>4),c.next()}function o(l,c){return c.x=l.x,c.y=l.y,c.z=l.z,c.w=l.w,c.v=l.v,c.d=l.d,c}function i(l,c){var u=new a(l),d=c&&c.state,p=function(){return(u.next()>>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(typeof d=="object"&&o(d,u),p.state=function(){return o(u,{})}),p}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.xorwow=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),FN=ts({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorshift7.js"(e,t){(function(n,s,r){function a(l){var c=this;c.next=function(){var d=c.x,p=c.i,h,f,m;return h=d[p],h^=h>>>7,f=h^h<<24,h=d[p+1&7],f^=h^h>>>10,h=d[p+3&7],f^=h^h>>>3,h=d[p+4&7],f^=h^h<<7,h=d[p+7&7],h=h^h<<13,f^=h^h<<9,d[p]=f,c.i=p+1&7,f};function u(d,p){var h,f,m=[];if(p===(p|0))f=m[0]=p;else for(p=""+p,h=0;h0;--h)d.next()}u(c,l)}function o(l,c){return c.x=l.x.slice(),c.i=l.i,c}function i(l,c){l==null&&(l=+new Date);var u=new a(l),d=c&&c.state,p=function(){return(u.next()>>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(d.x&&o(d,u),p.state=function(){return o(u,{})}),p}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.xorshift7=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),ON=ts({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor4096.js"(e,t){(function(n,s,r){function a(l){var c=this;c.next=function(){var d=c.w,p=c.X,h=c.i,f,m;return c.w=d=d+1640531527|0,m=p[h+34&127],f=p[h=h+1&127],m^=m<<13,f^=f<<17,m^=m>>>15,f^=f>>>12,m=p[h]=m^f,c.i=h,m+(d^d>>>16)|0};function u(d,p){var h,f,m,g,A,y=[],x=128;for(p===(p|0)?(f=p,p=null):(p=p+"\0",f=0,x=Math.max(x,p.length)),m=0,g=-32;g>>15,f^=f<<4,f^=f>>>13,g>=0&&(A=A+1640531527|0,h=y[g&127]^=f+A,m=h==0?m+1:0);for(m>=128&&(y[(p&&p.length||0)&127]=-1),m=127,g=4*128;g>0;--g)f=y[m+34&127],h=y[m=m+1&127],f^=f<<13,h^=h<<17,f^=f>>>15,h^=h>>>12,y[m]=f^h;d.w=A,d.X=y,d.i=m}u(c,l)}function o(l,c){return c.i=l.i,c.w=l.w,c.X=l.X.slice(),c}function i(l,c){l==null&&(l=+new Date);var u=new a(l),d=c&&c.state,p=function(){return(u.next()>>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(d.X&&o(d,u),p.state=function(){return o(u,{})}),p}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.xor4096=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),MN=ts({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/tychei.js"(e,t){(function(n,s,r){function a(l){var c=this,u="";c.next=function(){var p=c.b,h=c.c,f=c.d,m=c.a;return p=p<<25^p>>>7^h,h=h-f|0,f=f<<24^f>>>8^m,m=m-p|0,c.b=p=p<<20^p>>>12^h,c.c=h=h-f|0,c.d=f<<16^h>>>16^m,c.a=m-p|0},c.a=0,c.b=0,c.c=2654435769|0,c.d=1367130551,l===Math.floor(l)?(c.a=l/4294967296|0,c.b=l|0):u+=l;for(var d=0;d>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(typeof d=="object"&&o(d,u),p.state=function(){return o(u,{})}),p}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.tychei=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),zN=ts({"(disabled):crypto"(){}}),LN=ts({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/seedrandom.js"(e,t){(function(n,s,r){var a=256,o=6,i=52,l="random",c=r.pow(a,o),u=r.pow(2,i),d=u*2,p=a-1,h;function f(w,k,S){var E=[];k=k==!0?{entropy:!0}:k||{};var $=y(A(k.entropy?[w,b(s)]:w==null?x():w,3),E),F=new m(E),R=function(){for(var P=F.g(o),T=c,M=0;P=d;)P/=2,T/=2,M>>>=1;return(P+M)/T};return R.int32=function(){return F.g(4)|0},R.quick=function(){return F.g(4)/4294967296},R.double=R,y(b(F.S),s),(k.pass||S||function(P,T,M,U){return U&&(U.S&&g(U,F),P.state=function(){return g(F,{})}),M?(r[l]=P,T):P})(R,$,"global"in k?k.global:this==r,k.state)}function m(w){var k,S=w.length,E=this,$=0,F=E.i=E.j=0,R=E.S=[];for(S||(w=[S++]);$1&&(g=process.argv[1].replace(/\\/g,"/")),m=process.argv.slice(2),process.on("uncaughtException",function(C){if(!(C instanceof Nc))throw C}),process.on("unhandledRejection",Wr),A=function(C){process.exit(C)},u.inspect=function(){return"[Emscripten Module object]"};var U;try{U=Ws("worker_threads")}catch(C){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),C}global.Worker=U.Worker}else w?(typeof read!="undefined"&&($=function(D){return read(D)}),R=function(D){var L;return typeof readbuffer=="function"?new Uint8Array(readbuffer(D)):(L=read(D,"binary"),we(typeof L=="object"),L)},typeof scriptArgs!="undefined"?m=scriptArgs:typeof arguments!="undefined"&&(m=arguments),typeof quit=="function"&&(A=function(C){quit(C)}),typeof print!="undefined"&&(typeof console=="undefined"&&(console={}),console.log=print,console.warn=console.error=typeof printErr!="undefined"?printErr:print)):(y||x)&&(x?S=self.location.href:typeof document!="undefined"&&document.currentScript&&(S=document.currentScript.src),typeof s!="undefined"&&s&&(S=s),S.indexOf("blob:")!==0?S=S.substr(0,S.lastIndexOf("/")+1):S="",b?($=function(D,L){return T||(T=Ws("fs")),M||(M=Ws("path")),D=M.normalize(D),T.readFileSync(D,L?null:"utf8")},R=function(D){var L=$(D,!0);return L.buffer||(L=new Uint8Array(L)),we(L.buffer),L}):($=function(C){var D=new XMLHttpRequest;return D.open("GET",C,!1),D.send(null),D.responseText},x&&(R=function(C){var D=new XMLHttpRequest;return D.open("GET",C,!1),D.responseType="arraybuffer",D.send(null),new Uint8Array(D.response)}),F=function(C,D,L){var Z=new XMLHttpRequest;Z.open("GET",C,!0),Z.responseType="arraybuffer",Z.onload=function(){if(Z.status==200||Z.status==0&&Z.response){D(Z.response);return}L()},Z.onerror=L,Z.send(null)}),P=function(C){document.title=C});b&&typeof performance=="undefined"&&(global.performance=Ws("perf_hooks").performance);var H=u.print||console.log.bind(console),z=u.printErr||console.warn.bind(console);for(f in h)h.hasOwnProperty(f)&&(u[f]=h[f]);h=null,u.arguments&&(m=u.arguments),u.thisProgram&&(g=u.thisProgram),u.quit&&(A=u.quit);function X(C){X.shown||(X.shown={}),X.shown[C]||(X.shown[C]=1,z(C))}var ee=Atomics.load,Y=Atomics.store,ne=Atomics.compareExchange,se;u.wasmBinary&&(se=u.wasmBinary);var J=u.noExitRuntime||!0;typeof WebAssembly!="object"&&Wr("no native wasm support detected");var te,ue,ce=!1,be;function we(C,D){C||Wr("Assertion failed: "+D)}function Ce(C){var D=u["_"+C];return we(D,"Cannot call unknown function "+C+", make sure it is exported"),D}function Oe(C,D,L,Z,Ae){var me={string:function(Mn){var Ml=0;if(Mn!=null&&Mn!==0){var Jb=(Mn.length<<2)+1;Ml=Pl(Jb),ut(Mn,Ml,Jb)}return Ml},array:function(Mn){var Ml=Pl(Mn.length);return At(Mn,Ml),Ml}};function ge(Mn){return D==="string"?rt(Mn):D==="boolean"?Boolean(Mn):Mn}var Te=Ce(C),ht=[],fn=0;if(Z)for(var nn=0;nn=Z);){var me=C[D++];if(!me)return Ae;if(!(me&128)){Ae+=String.fromCharCode(me);continue}var ge=C[D++]&63;if((me&224)==192){Ae+=String.fromCharCode((me&31)<<6|ge);continue}var Te=C[D++]&63;if((me&240)==224?me=(me&15)<<12|ge<<6|Te:me=(me&7)<<18|ge<<12|Te<<6|C[D++]&63,me<65536)Ae+=String.fromCharCode(me);else{var ht=me-65536;Ae+=String.fromCharCode(55296|ht>>10,56320|ht&1023)}}return Ae}function rt(C,D){return C?Xe(o(),C,D):""}function ft(C,D,L,Z){if(!(Z>0))return 0;for(var Ae=L,me=L+Z-1,ge=0;ge=55296&&Te<=57343){var ht=C.charCodeAt(++ge);Te=65536+((Te&1023)<<10)|ht&1023}if(Te<=127){if(L>=me)break;D[L++]=Te}else if(Te<=2047){if(L+1>=me)break;D[L++]=192|Te>>6,D[L++]=128|Te&63}else if(Te<=65535){if(L+2>=me)break;D[L++]=224|Te>>12,D[L++]=128|Te>>6&63,D[L++]=128|Te&63}else{if(L+3>=me)break;D[L++]=240|Te>>18,D[L++]=128|Te>>12&63,D[L++]=128|Te>>6&63,D[L++]=128|Te&63}}return D[L]=0,L-Ae}function ut(C,D,L){return ft(C,o(),D,L)}function ct(C){for(var D=0,L=0;L=55296&&Z<=57343&&(Z=65536+((Z&1023)<<10)|C.charCodeAt(++L)&1023),Z<=127?++D:Z<=2047?D+=2:Z<=65535?D+=3:D+=4}return D}function At(C,D){a().set(C,D)}function yt(C,D){return C%D>0&&(C+=D-C%D),C}var Et,Pt,Jn,wn,nr,On,ds,Ls,Is;function kn(C){Et=C,u.HEAP8=Pt=new Int8Array(C),u.HEAP16=wn=new Int16Array(C),u.HEAP32=On=new Int32Array(C),u.HEAPU8=Jn=new Uint8Array(C),u.HEAPU16=nr=new Uint16Array(C),u.HEAPU32=ds=new Uint32Array(C),u.HEAPF32=Ls=new Float32Array(C),u.HEAPF64=Is=new Float64Array(C)}var br=u.INITIAL_MEMORY||16777216;if(k)te=u.wasmMemory,Et=u.buffer;else if(u.wasmMemory)te=u.wasmMemory;else if(te=new WebAssembly.Memory({initial:br/65536,maximum:2147483648/65536,shared:!0}),!(te.buffer instanceof SharedArrayBuffer))throw z("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),b&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");te&&(Et=te.buffer),br=Et.byteLength,kn(Et);var Rn,vr=[],wr=[],pa=[],Ac=[],sr=[],wp=!1,f0=!1;k||wr.push({func:function(){Bp()}});function kp(){if(!k){if(u.preRun)for(typeof u.preRun=="function"&&(u.preRun=[u.preRun]);u.preRun.length;)m0(u.preRun.shift());Rl(vr)}}function Ip(){wp=!0,!k&&Rl(wr)}function Sp(){k||Rl(pa)}function Qn(){k||(f0=!0)}function Cp(){if(!k){if(u.postRun)for(typeof u.postRun=="function"&&(u.postRun=[u.postRun]);u.postRun.length;)g0(u.postRun.shift());Rl(sr)}}function m0(C){vr.unshift(C)}function g0(C){sr.unshift(C)}var Bs=0,yc=null,Xo=null;function A0(C){we(!k,"addRunDependency cannot be used in a pthread worker"),Bs++,u.monitorRunDependencies&&u.monitorRunDependencies(Bs)}function y0(C){if(Bs--,u.monitorRunDependencies&&u.monitorRunDependencies(Bs),Bs==0&&(yc!==null&&(clearInterval(yc),yc=null),Xo)){var D=Xo;Xo=null,D()}}u.preloadedImages={},u.preloadedAudios={};function Wr(C){u.onAbort&&u.onAbort(C),k&&console.error("Pthread aborting at "+new Error().stack),C+="",z(C),ce=!0,be=1,C="abort("+C+"). Build with -s ASSERTIONS=1 for more info.";var D=new WebAssembly.RuntimeError(C);throw p(D),D}function Ko(C,D){return String.prototype.startsWith?C.startsWith(D):C.indexOf(D)===0}var x0="data:application/octet-stream;base64,";function Tp(C){return Ko(C,x0)}var b0="file://";function Np(C){return Ko(C,b0)}var es="tfjs-backend-wasm-threaded-simd.wasm";Tp(es)||(es=E(es));function v0(C){try{if(C==es&&se)return new Uint8Array(se);if(R)return R(C);throw"both async and sync fetching of the wasm failed"}catch(D){Wr(D)}}function Ep(){if(!se&&(y||x)){if(typeof fetch=="function"&&!Np(es))return fetch(es,{credentials:"same-origin"}).then(function(C){if(!C.ok)throw"failed to load wasm binary file at '"+es+"'";return C.arrayBuffer()}).catch(function(){return v0(es)});if(F)return new Promise(function(C,D){F(es,function(L){C(new Uint8Array(L))},D)})}return Promise.resolve().then(function(){return v0(es)})}function w0(){var C={a:fg};function D(ge,Te){var ht=ge.exports;if(u.asm=ht,Rn=u.asm.kb,ue=Te,!k){var fn=Re.unusedWorkers.length;Re.unusedWorkers.forEach(function(nn){Re.loadWasmModuleToWorker(nn,function(){--fn||y0("wasm-instantiate")})})}}k||A0("wasm-instantiate");function L(ge){D(ge.instance,ge.module)}function Z(ge){return Ep().then(function(Te){return WebAssembly.instantiate(Te,C)}).then(ge,function(Te){z("failed to asynchronously prepare wasm: "+Te),Wr(Te)})}function Ae(){return!se&&typeof WebAssembly.instantiateStreaming=="function"&&!Tp(es)&&!Np(es)&&typeof fetch=="function"?fetch(es,{credentials:"same-origin"}).then(function(ge){var Te=WebAssembly.instantiateStreaming(ge,C);return Te.then(L,function(ht){return z("wasm streaming compile failed: "+ht),z("falling back to ArrayBuffer instantiation"),Z(L)})}):Z(L)}if(u.instantiateWasm)try{var me=u.instantiateWasm(C,D);return me}catch(ge){return z("Module.instantiateWasm callback failed with error: "+ge),!1}return Ae().catch(p),{}}var Rp={10072:function(){throw"Canceled!"},10090:function(C,D){setTimeout(function(){jb(C,D)},0)}};function k0(){Re.initRuntime()}function Rl(C){for(;C.length>0;){var D=C.shift();if(typeof D=="function"){D(u);continue}var L=D.func;typeof L=="number"?D.arg===void 0?Rn.get(L)():Rn.get(L)(D.arg):L(D.arg===void 0?null:D.arg)}}var ha={EPERM:63,ENOENT:44,ESRCH:71,EINTR:27,EIO:29,ENXIO:60,E2BIG:1,ENOEXEC:45,EBADF:8,ECHILD:12,EAGAIN:6,EWOULDBLOCK:6,ENOMEM:48,EACCES:2,EFAULT:21,ENOTBLK:105,EBUSY:10,EEXIST:20,EXDEV:75,ENODEV:43,ENOTDIR:54,EISDIR:31,EINVAL:28,ENFILE:41,EMFILE:33,ENOTTY:59,ETXTBSY:74,EFBIG:22,ENOSPC:51,ESPIPE:70,EROFS:69,EMLINK:34,EPIPE:64,EDOM:18,ERANGE:68,ENOMSG:49,EIDRM:24,ECHRNG:106,EL2NSYNC:156,EL3HLT:107,EL3RST:108,ELNRNG:109,EUNATCH:110,ENOCSI:111,EL2HLT:112,EDEADLK:16,ENOLCK:46,EBADE:113,EBADR:114,EXFULL:115,ENOANO:104,EBADRQC:103,EBADSLT:102,EDEADLOCK:16,EBFONT:101,ENOSTR:100,ENODATA:116,ETIME:117,ENOSR:118,ENONET:119,ENOPKG:120,EREMOTE:121,ENOLINK:47,EADV:122,ESRMNT:123,ECOMM:124,EPROTO:65,EMULTIHOP:36,EDOTDOT:125,EBADMSG:9,ENOTUNIQ:126,EBADFD:127,EREMCHG:128,ELIBACC:129,ELIBBAD:130,ELIBSCN:131,ELIBMAX:132,ELIBEXEC:133,ENOSYS:52,ENOTEMPTY:55,ENAMETOOLONG:37,ELOOP:32,EOPNOTSUPP:138,EPFNOSUPPORT:139,ECONNRESET:15,ENOBUFS:42,EAFNOSUPPORT:5,EPROTOTYPE:67,ENOTSOCK:57,ENOPROTOOPT:50,ESHUTDOWN:140,ECONNREFUSED:14,EADDRINUSE:3,ECONNABORTED:13,ENETUNREACH:40,ENETDOWN:38,ETIMEDOUT:73,EHOSTDOWN:142,EHOSTUNREACH:23,EINPROGRESS:26,EALREADY:7,EDESTADDRREQ:17,EMSGSIZE:35,EPROTONOSUPPORT:66,ESOCKTNOSUPPORT:137,EADDRNOTAVAIL:4,ENETRESET:39,EISCONN:30,ENOTCONN:53,ETOOMANYREFS:141,EUSERS:136,EDQUOT:19,ESTALE:72,ENOTSUP:138,ENOMEDIUM:148,EILSEQ:25,EOVERFLOW:61,ECANCELED:11,ENOTRECOVERABLE:56,EOWNERDEAD:62,ESTRPIPE:135};function xc(C,D){if(C<=0||C>a().length||C&!0||D<0)return-28;if(D==0)return 0;D>=2147483647&&(D=1/0);var L=Atomics.load(i(),Fl>>2),Z=0;if(L==C){var Ae=Atomics.compareExchange(i(),Fl>>2,L,0);if(Ae==L&&(--D,Z=1,D<=0))return 1}var me=Atomics.notify(i(),C>>2,D);if(me>=0)return me+Z;throw"Atomics.notify returned an unexpected value "+me}u._emscripten_futex_wake=xc;function I0(C){if(k)throw"Internal Error! killThread() can only ever be called from main application thread!";if(!C)throw"Internal Error! Null pthread_ptr in killThread!";i()[C+12>>2]=0;var D=Re.pthreads[C];D.worker.terminate(),Re.freeThreadData(D),Re.runningWorkers.splice(Re.runningWorkers.indexOf(D.worker),1),D.worker.pthread=void 0}function S0(C){if(k)throw"Internal Error! cancelThread() can only ever be called from main application thread!";if(!C)throw"Internal Error! Null pthread_ptr in cancelThread!";var D=Re.pthreads[C];D.worker.postMessage({cmd:"cancel"})}function $p(C){if(k)throw"Internal Error! cleanupThread() can only ever be called from main application thread!";if(!C)throw"Internal Error! Null pthread_ptr in cleanupThread!";var D=Re.pthreads[C];if(D){i()[C+12>>2]=0;var L=D.worker;Re.returnWorkerToPool(L)}}var Re={unusedWorkers:[],runningWorkers:[],initMainThreadBlock:function(){for(var C=8,D=0;D>2]=C;var L=C+152;i()[L>>2]=L;for(var Z=Yo(512),D=0;D<128;++D)l()[Z/4+D]=0;Atomics.store(l(),C+100>>2,Z),Atomics.store(l(),C+40>>2,C),Pg(C,!x,1),Gb(C)},initWorker:function(){},pthreads:{},threadExitHandlers:[],setThreadStatus:function(){},runExitHandlers:function(){for(;Re.threadExitHandlers.length>0;)Re.threadExitHandlers.pop()();k&&Aa()&&Ub()},runExitHandlersAndDeinitThread:function(C,D){Atomics.store(l(),C+56>>2,1),Atomics.store(l(),C+60>>2,0),Re.runExitHandlers(),Atomics.store(l(),C+4>>2,D),Atomics.store(l(),C+0>>2,1),xc(C+0,2147483647),Pg(0,0,0)},threadExit:function(C){var D=Aa();D&&(Re.runExitHandlersAndDeinitThread(D,C),k&&postMessage({cmd:"exit"}))},threadCancel:function(){Re.runExitHandlersAndDeinitThread(Aa(),-1),postMessage({cmd:"cancelDone"})},terminateAllThreads:function(){for(var C in Re.pthreads){var D=Re.pthreads[C];D&&D.worker&&Re.returnWorkerToPool(D.worker)}Re.pthreads={};for(var L=0;L>2];i()[C.threadInfoStruct+100>>2]=0,Cc(D),Cc(C.threadInfoStruct)}C.threadInfoStruct=0,C.allocatedOwnStack&&C.stackBase&&Cc(C.stackBase),C.stackBase=0,C.worker&&(C.worker.pthread=null)}},returnWorkerToPool:function(C){Re.runWithoutMainThreadQueuedCalls(function(){delete Re.pthreads[C.pthread.threadInfoStruct],Re.unusedWorkers.push(C),Re.runningWorkers.splice(Re.runningWorkers.indexOf(C),1),Re.freeThreadData(C.pthread),C.pthread=void 0})},runWithoutMainThreadQueuedCalls:function(C){i()[Yb>>2]=0;try{C()}finally{i()[Yb>>2]=1}},receiveObjectTransfer:function(C){},loadWasmModuleToWorker:function(C,D){C.onmessage=function(L){var Z=L.data,Ae=Z.cmd;if(C.pthread&&(Re.currentProxiedOperationCallerThread=C.pthread.threadInfoStruct),Z.targetThread&&Z.targetThread!=Aa()){var me=Re.pthreads[Z.targetThread];me?me.worker.postMessage(L.data,Z.transferList):console.error('Internal error! Worker sent a message "'+Ae+'" to target pthread '+Z.targetThread+", but that thread no longer exists!"),Re.currentProxiedOperationCallerThread=void 0;return}if(Ae==="processQueuedMainThreadWork")Hp();else if(Ae==="spawnThread")zp(L.data);else if(Ae==="cleanupThread")$p(Z.thread);else if(Ae==="killThread")I0(Z.thread);else if(Ae==="cancelThread")S0(Z.thread);else if(Ae==="loaded")C.loaded=!0,D&&D(C),C.runPthread&&(C.runPthread(),delete C.runPthread);else if(Ae==="print")H("Thread "+Z.threadId+": "+Z.text);else if(Ae==="printErr")z("Thread "+Z.threadId+": "+Z.text);else if(Ae==="alert")alert("Thread "+Z.threadId+": "+Z.text);else if(Ae==="exit"){var ge=C.pthread&&Atomics.load(l(),C.pthread.threadInfoStruct+64>>2);ge&&Re.returnWorkerToPool(C)}else if(Ae==="exitProcess")try{bN(Z.returnCode)}catch(Te){if(Te instanceof Nc)return;throw Te}else Ae==="cancelDone"?Re.returnWorkerToPool(C):Ae==="objectTransfer"?Re.receiveObjectTransfer(L.data):L.data.target==="setimmediate"?C.postMessage(L.data):z("worker sent an unknown command "+Ae);Re.currentProxiedOperationCallerThread=void 0},C.onerror=function(L){z("pthread sent an error! "+L.filename+":"+L.lineno+": "+L.message)},b&&(C.on("message",function(L){C.onmessage({data:L})}),C.on("error",function(L){C.onerror(L)}),C.on("exit",function(L){})),C.postMessage({cmd:"load",urlOrBlob:u.mainScriptUrlOrBlob||s,wasmMemory:te,wasmModule:ue})},allocateUnusedWorker:function(){var C=E("tfjs-backend-wasm-threaded-simd.worker.js");Re.unusedWorkers.push(new Worker(C))},getNewWorker:function(){return Re.unusedWorkers.length==0&&(Re.allocateUnusedWorker(),Re.loadWasmModuleToWorker(Re.unusedWorkers[0])),Re.unusedWorkers.length>0?Re.unusedWorkers.pop():null},busySpinWait:function(C){for(var D=performance.now()+C;performance.now()>2]=C,C}function D0(C,D){if(k)return fa(1,1,C,D)}function _0(C,D){if(C==D)postMessage({cmd:"processQueuedMainThreadWork"});else if(k)postMessage({targetThread:C,cmd:"processThreadQueue"});else{var L=Re.pthreads[C],Z=L&&L.worker;if(!Z)return;Z.postMessage({cmd:"processThreadQueue"})}return 1}function P0(){Wr()}function F0(C,D,L){var Z=L0(D,L);return Rp[C].apply(null,Z)}function O0(C,D){}function Dp(C,D,L){if(C<=0||C>a().length||C&!0)return-28;if(y){if(Atomics.load(i(),C>>2)!=D)return-6;for(var Ae=performance.now(),me=Ae+L,ge=Atomics.exchange(i(),Fl>>2,C);;){if(Ae=performance.now(),Ae>me)return ge=Atomics.exchange(i(),Fl>>2,0),-73;if(ge=Atomics.exchange(i(),Fl>>2,0),ge==0)break;if(Hp(),Atomics.load(i(),C>>2)!=D)return-6;ge=Atomics.exchange(i(),Fl>>2,C)}return 0}else{var Z=Atomics.wait(i(),C>>2,D,L);if(Z==="timed-out")return-73;if(Z==="not-equal")return-6;if(Z==="ok")return 0;throw"Atomics.wait returned an unexpected value "+Z}}function M0(C,D,L){o().copyWithin(C,D,D+L)}function z0(){return b?Ws("os").cpus().length:navigator.hardwareConcurrency}function fa(C,D){for(var L=arguments.length-2,Z=Tc(),Ae=L,me=Pl(Ae*8),ge=me>>3,Te=0;Te>=2;L=o()[C++];){var Z=L<105;Z&&D&1&&D++,vc.push(Z?c()[D++>>1]:i()[D]),++D}return vc}function B0(C,D,L){bc.length=D;for(var Z=L>>3,Ae=0;Ae>>16),kn(te.buffer),1}catch(D){}}function U0(C){var D=W0();if(C<=D)return!1;var L=2147483648;if(C>L)return!1;for(var Z=1;Z<=4;Z*=2){var Ae=D*(1+.2/Z);Ae=Math.min(Ae,C+100663296);var me=Math.min(L,yt(Math.max(C,Ae),65536)),ge=V0(me);if(ge)return!0}return!1}var Ge={inEventHandler:0,removeAllEventListeners:function(){for(var C=Ge.eventHandlers.length-1;C>=0;--C)Ge._removeHandler(C);Ge.eventHandlers=[],Ge.deferredCalls=[]},registerRemoveEventListeners:function(){Ge.removeEventListenersRegistered||(Ac.push(Ge.removeAllEventListeners),Ge.removeEventListenersRegistered=!0)},deferredCalls:[],deferCall:function(C,D,L){function Z(ge,Te){if(ge.length!=Te.length)return!1;for(var ht in ge)if(ge[ht]!=Te[ht])return!1;return!0}for(var Ae in Ge.deferredCalls){var me=Ge.deferredCalls[Ae];if(me.targetFunction==C&&Z(me.argsList,L))return}Ge.deferredCalls.push({targetFunction:C,precedence:D,argsList:L}),Ge.deferredCalls.sort(function(ge,Te){return ge.precedence>2]=L,i()[ge+4>>2]=Z,i()[ge+8>>2]=Ae,_g(0,C,637534208,D,Z,ge),_l(me)},getTargetThreadForEventCallback:function(C){switch(C){case 1:return 0;case 2:return Re.currentProxiedOperationCallerThread;default:return C}},getNodeNameForTarget:function(C){return C?C==window?"#window":C==screen?"#screen":C&&C.nodeName?C.nodeName:"":""},fullscreenEnabled:function(){return document.fullscreenEnabled||document.webkitFullscreenEnabled}};function G0(C){var D=ct(C)+1,L=Yo(D);return ut(C,L,D),L}function H0(C,D,L,Z){var Ae=Tc(),me=Pl(12),ge=0;D&&(ge=G0(D)),i()[me>>2]=ge,i()[me+4>>2]=L,i()[me+8>>2]=Z,_g(0,C,657457152,0,ge,me),_l(Ae)}function j0(C,D,L,Z){D=D?rt(D):"",H0(C,D,L,Z)}function q0(C){return C>2?rt(C):C}var X0=[0,typeof document!="undefined"?document:0,typeof window!="undefined"?window:0];function K0(C){C=q0(C);var D=X0[C]||(typeof document!="undefined"?document.querySelector(C):void 0);return D}function wc(C){return K0(C)}function _p(C,D,L){var Z=wc(C);if(!Z)return-4;if(Z.canvasSharedPtr&&(i()[Z.canvasSharedPtr>>2]=D,i()[Z.canvasSharedPtr+4>>2]=L),Z.offscreenCanvas||!Z.controlTransferredOffscreen){Z.offscreenCanvas&&(Z=Z.offscreenCanvas);var Ae=!1;if(Z.GLctxObject&&Z.GLctxObject.GLctx){var me=Z.GLctxObject.GLctx.getParameter(2978);Ae=me[0]===0&&me[1]===0&&me[2]===Z.width&&me[3]===Z.height}Z.width=D,Z.height=L,Ae&&Z.GLctxObject.GLctx.viewport(0,0,D,L)}else if(Z.canvasSharedPtr){var ge=i()[Z.canvasSharedPtr+8>>2];return j0(ge,C,D,L),1}else return-4;return 0}function Pp(C,D,L){return k?fa(2,1,C,D,L):_p(C,D,L)}function Z0(C,D,L){var Z=wc(C);return Z?_p(C,D,L):Pp(C,D,L)}function Y0(C){}function J0(C,D){}function Q0(C){var D=C.getExtension("ANGLE_instanced_arrays");if(D)return C.vertexAttribDivisor=function(L,Z){D.vertexAttribDivisorANGLE(L,Z)},C.drawArraysInstanced=function(L,Z,Ae,me){D.drawArraysInstancedANGLE(L,Z,Ae,me)},C.drawElementsInstanced=function(L,Z,Ae,me,ge){D.drawElementsInstancedANGLE(L,Z,Ae,me,ge)},1}function eg(C){var D=C.getExtension("OES_vertex_array_object");if(D)return C.createVertexArray=function(){return D.createVertexArrayOES()},C.deleteVertexArray=function(L){D.deleteVertexArrayOES(L)},C.bindVertexArray=function(L){D.bindVertexArrayOES(L)},C.isVertexArray=function(L){return D.isVertexArrayOES(L)},1}function tg(C){var D=C.getExtension("WEBGL_draw_buffers");if(D)return C.drawBuffers=function(L,Z){D.drawBuffersWEBGL(L,Z)},1}function ng(C){return!!(C.multiDrawWebgl=C.getExtension("WEBGL_multi_draw"))}var dt={counter:1,buffers:[],programs:[],framebuffers:[],renderbuffers:[],textures:[],uniforms:[],shaders:[],vaos:[],contexts:{},offscreenCanvases:{},timerQueriesEXT:[],programInfos:{},stringCache:{},unpackAlignment:4,recordError:function(D){dt.lastError||(dt.lastError=D)},getNewId:function(C){for(var D=dt.counter++,L=C.length;L>2]:-1;Ae+=rt(i()[L+me*4>>2],ge<0?void 0:ge)}return Ae},createContext:function(C,D){var L=C.getContext("webgl",D);if(!L)return 0;var Z=dt.registerContext(L,D);return Z},registerContext:function(C,D){var L=Yo(8);i()[L+4>>2]=Aa();var Z={handle:L,attributes:D,version:D.majorVersion,GLctx:C};return C.canvas&&(C.canvas.GLctxObject=Z),dt.contexts[L]=Z,(typeof D.enableExtensionsByDefault=="undefined"||D.enableExtensionsByDefault)&&dt.initExtensions(Z),L},makeContextCurrent:function(C){return dt.currentContext=dt.contexts[C],u.ctx=ma=dt.currentContext&&dt.currentContext.GLctx,!(C&&!ma)},getContext:function(C){return dt.contexts[C]},deleteContext:function(C){dt.currentContext===dt.contexts[C]&&(dt.currentContext=null),typeof Ge=="object"&&Ge.removeAllHandlersOnTarget(dt.contexts[C].GLctx.canvas),dt.contexts[C]&&dt.contexts[C].GLctx.canvas&&(dt.contexts[C].GLctx.canvas.GLctxObject=void 0),Cc(dt.contexts[C].handle),dt.contexts[C]=null},initExtensions:function(C){if(C||(C=dt.currentContext),!C.initExtensionsDone){C.initExtensionsDone=!0;var D=C.GLctx;Q0(D),eg(D),tg(D),D.disjointTimerQueryExt=D.getExtension("EXT_disjoint_timer_query"),ng(D);var L=D.getSupportedExtensions()||[];L.forEach(function(Z){Z.indexOf("lose_context")<0&&Z.indexOf("debug")<0&&D.getExtension(Z)})}},populateUniformTable:function(C){for(var D=dt.programs[C],L=dt.programInfos[C]={uniforms:{},maxUniformLength:0,maxAttributeLength:-1,maxUniformBlockNameLength:-1},Z=L.uniforms,Ae=ma.getProgramParameter(D,35718),me=0;me>2,Z=i()[L+(24>>2)],Ae={alpha:!!i()[L+(0>>2)],depth:!!i()[L+(4>>2)],stencil:!!i()[L+(8>>2)],antialias:!!i()[L+(12>>2)],premultipliedAlpha:!!i()[L+(16>>2)],preserveDrawingBuffer:!!i()[L+(20>>2)],powerPreference:sg[Z],failIfMajorPerformanceCaveat:!!i()[L+(28>>2)],majorVersion:i()[L+(32>>2)],minorVersion:i()[L+(36>>2)],enableExtensionsByDefault:i()[L+(40>>2)],explicitSwapControl:i()[L+(44>>2)],proxyContextToMainThread:i()[L+(48>>2)],renderViaOffscreenBackBuffer:i()[L+(52>>2)]},me=wc(C);if(!me||Ae.explicitSwapControl)return 0;var ge=dt.createContext(me,Ae);return ge}function ag(C,D){return rg(C,D)}var $l={mappings:{},buffers:[null,[],[]],printChar:function(C,D){var L=$l.buffers[C];D===0||D===10?((C===1?H:z)(Xe(L,0)),L.length=0):L.push(D)},varargs:void 0,get:function(){$l.varargs+=4;var C=i()[$l.varargs-4>>2];return C},getStr:function(C){var D=rt(C);return D},get64:function(C,D){return C}};function Fp(C){return k?fa(3,1,C):0}function Op(C,D,L,Z,Ae){if(k)return fa(4,1,C,D,L,Z,Ae)}function Mp(C,D,L,Z){if(k)return fa(5,1,C,D,L,Z);for(var Ae=0,me=0;me>2],Te=i()[D+(me*8+4)>>2],ht=0;ht>2]=Ae,0}function og(C){var D=Re.threadExitHandlers.pop();C&&D()}function ig(C,D){Re.threadExitHandlers.push(function(){Rn.get(C)(D)})}function zp(C){if(k)throw"Internal Error! spawnThread() can only ever be called from main application thread!";var D=Re.getNewWorker();if(D.pthread!==void 0)throw"Internal error!";if(!C.pthread_ptr)throw"Internal error, no pthread ptr!";Re.runningWorkers.push(D);for(var L=Yo(128*4),Z=0;Z<128;++Z)i()[L+Z*4>>2]=0;var Ae=C.stackBase+C.stackSize,me=Re.pthreads[C.pthread_ptr]={worker:D,stackBase:C.stackBase,stackSize:C.stackSize,allocatedOwnStack:C.allocatedOwnStack,threadInfoStruct:C.pthread_ptr},ge=me.threadInfoStruct>>2;Atomics.store(l(),ge+(64>>2),C.detached),Atomics.store(l(),ge+(100>>2),L),Atomics.store(l(),ge+(40>>2),me.threadInfoStruct),Atomics.store(l(),ge+(80>>2),C.stackSize),Atomics.store(l(),ge+(76>>2),Ae),Atomics.store(l(),ge+(104>>2),C.stackSize),Atomics.store(l(),ge+(104+8>>2),Ae),Atomics.store(l(),ge+(104+12>>2),C.detached);var Te=Vb(),ht=Te+40;Atomics.store(l(),ge+(172>>2),ht),D.pthread=me;var fn={cmd:"run",start_routine:C.startRoutine,arg:C.arg,threadInfoStruct:C.pthread_ptr,stackBase:C.stackBase,stackSize:C.stackSize};D.runPthread=function(){fn.time=performance.now(),D.postMessage(fn,C.transferList)},D.loaded&&(D.runPthread(),delete D.runPthread)}function lg(C,D,L,Z){if(typeof SharedArrayBuffer=="undefined")return z("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;if(!C)return z("pthread_create called with a null thread pointer!"),28;var Ae=[],me=0;if(k&&(Ae.length===0||me))return qb(687865856,C,D,L,Z);if(me)return me;var ge=0,Te=0,ht=0;D&&D!=-1?(ge=i()[D>>2],ge+=81920,Te=i()[D+8>>2],ht=i()[D+12>>2]!==0):ge=2097152;var fn=Te==0;fn?Te=Zb(16,ge):(Te-=ge,we(Te>0));for(var nn=Yo(228),ya=0;ya<228>>2;++ya)l()[(nn>>2)+ya]=0;i()[C>>2]=nn,i()[nn+12>>2]=nn;var Ol=nn+152;i()[Ol>>2]=Ol;var Mn={stackBase:Te,stackSize:ge,allocatedOwnStack:fn,detached:ht,startRoutine:L,pthread_ptr:nn,arg:Z,transferList:Ae};return k?(Mn.cmd="spawnThread",postMessage(Mn,Ae)):zp(Mn),0}function ug(){if(!!k){var C=Aa();if(!!C){var D=Atomics.load(l(),C+56>>2);if(!D){var L=Atomics.load(l(),C+0>>2);if(L==2)throw"Canceled!"}}}}function cg(){b||x||X("Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread")}function dg(C,D,L){if(!C)return z("pthread_join attempted on a null thread pointer!"),ha.ESRCH;if(k&&Aa()==C)return z("PThread "+C+" is attempting to join to itself!"),ha.EDEADLK;if(!k&&Hb()==C)return z("Main thread "+C+" is attempting to join to itself!"),ha.EDEADLK;var Z=i()[C+12>>2];if(Z!==C)return z("pthread_join attempted on thread "+C+", which does not point to a valid thread, or does not exist anymore!"),ha.ESRCH;var Ae=Atomics.load(l(),C+64>>2);if(Ae)return z("Attempted to join thread "+C+", which was already detached!"),ha.EINVAL;for(L&&cg();;){var me=Atomics.load(l(),C+0>>2);if(me==1){var ge=Atomics.load(l(),C+4>>2);return D&&(i()[D>>2]=ge),Atomics.store(l(),C+64>>2,1),k?postMessage({cmd:"cleanupThread",thread:C}):$p(C),0}if(!L)return ha.EBUSY;ug(),k||Hp(),Dp(C+0,me,k?100:1)}}function pg(C,D){return dg(C,D,!0)}function Lp(C){if(k)return fa(6,1,C);switch(C){case 30:return 16384;case 85:var D=2147483648;return D/16384;case 132:case 133:case 12:case 137:case 138:case 15:case 235:case 16:case 17:case 18:case 19:case 20:case 149:case 13:case 10:case 236:case 153:case 9:case 21:case 22:case 159:case 154:case 14:case 77:case 78:case 139:case 82:case 68:case 67:case 164:case 11:case 29:case 47:case 48:case 95:case 52:case 51:case 46:return 200809;case 27:case 246:case 127:case 128:case 23:case 24:case 160:case 161:case 181:case 182:case 242:case 183:case 184:case 243:case 244:case 245:case 165:case 178:case 179:case 49:case 50:case 168:case 169:case 175:case 170:case 171:case 172:case 97:case 76:case 32:case 173:case 35:case 80:case 81:case 79:return-1;case 176:case 177:case 7:case 155:case 8:case 157:case 125:case 126:case 92:case 93:case 129:case 130:case 131:case 94:case 91:return 1;case 74:case 60:case 69:case 70:case 4:return 1024;case 31:case 42:case 72:return 32;case 87:case 26:case 33:return 2147483647;case 34:case 1:return 47839;case 38:case 36:return 99;case 43:case 37:return 2048;case 0:return 2097152;case 3:return 65536;case 28:return 32768;case 44:return 32767;case 75:return 16384;case 39:return 1e3;case 89:return 700;case 71:return 256;case 40:return 255;case 2:return 100;case 180:return 64;case 25:return 20;case 5:return 16;case 6:return 6;case 73:return 4;case 84:return typeof navigator=="object"&&navigator.hardwareConcurrency||1}return $0(28),-1}k||Re.initMainThreadBlock();var ma,hg=[null,D0,Pp,Fp,Op,Mp,Lp],fg={e:E0,r:R0,x:_0,b:P0,y:F0,j:O0,d:Dp,c:xc,f:Zo,p:M0,A:z0,u:B0,q:U0,v:Z0,i:Y0,s:J0,w:ag,l:Fp,n:Op,g:Mp,o:k0,a:te||u.wasmMemory,z:og,k:ig,h:lg,m:pg,t:Lp},Bb=w0(),Bp=u.___wasm_call_ctors=function(){return(Bp=u.___wasm_call_ctors=u.asm.B).apply(null,arguments)},mg=u._init=function(){return(mg=u._init=u.asm.C).apply(null,arguments)},gg=u._init_with_threads_count=function(){return(gg=u._init_with_threads_count=u.asm.D).apply(null,arguments)},Ag=u._get_threads_count=function(){return(Ag=u._get_threads_count=u.asm.E).apply(null,arguments)},yg=u._register_tensor=function(){return(yg=u._register_tensor=u.asm.F).apply(null,arguments)},xg=u._dispose_data=function(){return(xg=u._dispose_data=u.asm.G).apply(null,arguments)},bg=u._dispose=function(){return(bg=u._dispose=u.asm.H).apply(null,arguments)},vg=u._Abs=function(){return(vg=u._Abs=u.asm.I).apply(null,arguments)},wg=u._Add=function(){return(wg=u._Add=u.asm.J).apply(null,arguments)},kg=u._AddN=function(){return(kg=u._AddN=u.asm.K).apply(null,arguments)},Ig=u._All=function(){return(Ig=u._All=u.asm.L).apply(null,arguments)},Sg=u._Any=function(){return(Sg=u._Any=u.asm.M).apply(null,arguments)},Cg=u._ArgMax=function(){return(Cg=u._ArgMax=u.asm.N).apply(null,arguments)},Tg=u._AvgPool=function(){return(Tg=u._AvgPool=u.asm.O).apply(null,arguments)},Ng=u._BatchMatMul=function(){return(Ng=u._BatchMatMul=u.asm.P).apply(null,arguments)},Eg=u._Ceil=function(){return(Eg=u._Ceil=u.asm.Q).apply(null,arguments)},Rg=u._ClipByValue=function(){return(Rg=u._ClipByValue=u.asm.R).apply(null,arguments)},$g=u._Conv2D=function(){return($g=u._Conv2D=u.asm.S).apply(null,arguments)},Wp=u._Conv2DBackpropInput=function(){return(Wp=u._Conv2DBackpropInput=u.asm.T).apply(null,arguments)},Vp=u._Cos=function(){return(Vp=u._Cos=u.asm.U).apply(null,arguments)},kc=u._Cosh=function(){return(kc=u._Cosh=u.asm.V).apply(null,arguments)},Dl=u._CropAndResize=function(){return(Dl=u._CropAndResize=u.asm.W).apply(null,arguments)},Dg=u._Cumsum=function(){return(Dg=u._Cumsum=u.asm.X).apply(null,arguments)},Ic=u._DepthToSpace=function(){return(Ic=u._DepthToSpace=u.asm.Y).apply(null,arguments)},re=u._DepthwiseConv2dNative=function(){return(re=u._DepthwiseConv2dNative=u.asm.Z).apply(null,arguments)},oe=u._Elu=function(){return(oe=u._Elu=u.asm._).apply(null,arguments)},ke=u._Equal=function(){return(ke=u._Equal=u.asm.$).apply(null,arguments)},it=u._Exp=function(){return(it=u._Exp=u.asm.aa).apply(null,arguments)},Lt=u._FlipLeftRight=function(){return(Lt=u._FlipLeftRight=u.asm.ba).apply(null,arguments)},Rt=u._Floor=function(){return(Rt=u._Floor=u.asm.ca).apply(null,arguments)},Je=u._FloorDiv=function(){return(Je=u._FloorDiv=u.asm.da).apply(null,arguments)},Qe=u._FusedBatchNorm=function(){return(Qe=u._FusedBatchNorm=u.asm.ea).apply(null,arguments)},In=u._FusedConv2D=function(){return(In=u._FusedConv2D=u.asm.fa).apply(null,arguments)},Vr=u._FusedDepthwiseConv2D=function(){return(Vr=u._FusedDepthwiseConv2D=u.asm.ga).apply(null,arguments)},Ur=u._Gather=function(){return(Ur=u._Gather=u.asm.ha).apply(null,arguments)},Up=u._GatherNd=function(){return(Up=u._GatherNd=u.asm.ia).apply(null,arguments)},Sc=u._Greater=function(){return(Sc=u._Greater=u.asm.ja).apply(null,arguments)},ps=u._GreaterEqual=function(){return(ps=u._GreaterEqual=u.asm.ka).apply(null,arguments)},ga=u._LeakyRelu=function(){return(ga=u._LeakyRelu=u.asm.la).apply(null,arguments)},Gp=u._Less=function(){return(Gp=u._Less=u.asm.ma).apply(null,arguments)},IT=u._LessEqual=function(){return(IT=u._LessEqual=u.asm.na).apply(null,arguments)},ST=u._Log=function(){return(ST=u._Log=u.asm.oa).apply(null,arguments)},CT=u._LogicalAnd=function(){return(CT=u._LogicalAnd=u.asm.pa).apply(null,arguments)},TT=u._Max=function(){return(TT=u._Max=u.asm.qa).apply(null,arguments)},NT=u._MaxPool=function(){return(NT=u._MaxPool=u.asm.ra).apply(null,arguments)},ET=u._Maximum=function(){return(ET=u._Maximum=u.asm.sa).apply(null,arguments)},RT=u._Mean=function(){return(RT=u._Mean=u.asm.ta).apply(null,arguments)},$T=u._Min=function(){return($T=u._Min=u.asm.ua).apply(null,arguments)},DT=u._Minimum=function(){return(DT=u._Minimum=u.asm.va).apply(null,arguments)},_T=u._MirrorPad=function(){return(_T=u._MirrorPad=u.asm.wa).apply(null,arguments)},PT=u._Multiply=function(){return(PT=u._Multiply=u.asm.xa).apply(null,arguments)},FT=u._Neg=function(){return(FT=u._Neg=u.asm.ya).apply(null,arguments)},OT=u._NonMaxSuppressionV3=function(){return(OT=u._NonMaxSuppressionV3=u.asm.za).apply(null,arguments)},MT=u._NonMaxSuppressionV4=function(){return(MT=u._NonMaxSuppressionV4=u.asm.Aa).apply(null,arguments)},zT=u._NonMaxSuppressionV5=function(){return(zT=u._NonMaxSuppressionV5=u.asm.Ba).apply(null,arguments)},LT=u._NotEqual=function(){return(LT=u._NotEqual=u.asm.Ca).apply(null,arguments)},BT=u._OneHot=function(){return(BT=u._OneHot=u.asm.Da).apply(null,arguments)},WT=u._PadV2=function(){return(WT=u._PadV2=u.asm.Ea).apply(null,arguments)},VT=u._Pow=function(){return(VT=u._Pow=u.asm.Fa).apply(null,arguments)},UT=u._Prelu=function(){return(UT=u._Prelu=u.asm.Ga).apply(null,arguments)},GT=u._Prod=function(){return(GT=u._Prod=u.asm.Ha).apply(null,arguments)},HT=u._RealDiv=function(){return(HT=u._RealDiv=u.asm.Ia).apply(null,arguments)},jT=u._Relu=function(){return(jT=u._Relu=u.asm.Ja).apply(null,arguments)},qT=u._Relu6=function(){return(qT=u._Relu6=u.asm.Ka).apply(null,arguments)},XT=u._ResizeBilinear=function(){return(XT=u._ResizeBilinear=u.asm.La).apply(null,arguments)},KT=u._Reverse=function(){return(KT=u._Reverse=u.asm.Ma).apply(null,arguments)},ZT=u._RotateWithOffset=function(){return(ZT=u._RotateWithOffset=u.asm.Na).apply(null,arguments)},YT=u._Round=function(){return(YT=u._Round=u.asm.Oa).apply(null,arguments)},JT=u._Rsqrt=function(){return(JT=u._Rsqrt=u.asm.Pa).apply(null,arguments)},QT=u._ScatterNd=function(){return(QT=u._ScatterNd=u.asm.Qa).apply(null,arguments)},eN=u._SelectV2=function(){return(eN=u._SelectV2=u.asm.Ra).apply(null,arguments)},tN=u._Sigmoid=function(){return(tN=u._Sigmoid=u.asm.Sa).apply(null,arguments)},nN=u._Sin=function(){return(nN=u._Sin=u.asm.Ta).apply(null,arguments)},sN=u._Softmax=function(){return(sN=u._Softmax=u.asm.Ua).apply(null,arguments)},rN=u._Sqrt=function(){return(rN=u._Sqrt=u.asm.Va).apply(null,arguments)},aN=u._Square=function(){return(aN=u._Square=u.asm.Wa).apply(null,arguments)},oN=u._SquaredDifference=function(){return(oN=u._SquaredDifference=u.asm.Xa).apply(null,arguments)},iN=u._Step=function(){return(iN=u._Step=u.asm.Ya).apply(null,arguments)},lN=u._StridedSlice=function(){return(lN=u._StridedSlice=u.asm.Za).apply(null,arguments)},uN=u._Sub=function(){return(uN=u._Sub=u.asm._a).apply(null,arguments)},cN=u._Sum=function(){return(cN=u._Sum=u.asm.$a).apply(null,arguments)},dN=u._Tan=function(){return(dN=u._Tan=u.asm.ab).apply(null,arguments)},pN=u._Tanh=function(){return(pN=u._Tanh=u.asm.bb).apply(null,arguments)},hN=u._Tile=function(){return(hN=u._Tile=u.asm.cb).apply(null,arguments)},fN=u._TopK=function(){return(fN=u._TopK=u.asm.db).apply(null,arguments)},mN=u._Transform=function(){return(mN=u._Transform=u.asm.eb).apply(null,arguments)},gN=u._Transpose=function(){return(gN=u._Transpose=u.asm.fb).apply(null,arguments)},AN=u.__FusedMatMul=function(){return(AN=u.__FusedMatMul=u.asm.gb).apply(null,arguments)},Yo=u._malloc=function(){return(Yo=u._malloc=u.asm.hb).apply(null,arguments)},Cc=u._free=function(){return(Cc=u._free=u.asm.ib).apply(null,arguments)},Wb=u.___errno_location=function(){return(Wb=u.___errno_location=u.asm.jb).apply(null,arguments)},Vb=u._emscripten_get_global_libc=function(){return(Vb=u._emscripten_get_global_libc=u.asm.lb).apply(null,arguments)},Aa=u._pthread_self=function(){return(Aa=u._pthread_self=u.asm.mb).apply(null,arguments)},Ub=u.___pthread_tsd_run_dtors=function(){return(Ub=u.___pthread_tsd_run_dtors=u.asm.nb).apply(null,arguments)},Hp=u._emscripten_main_thread_process_queued_calls=function(){return(Hp=u._emscripten_main_thread_process_queued_calls=u.asm.ob).apply(null,arguments)},yN=u._emscripten_current_thread_process_queued_calls=function(){return(yN=u._emscripten_current_thread_process_queued_calls=u.asm.pb).apply(null,arguments)},Gb=u._emscripten_register_main_browser_thread_id=function(){return(Gb=u._emscripten_register_main_browser_thread_id=u.asm.qb).apply(null,arguments)},Hb=u._emscripten_main_browser_thread_id=function(){return(Hb=u._emscripten_main_browser_thread_id=u.asm.rb).apply(null,arguments)},jb=u.__emscripten_do_dispatch_to_thread=function(){return(jb=u.__emscripten_do_dispatch_to_thread=u.asm.sb).apply(null,arguments)},qb=u._emscripten_sync_run_in_main_thread_4=function(){return(qb=u._emscripten_sync_run_in_main_thread_4=u.asm.tb).apply(null,arguments)},Xb=u._emscripten_run_in_main_runtime_thread_js=function(){return(Xb=u._emscripten_run_in_main_runtime_thread_js=u.asm.ub).apply(null,arguments)},_g=u.__emscripten_call_on_thread=function(){return(_g=u.__emscripten_call_on_thread=u.asm.vb).apply(null,arguments)},xN=u._emscripten_tls_init=function(){return(xN=u._emscripten_tls_init=u.asm.wb).apply(null,arguments)},Pg=u.__emscripten_thread_init=function(){return(Pg=u.__emscripten_thread_init=u.asm.xb).apply(null,arguments)},Tc=u.stackSave=function(){return(Tc=u.stackSave=u.asm.yb).apply(null,arguments)},_l=u.stackRestore=function(){return(_l=u.stackRestore=u.asm.zb).apply(null,arguments)},Pl=u.stackAlloc=function(){return(Pl=u.stackAlloc=u.asm.Ab).apply(null,arguments)},Kb=u._emscripten_stack_set_limits=function(){return(Kb=u._emscripten_stack_set_limits=u.asm.Bb).apply(null,arguments)},Zb=u._memalign=function(){return(Zb=u._memalign=u.asm.Cb).apply(null,arguments)},Yb=u.__emscripten_allow_main_runtime_queued_calls=10064,Fl=u.__emscripten_main_thread_futex=10268;u.cwrap=Ue,u.PThread=Re,u.PThread=Re,u.wasmMemory=te,u.ExitStatus=Nc;var jp;function Nc(C){this.name="ExitStatus",this.message="Program terminated with exit("+C+")",this.status=C}Xo=function C(){jp||Fg(),jp||(Xo=C)};function Fg(C){if(C=C||m,Bs>0)return;if(k){d(u),Ip(),postMessage({cmd:"loaded"});return}if(kp(),Bs>0)return;function D(){jp||(jp=!0,u.calledRun=!0,!ce&&(Ip(),Sp(),d(u),u.onRuntimeInitialized&&u.onRuntimeInitialized(),Cp()))}u.setStatus?(u.setStatus("Running..."),setTimeout(function(){setTimeout(function(){u.setStatus("")},1),D()},1)):D()}u.run=Fg;function bN(C,D){if(!(D&&J&&C===0)){if(!D&&k)throw postMessage({cmd:"exitProcess",returnCode:C}),new Nc(C);J||(Re.terminateAllThreads(),be=C,Qn(),u.onExit&&u.onExit(C),ce=!0),A(C,new Nc(C))}}if(u.preInit)for(typeof u.preInit=="function"&&(u.preInit=[u.preInit]);u.preInit.length>0;)u.preInit.pop()();return k&&(J=!1,Re.initWorker()),Fg(),r.ready}}();typeof e=="object"&&typeof t=="object"?t.exports=n:typeof define=="function"&&define.amd?define([],function(){return n}):typeof e=="object"&&(e.WasmBackendModuleThreadedSimd=n)}}),WN=ts({"src/tfjs-backend-wasm/wasm-out/tfjs-backend-wasm.js"(e,t){var n=function(){var s=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename!="undefined"&&(s=s||__filename),function(r){r=r||{};var a=typeof r!="undefined"?r:{},o,i;a.ready=new Promise(function(re,oe){o=re,i=oe});var l={},c;for(c in a)a.hasOwnProperty(c)&&(l[c]=a[c]);var u=[],d="./this.program",p=function(re,oe){throw oe},h=!1,f=!1,m=!1,g=!1;h=typeof window=="object",f=typeof importScripts=="function",m=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",g=!h&&!m&&!f;var A="";function y(re){return a.locateFile?a.locateFile(re,A):A+re}var x,b,w,k,S,E;m?(f?A=Ws("path").dirname(A)+"/":A=__dirname+"/",x=function(oe,ke){return S||(S=Ws("fs")),E||(E=Ws("path")),oe=E.normalize(oe),S.readFileSync(oe,ke?null:"utf8")},w=function(oe){var ke=x(oe,!0);return ke.buffer||(ke=new Uint8Array(ke)),H(ke.buffer),ke},process.argv.length>1&&(d=process.argv[1].replace(/\\/g,"/")),u=process.argv.slice(2),process.on("uncaughtException",function(re){if(!(re instanceof Dg))throw re}),process.on("unhandledRejection",sr),p=function(re){process.exit(re)},a.inspect=function(){return"[Emscripten Module object]"}):g?(typeof read!="undefined"&&(x=function(oe){return read(oe)}),w=function(oe){var ke;return typeof readbuffer=="function"?new Uint8Array(readbuffer(oe)):(ke=read(oe,"binary"),H(typeof ke=="object"),ke)},typeof scriptArgs!="undefined"?u=scriptArgs:typeof arguments!="undefined"&&(u=arguments),typeof quit=="function"&&(p=function(re){quit(re)}),typeof print!="undefined"&&(typeof console=="undefined"&&(console={}),console.log=print,console.warn=console.error=typeof printErr!="undefined"?printErr:print)):(h||f)&&(f?A=self.location.href:typeof document!="undefined"&&document.currentScript&&(A=document.currentScript.src),s&&(A=s),A.indexOf("blob:")!==0?A=A.substr(0,A.lastIndexOf("/")+1):A="",x=function(re){var oe=new XMLHttpRequest;return oe.open("GET",re,!1),oe.send(null),oe.responseText},f&&(w=function(re){var oe=new XMLHttpRequest;return oe.open("GET",re,!1),oe.responseType="arraybuffer",oe.send(null),new Uint8Array(oe.response)}),b=function(re,oe,ke){var it=new XMLHttpRequest;it.open("GET",re,!0),it.responseType="arraybuffer",it.onload=function(){if(it.status==200||it.status==0&&it.response){oe(it.response);return}ke()},it.onerror=ke,it.send(null)},k=function(re){document.title=re});var $=a.print||console.log.bind(console),F=a.printErr||console.warn.bind(console);for(c in l)l.hasOwnProperty(c)&&(a[c]=l[c]);l=null,a.arguments&&(u=a.arguments),a.thisProgram&&(d=a.thisProgram),a.quit&&(p=a.quit);var R;a.wasmBinary&&(R=a.wasmBinary);var P=a.noExitRuntime||!0;typeof WebAssembly!="object"&&sr("no native wasm support detected");var T,M=!1,U;function H(re,oe){re||sr("Assertion failed: "+oe)}function z(re){var oe=a["_"+re];return H(oe,"Cannot call unknown function "+re+", make sure it is exported"),oe}function X(re,oe,ke,it,Lt){var Rt={string:function(ps){var ga=0;if(ps!=null&&ps!==0){var Gp=(ps.length<<2)+1;ga=kc(Gp),te(ps,ga,Gp)}return ga},array:function(ps){var ga=kc(ps.length);return ue(ps,ga),ga}};function Je(ps){return oe==="string"?se(ps):oe==="boolean"?Boolean(ps):ps}var Qe=z(re),In=[],Vr=0;if(it)for(var Ur=0;Ur=it);)++Lt;if(Lt-oe>16&&re.subarray&&Y)return Y.decode(re.subarray(oe,Lt));for(var Rt="";oe>10,56320|Vr&1023)}}return Rt}function se(re,oe){return re?ne(Ce,re,oe):""}function J(re,oe,ke,it){if(!(it>0))return 0;for(var Lt=ke,Rt=ke+it-1,Je=0;Je=55296&&Qe<=57343){var In=re.charCodeAt(++Je);Qe=65536+((Qe&1023)<<10)|In&1023}if(Qe<=127){if(ke>=Rt)break;oe[ke++]=Qe}else if(Qe<=2047){if(ke+1>=Rt)break;oe[ke++]=192|Qe>>6,oe[ke++]=128|Qe&63}else if(Qe<=65535){if(ke+2>=Rt)break;oe[ke++]=224|Qe>>12,oe[ke++]=128|Qe>>6&63,oe[ke++]=128|Qe&63}else{if(ke+3>=Rt)break;oe[ke++]=240|Qe>>18,oe[ke++]=128|Qe>>12&63,oe[ke++]=128|Qe>>6&63,oe[ke++]=128|Qe&63}}return oe[ke]=0,ke-Lt}function te(re,oe,ke){return J(re,Ce,oe,ke)}function ue(re,oe){we.set(re,oe)}function ce(re,oe){return re%oe>0&&(re+=oe-re%oe),re}var be,we,Ce,Oe,Ue,Xe,rt,ft,ut;function ct(re){be=re,a.HEAP8=we=new Int8Array(re),a.HEAP16=Oe=new Int16Array(re),a.HEAP32=Xe=new Int32Array(re),a.HEAPU8=Ce=new Uint8Array(re),a.HEAPU16=Ue=new Uint16Array(re),a.HEAPU32=rt=new Uint32Array(re),a.HEAPF32=ft=new Float32Array(re),a.HEAPF64=ut=new Float64Array(re)}var At=a.INITIAL_MEMORY||16777216,yt,Et=[],Pt=[],Jn=[],wn=[],nr=!1;Pt.push({func:function(){Ep()}});function On(){if(a.preRun)for(typeof a.preRun=="function"&&(a.preRun=[a.preRun]);a.preRun.length;)kn(a.preRun.shift());Bs(Et)}function ds(){nr=!0,Bs(Pt)}function Ls(){Bs(Jn)}function Is(){if(a.postRun)for(typeof a.postRun=="function"&&(a.postRun=[a.postRun]);a.postRun.length;)br(a.postRun.shift());Bs(wn)}function kn(re){Et.unshift(re)}function br(re){wn.unshift(re)}var Rn=0,vr=null,wr=null;function pa(re){Rn++,a.monitorRunDependencies&&a.monitorRunDependencies(Rn)}function Ac(re){if(Rn--,a.monitorRunDependencies&&a.monitorRunDependencies(Rn),Rn==0&&(vr!==null&&(clearInterval(vr),vr=null),wr)){var oe=wr;wr=null,oe()}}a.preloadedImages={},a.preloadedAudios={};function sr(re){a.onAbort&&a.onAbort(re),re+="",F(re),M=!0,U=1,re="abort("+re+"). Build with -s ASSERTIONS=1 for more info.";var oe=new WebAssembly.RuntimeError(re);throw i(oe),oe}function wp(re,oe){return String.prototype.startsWith?re.startsWith(oe):re.indexOf(oe)===0}var f0="data:application/octet-stream;base64,";function kp(re){return wp(re,f0)}var Ip="file://";function Sp(re){return wp(re,Ip)}var Qn="tfjs-backend-wasm.wasm";kp(Qn)||(Qn=y(Qn));function Cp(re){try{if(re==Qn&&R)return new Uint8Array(R);if(w)return w(re);throw"both async and sync fetching of the wasm failed"}catch(oe){sr(oe)}}function m0(){if(!R&&(h||f)){if(typeof fetch=="function"&&!Sp(Qn))return fetch(Qn,{credentials:"same-origin"}).then(function(re){if(!re.ok)throw"failed to load wasm binary file at '"+Qn+"'";return re.arrayBuffer()}).catch(function(){return Cp(Qn)});if(b)return new Promise(function(re,oe){b(Qn,function(ke){re(new Uint8Array(ke))},oe)})}return Promise.resolve().then(function(){return Cp(Qn)})}function g0(){var re={a:es};function oe(Je,Qe){var In=Je.exports;a.asm=In,T=a.asm.h,ct(T.buffer),yt=a.asm.Sa,Ac("wasm-instantiate")}pa("wasm-instantiate");function ke(Je){oe(Je.instance)}function it(Je){return m0().then(function(Qe){return WebAssembly.instantiate(Qe,re)}).then(Je,function(Qe){F("failed to asynchronously prepare wasm: "+Qe),sr(Qe)})}function Lt(){return!R&&typeof WebAssembly.instantiateStreaming=="function"&&!kp(Qn)&&!Sp(Qn)&&typeof fetch=="function"?fetch(Qn,{credentials:"same-origin"}).then(function(Je){var Qe=WebAssembly.instantiateStreaming(Je,re);return Qe.then(ke,function(In){return F("wasm streaming compile failed: "+In),F("falling back to ArrayBuffer instantiation"),it(ke)})}):it(ke)}if(a.instantiateWasm)try{var Rt=a.instantiateWasm(re,oe);return Rt}catch(Je){return F("Module.instantiateWasm callback failed with error: "+Je),!1}return Lt().catch(i),{}}function Bs(re){for(;re.length>0;){var oe=re.shift();if(typeof oe=="function"){oe(a);continue}var ke=oe.func;typeof ke=="number"?oe.arg===void 0?yt.get(ke)():yt.get(ke)(oe.arg):ke(oe.arg===void 0?null:oe.arg)}}function yc(){sr()}function Xo(re,oe,ke){Ce.copyWithin(re,oe,oe+ke)}function A0(){return Ce.length}function y0(re){try{return T.grow(re-be.byteLength+65535>>>16),ct(T.buffer),1}catch(oe){}}function Wr(re){var oe=A0(),ke=2147483648;if(re>ke)return!1;for(var it=1;it<=4;it*=2){var Lt=oe*(1+.2/it);Lt=Math.min(Lt,re+100663296);var Rt=Math.min(ke,ce(Math.max(re,Lt),65536)),Je=y0(Rt);if(Je)return!0}return!1}var Ko={mappings:{},buffers:[null,[],[]],printChar:function(re,oe){var ke=Ko.buffers[re];oe===0||oe===10?((re===1?$:F)(ne(ke,0)),ke.length=0):ke.push(oe)},varargs:void 0,get:function(){Ko.varargs+=4;var re=Xe[Ko.varargs-4>>2];return re},getStr:function(re){var oe=se(re);return oe},get64:function(re,oe){return re}};function x0(re){return 0}function Tp(re,oe,ke,it,Lt){}function b0(re,oe,ke,it){for(var Lt=0,Rt=0;Rt>2],Qe=Xe[oe+(Rt*8+4)>>2],In=0;In>2]=Lt,0}function Np(){return 28}var es={a:yc,d:Xo,e:Wr,f:x0,c:Tp,b:b0,g:Np},v0=g0(),Ep=a.___wasm_call_ctors=function(){return(Ep=a.___wasm_call_ctors=a.asm.i).apply(null,arguments)},w0=a._init=function(){return(w0=a._init=a.asm.j).apply(null,arguments)},Rp=a._init_with_threads_count=function(){return(Rp=a._init_with_threads_count=a.asm.k).apply(null,arguments)},k0=a._get_threads_count=function(){return(k0=a._get_threads_count=a.asm.l).apply(null,arguments)},Rl=a._register_tensor=function(){return(Rl=a._register_tensor=a.asm.m).apply(null,arguments)},ha=a._dispose_data=function(){return(ha=a._dispose_data=a.asm.n).apply(null,arguments)},xc=a._dispose=function(){return(xc=a._dispose=a.asm.o).apply(null,arguments)},I0=a._Abs=function(){return(I0=a._Abs=a.asm.p).apply(null,arguments)},S0=a._Add=function(){return(S0=a._Add=a.asm.q).apply(null,arguments)},$p=a._AddN=function(){return($p=a._AddN=a.asm.r).apply(null,arguments)},Re=a._All=function(){return(Re=a._All=a.asm.s).apply(null,arguments)},C0=a._Any=function(){return(C0=a._Any=a.asm.t).apply(null,arguments)},T0=a._ArgMax=function(){return(T0=a._ArgMax=a.asm.u).apply(null,arguments)},N0=a._AvgPool=function(){return(N0=a._AvgPool=a.asm.v).apply(null,arguments)},E0=a._BatchMatMul=function(){return(E0=a._BatchMatMul=a.asm.w).apply(null,arguments)},R0=a._Ceil=function(){return(R0=a._Ceil=a.asm.x).apply(null,arguments)},Zo=a._ClipByValue=function(){return(Zo=a._ClipByValue=a.asm.y).apply(null,arguments)},$0=a._Conv2D=function(){return($0=a._Conv2D=a.asm.z).apply(null,arguments)},D0=a._Conv2DBackpropInput=function(){return(D0=a._Conv2DBackpropInput=a.asm.A).apply(null,arguments)},_0=a._Cos=function(){return(_0=a._Cos=a.asm.B).apply(null,arguments)},P0=a._Cosh=function(){return(P0=a._Cosh=a.asm.C).apply(null,arguments)},F0=a._CropAndResize=function(){return(F0=a._CropAndResize=a.asm.D).apply(null,arguments)},O0=a._Cumsum=function(){return(O0=a._Cumsum=a.asm.E).apply(null,arguments)},Dp=a._DepthToSpace=function(){return(Dp=a._DepthToSpace=a.asm.F).apply(null,arguments)},M0=a._DepthwiseConv2dNative=function(){return(M0=a._DepthwiseConv2dNative=a.asm.G).apply(null,arguments)},z0=a._Elu=function(){return(z0=a._Elu=a.asm.H).apply(null,arguments)},fa=a._Equal=function(){return(fa=a._Equal=a.asm.I).apply(null,arguments)},bc=a._Exp=function(){return(bc=a._Exp=a.asm.J).apply(null,arguments)},vc=a._FlipLeftRight=function(){return(vc=a._FlipLeftRight=a.asm.K).apply(null,arguments)},L0=a._Floor=function(){return(L0=a._Floor=a.asm.L).apply(null,arguments)},B0=a._FloorDiv=function(){return(B0=a._FloorDiv=a.asm.M).apply(null,arguments)},W0=a._FusedBatchNorm=function(){return(W0=a._FusedBatchNorm=a.asm.N).apply(null,arguments)},V0=a._FusedConv2D=function(){return(V0=a._FusedConv2D=a.asm.O).apply(null,arguments)},U0=a._FusedDepthwiseConv2D=function(){return(U0=a._FusedDepthwiseConv2D=a.asm.P).apply(null,arguments)},Ge=a._Gather=function(){return(Ge=a._Gather=a.asm.Q).apply(null,arguments)},G0=a._GatherNd=function(){return(G0=a._GatherNd=a.asm.R).apply(null,arguments)},H0=a._Greater=function(){return(H0=a._Greater=a.asm.S).apply(null,arguments)},j0=a._GreaterEqual=function(){return(j0=a._GreaterEqual=a.asm.T).apply(null,arguments)},q0=a._LeakyRelu=function(){return(q0=a._LeakyRelu=a.asm.U).apply(null,arguments)},X0=a._Less=function(){return(X0=a._Less=a.asm.V).apply(null,arguments)},K0=a._LessEqual=function(){return(K0=a._LessEqual=a.asm.W).apply(null,arguments)},wc=a._Log=function(){return(wc=a._Log=a.asm.X).apply(null,arguments)},_p=a._LogicalAnd=function(){return(_p=a._LogicalAnd=a.asm.Y).apply(null,arguments)},Pp=a._Max=function(){return(Pp=a._Max=a.asm.Z).apply(null,arguments)},Z0=a._MaxPool=function(){return(Z0=a._MaxPool=a.asm._).apply(null,arguments)},Y0=a._Maximum=function(){return(Y0=a._Maximum=a.asm.$).apply(null,arguments)},J0=a._Mean=function(){return(J0=a._Mean=a.asm.aa).apply(null,arguments)},Q0=a._Min=function(){return(Q0=a._Min=a.asm.ba).apply(null,arguments)},eg=a._Minimum=function(){return(eg=a._Minimum=a.asm.ca).apply(null,arguments)},tg=a._MirrorPad=function(){return(tg=a._MirrorPad=a.asm.da).apply(null,arguments)},ng=a._Multiply=function(){return(ng=a._Multiply=a.asm.ea).apply(null,arguments)},dt=a._Neg=function(){return(dt=a._Neg=a.asm.fa).apply(null,arguments)},sg=a._NonMaxSuppressionV3=function(){return(sg=a._NonMaxSuppressionV3=a.asm.ga).apply(null,arguments)},rg=a._NonMaxSuppressionV4=function(){return(rg=a._NonMaxSuppressionV4=a.asm.ha).apply(null,arguments)},ag=a._NonMaxSuppressionV5=function(){return(ag=a._NonMaxSuppressionV5=a.asm.ia).apply(null,arguments)},$l=a._NotEqual=function(){return($l=a._NotEqual=a.asm.ja).apply(null,arguments)},Fp=a._OneHot=function(){return(Fp=a._OneHot=a.asm.ka).apply(null,arguments)},Op=a._PadV2=function(){return(Op=a._PadV2=a.asm.la).apply(null,arguments)},Mp=a._Pow=function(){return(Mp=a._Pow=a.asm.ma).apply(null,arguments)},og=a._Prelu=function(){return(og=a._Prelu=a.asm.na).apply(null,arguments)},ig=a._Prod=function(){return(ig=a._Prod=a.asm.oa).apply(null,arguments)},zp=a._RealDiv=function(){return(zp=a._RealDiv=a.asm.pa).apply(null,arguments)},lg=a._Relu=function(){return(lg=a._Relu=a.asm.qa).apply(null,arguments)},ug=a._Relu6=function(){return(ug=a._Relu6=a.asm.ra).apply(null,arguments)},cg=a._ResizeBilinear=function(){return(cg=a._ResizeBilinear=a.asm.sa).apply(null,arguments)},dg=a._Reverse=function(){return(dg=a._Reverse=a.asm.ta).apply(null,arguments)},pg=a._RotateWithOffset=function(){return(pg=a._RotateWithOffset=a.asm.ua).apply(null,arguments)},Lp=a._Round=function(){return(Lp=a._Round=a.asm.va).apply(null,arguments)},ma=a._Rsqrt=function(){return(ma=a._Rsqrt=a.asm.wa).apply(null,arguments)},hg=a._ScatterNd=function(){return(hg=a._ScatterNd=a.asm.xa).apply(null,arguments)},fg=a._SelectV2=function(){return(fg=a._SelectV2=a.asm.ya).apply(null,arguments)},Bb=a._Sigmoid=function(){return(Bb=a._Sigmoid=a.asm.za).apply(null,arguments)},Bp=a._Sin=function(){return(Bp=a._Sin=a.asm.Aa).apply(null,arguments)},mg=a._Softmax=function(){return(mg=a._Softmax=a.asm.Ba).apply(null,arguments)},gg=a._Sqrt=function(){return(gg=a._Sqrt=a.asm.Ca).apply(null,arguments)},Ag=a._Square=function(){return(Ag=a._Square=a.asm.Da).apply(null,arguments)},yg=a._SquaredDifference=function(){return(yg=a._SquaredDifference=a.asm.Ea).apply(null,arguments)},xg=a._Step=function(){return(xg=a._Step=a.asm.Fa).apply(null,arguments)},bg=a._StridedSlice=function(){return(bg=a._StridedSlice=a.asm.Ga).apply(null,arguments)},vg=a._Sub=function(){return(vg=a._Sub=a.asm.Ha).apply(null,arguments)},wg=a._Sum=function(){return(wg=a._Sum=a.asm.Ia).apply(null,arguments)},kg=a._Tan=function(){return(kg=a._Tan=a.asm.Ja).apply(null,arguments)},Ig=a._Tanh=function(){return(Ig=a._Tanh=a.asm.Ka).apply(null,arguments)},Sg=a._Tile=function(){return(Sg=a._Tile=a.asm.La).apply(null,arguments)},Cg=a._TopK=function(){return(Cg=a._TopK=a.asm.Ma).apply(null,arguments)},Tg=a._Transform=function(){return(Tg=a._Transform=a.asm.Na).apply(null,arguments)},Ng=a._Transpose=function(){return(Ng=a._Transpose=a.asm.Oa).apply(null,arguments)},Eg=a.__FusedMatMul=function(){return(Eg=a.__FusedMatMul=a.asm.Pa).apply(null,arguments)},Rg=a._malloc=function(){return(Rg=a._malloc=a.asm.Qa).apply(null,arguments)},$g=a._free=function(){return($g=a._free=a.asm.Ra).apply(null,arguments)},Wp=a.stackSave=function(){return(Wp=a.stackSave=a.asm.Ta).apply(null,arguments)},Vp=a.stackRestore=function(){return(Vp=a.stackRestore=a.asm.Ua).apply(null,arguments)},kc=a.stackAlloc=function(){return(kc=a.stackAlloc=a.asm.Va).apply(null,arguments)};a.cwrap=ee;var Dl;function Dg(re){this.name="ExitStatus",this.message="Program terminated with exit("+re+")",this.status=re}wr=function re(){Dl||Ic(),Dl||(wr=re)};function Ic(re){if(re=re||u,Rn>0||(On(),Rn>0))return;function oe(){Dl||(Dl=!0,a.calledRun=!0,!M&&(ds(),Ls(),o(a),a.onRuntimeInitialized&&a.onRuntimeInitialized(),Is()))}a.setStatus?(a.setStatus("Running..."),setTimeout(function(){setTimeout(function(){a.setStatus("")},1),oe()},1)):oe()}if(a.run=Ic,a.preInit)for(typeof a.preInit=="function"&&(a.preInit=[a.preInit]);a.preInit.length>0;)a.preInit.pop()();return Ic(),r.ready}}();typeof e=="object"&&typeof t=="object"?t.exports=n:typeof define=="function"&&define.amd?define([],function(){return n}):typeof e=="object"&&(e.WasmBackendModule=n)}}),VN=1e-7,UN=1e-4,Dc=class{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}},Ll=class{refCount(e){return Vs("refCount")}incRef(e){return Vs("incRef")}timerAvailable(){return!0}time(e){return Vs("time")}read(e){return Vs("read")}readSync(e){return Vs("readSync")}numDataIds(){return Vs("numDataIds")}disposeData(e,t){return Vs("disposeData")}write(e,t,n){return Vs("write")}move(e,t,n,s,r){return Vs("move")}memory(){return Vs("memory")}floatPrecision(){return Vs("floatPrecision")}epsilon(){return this.floatPrecision()===32?VN:UN}dispose(){return Vs("dispose")}};function Vs(e){throw new Error(`'${e}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}function n5(e){let t=e.length,n=0;for(;t>0;)n=Math.random()*t|0,t--,Zp(e,t,n)}function GN(e,t){if(e.length!==t.length)throw new Error(`Array sizes must match to be shuffled together First array length was ${e.length}Second array length was ${t.length}`);let n=e.length,s=0;for(;n>0;)s=Math.random()*n|0,n--,Zp(e,n,s),Zp(t,n,s)}function _c(e,t,n){return Math.max(e,Math.min(t,n))}function HN(e){return e%2==0?e:e+1}function Zp(e,t,n){let s=e[t];e[t]=e[n],e[n]=s}function jN(e){let t=0;for(let n=0;nn+` Shapes ${e} and ${t} must match`)}function ei(e){O(e!=null,()=>"The input to the tensor constructor must be a non-null value.")}function ti(e,t=[],n=!1){if(t==null&&(t=[]),Array.isArray(e)||Dn(e)&&!n)for(let s=0;s0,n){return new Promise((s,r)=>{let a=0,o=()=>{if(e()){s();return}a++;let i=t(a);if(n!=null&&a>=n){r();return}setTimeout(o,i)};o()})}function eE(e,t){let n=1,s=-1;for(let a=0;a=0)n*=e[a];else if(e[a]===-1){if(s!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${s} and dim ${a}`);s=a}else if(e[a]<0)throw Error(`Shapes can not be < 0. Found ${e[a]} at dim ${a}`);if(s===-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}`);let r=e.slice();return r[s]=t/n,r}function Us(e,t){let n=t.length;return e=e==null?t.map((s,r)=>r):[].concat(e),O(e.every(s=>s>=-n&&s`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`),O(e.every(s=>mn(s)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(s=>s<0?n+s:s)}function s5(e,t){let n=[],s=[],r=t!=null&&Array.isArray(t)&&t.length===0,a=t==null||r?null:Us(t,e).sort(),o=0;for(let i=0;ii)&&e[i]===1&&(n.push(e[i]),s.push(i)),a[o]<=i&&o++}e[i]!==1&&(n.push(e[i]),s.push(i))}return{newShape:n,keptDims:s}}function r5(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 a5(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 o5(e,t){for(let n=0;nt+=n.length),t}function ba(e){return typeof e=="string"||e instanceof String}function u5(e){return typeof e=="boolean"}function c5(e){return typeof e=="number"}function Yp(e){return Array.isArray(e)?Yp(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":c5(e)?"float32":ba(e)?"string":u5(e)?"bool":"float32"}function va(e){return!!(e&&e.constructor&&e.call&&e.apply)}function Jp(e,t){for(let n=t;n=0;--s)n[s]=n[s+1]*e[s+1];return n}function d5(e,t,n,s=!1){let r=new Array;if(t.length===1){let a=t[0]*(s?2:1);for(let o=0;ol*c)*(s?2:1);for(let l=0;lr*a)*(n?2:1);if(s===0)return[];if(s!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${n?" for a complex tensor":""}.`);return d5(0,e,t,n)}function Lg(e,t){let n=Qp(e,t);for(let s=0;ss*r,1);if(t==null||t==="float32")return Wl(e,new Float32Array(n));if(t==="int32")return Wl(e,new Int32Array(n));if(t==="bool")return Wl(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function Bg(e){e.forEach(t=>{O(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function sE(e,t,n){if(t===0)return 0;if(t===1)return e[0];let s=e[e.length-1];for(let r=0;r{let[s,r]=n.split(":");this.urlFlags[s]=lE(s,r)})}};function oE(e){let t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(n,...s)=>(iE(t,s[0],s[1]),s.join("="))),t}function iE(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}function lE(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 K(){return Ir}var Ir=null;function uE(e){Ir=e}var Vg;function f5(){if(Vg==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");Vg=e}return Vg}function cE(){let e=f5();return e._tfGlobals==null&&(e._tfGlobals=new Map),e._tfGlobals}function Ug(e,t){let n=cE();if(n.has(e))return n.get(e);{let s=t();return n.set(e,s),n.get(e)}}var ni="Abs",Vl="Acos",Ul="Acosh",Hr="Add",wa="AddN",Gl="All",Hl="Any",ka="ArgMax",jl="ArgMin",ql="Asin",Xl="Asinh",Kl="Atan",Zl="Atanh",Yl="Atan2",Ia="AvgPool",eh="AvgPoolGrad",Fc="AvgPool3D",th="AvgPool3DGrad",Sa="BatchMatMul",si="BatchToSpaceND",nh="Bincount",m5="BroadcastTo",sh="BroadcastArgs",Ca="Cast",Ta="Ceil",jr="ClipByValue",Oc="Complex",Mc="ComplexAbs",ri="Concat",Na="Conv2D",rh="Conv2DBackpropFilter",Ea="Conv2DBackpropInput",zc="Conv3D",ah="Conv3DBackpropFilterV2",oh="Conv3DBackpropInputV2",Ra="Cos",$a="Cosh",ai="Cumsum",oi="CropAndResize",ih="DenseBincount",ii="DepthToSpace",Da="DepthwiseConv2dNative",lh="DepthwiseConv2dNativeBackpropFilter",uh="DepthwiseConv2dNativeBackpropInput",ch="Diag",Lc="Dilation2D",dh="Dilation2DBackpropInput",ph="Dilation2DBackpropFilter",_a="RealDiv",Bc="Einsum",Pa="Elu",hh="EluGrad",Jl="Erf",li="Equal",Fa="Exp",ui="ExpandDims",ci="Expm1",fh="FFT",Ql="Fill",di="FlipLeftRight",Oa="Floor",Ma="FloorDiv",za="FusedBatchNorm",pi="GatherV2",hi="GatherNd",fi="Greater",La="GreaterEqual",Ba="Identity",mh="IFFT",Wc="Imag",eu="IsFinite",tu="IsInf",nu="IsNan",mi="LeakyRelu",gi="Less",Ai="LessEqual",gh="LinSpace",Wa="Log",su="Log1p",yi="LogicalAnd",ru="LogicalNot",Vc="LogicalOr",g5="LogSoftmax",Uc="LRN",Ah="LRNGrad",Va="Max",Ua="Maximum",Ga="MaxPool",yh="MaxPoolGrad",Gc="MaxPool3D",xh="MaxPool3DGrad",bh="MaxPoolWithArgmax",Ha="Mean",ja="Min",qa="Minimum",Xa="MirrorPad",au="Mod",vh="Multinomial",Ka="Multiply",xi="Neg",bi="NotEqual",vi="NonMaxSuppressionV3",ou="NonMaxSuppressionV4",wi="NonMaxSuppressionV5",ki="OnesLike",Ii="OneHot",Si="Pack",Za="PadV2",dE="Pool",Ya="Pow",Ja="Prelu",Ci="Prod",iu="Range",Hc="Real",lu="Reciprocal",Qa="Relu",Ti="Reshape",uu="ResizeNearestNeighbor",wh="ResizeNearestNeighborGrad",eo="ResizeBilinear",kh="ResizeBilinearGrad",to="Relu6",Ni="Reverse",Ei="Round",no="Rsqrt",Ri="ScatterNd",$i="Select",cu="Selu",Di="Slice",so="Sin",_i="Sinh",du="Sign",ro="Sigmoid",pu="Softplus",ao="Sqrt",oo="Sum",Pi="SpaceToBatchND",Fi="SplitV",io="Softmax",Ih="SparseFillEmptyRows",Sh="SparseReshape",Ch="SparseSegmentMean",Th="SparseSegmentSum",jc="SparseToDense",lo="SquaredDifference",hu="Square",Oi="StridedSlice",qc="StringNGrams",Nh="StringSplit",Eh="StringToHashBucketFast",uo="Sub",Mi="Tan",co="Tanh",qr="Tile",zi="TopK",Li="Transform",po="Transpose",Rh="Unique",Bi="Unpack",Xc="UnsortedSegmentSum",Wi="ZerosLike",ho="Step",Kc="FromPixels",Vi="RotateWithOffset",fo="_FusedMatMul",mo="FusedConv2D",go="FusedDepthwiseConv2D",fu=Ug("kernelRegistry",()=>new Map),Zc=Ug("gradRegistry",()=>new Map);function $h(e,t){let n=Hg(e,t);return fu.get(n)}function Gg(e){return Zc.get(e)}function Xr(e){let t=fu.entries(),n=[];for(;;){let{done:s,value:r}=t.next();if(s)break;let[a,o]=r,[i]=a.split("_");i===e&&n.push(o)}return n}function Kr(e){let{kernelName:t,backendName:n}=e,s=Hg(t,n);fu.has(s)&&kr(`The kernel '${t}' for backend '${n}' is already registered`),fu.set(s,e)}function A5(e){let{kernelName:t}=e;Zc.has(t)&&K().getBool("DEBUG")&&kr(`Overriding the gradient for '${t}'`),Zc.set(t,e)}function pE(e,t){let n=Hg(e,t);if(!fu.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);fu.delete(n)}function hE(e){if(!Zc.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);Zc.delete(e)}function fE(e,t){Xr(e).forEach(s=>{let r=Object.assign({},s,{backendName:t});Kr(r)})}function Hg(e,t){return`${t}_${e}`}var v={};ze(v,{arraysEqual:()=>Gr,assert:()=>O,assertNonNegativeIntegerDimensions:()=>Bg,assertNonNull:()=>ei,assertShapesMatch:()=>zn,bytesFromStringArray:()=>l5,bytesPerElement:()=>zg,checkConversionForErrors:()=>o5,clamp:()=>_c,computeStrides:()=>Bl,createScalarValue:()=>bE,createShuffledIndices:()=>JN,decodeString:()=>Ph,distSquared:()=>XN,encodeString:()=>Qc,fetch:()=>wE,fingerPrint64:()=>xE,flatten:()=>ti,getArrayFromDType:()=>a5,getTypedArrayFromDType:()=>r5,hasEncodingLoss:()=>tE,hexToLong:()=>Yc,indexToLoc:()=>rE,inferDtype:()=>Yp,inferFromImplicitShape:()=>eE,isBoolean:()=>u5,isFunction:()=>va,isInt:()=>mn,isNumber:()=>c5,isPromise:()=>Wg,isScalarShape:()=>KN,isString:()=>ba,isTypedArray:()=>Dn,isValidDtype:()=>i5,locToIndex:()=>sE,makeOnesTypedArray:()=>Lg,makeZerosNestedTypedArray:()=>nE,makeZerosTypedArray:()=>Qp,nearestDivisor:()=>Jp,nearestLargerEven:()=>HN,now:()=>Jc,parseAxisParam:()=>Us,randUniform:()=>qN,repeatedTry:()=>QN,rightPad:()=>Pc,shuffle:()=>n5,shuffleCombo:()=>GN,sizeFromShape:()=>Ut,sizeToSquarishShape:()=>YN,squeezeShape:()=>s5,sum:()=>jN,swap:()=>Zp,tanh:()=>ZN,toNestedArray:()=>Wl,toTypedArray:()=>_h});var y5=Qo(EN()),Ui=y5.default||y5;function Yc(e){return Ui.fromString(e,!0,16)}var x5=Yc("c3a5c85c97cb3127"),Gi=Yc("b492b66fbe98f273"),Ln=Yc("9ae16a3b2f90404f");function jg(e){return e.xor(e.shru(47))}function b5(e,t,n){let s=e.slice(t,t+n);return Ui.fromBytes(Array.from(s),!0,!0)}function kt(e,t){return b5(e,t,8)}function v5(e,t){return b5(e,t,4)}function gn(e,t){return t===0?e:e.shru(t).or(e.shl(64-t))}function Ao(e,t,n=Yc("9ddfea08eb382d69")){let s=e.xor(t).mul(n);s=s.xor(s.shru(47));let r=t.xor(s).mul(n);return r=r.xor(r.shru(47)),r=r.mul(n),r}function mE(e,t,n,s,r,a){r=r.add(e),a=gn(a.add(r).add(s),21);let o=r;return r=r.add(t),r=r.add(n),a=a.add(gn(r,44)),[r.add(s),a.add(o)]}function Dh(e,t,n,s){return mE(kt(e,t),kt(e,t+8),kt(e,t+16),kt(e,t+24),n,s)}function gE(e,t=e.length){if(t>=8){let n=Ln.add(t*2),s=kt(e,0).add(Ln),r=kt(e,t-8),a=gn(r,37).mul(n).add(s),o=gn(s,25).add(r).mul(n);return Ao(a,o,n)}if(t>=4){let n=Ln.add(t*2),s=v5(e,0);return Ao(s.shl(3).add(t),v5(e,t-4),n)}if(t>0){let n=e[0],s=e[t>>1],r=e[t-1],a=n+(s<<8),o=t+(r<<2);return jg(Ln.mul(a).xor(x5.mul(o))).mul(Ln)}return Ln}function AE(e,t=e.length){let n=Ln.add(t*2),s=kt(e,0).mul(Gi),r=kt(e,8),a=kt(e,t-8).mul(n),o=kt(e,t-16).mul(Ln);return Ao(gn(s.add(r),43).add(gn(a,30)).add(o),s.add(gn(r.add(Ln),18)).add(a),n)}function yE(e,t=e.length){let n=Ln.add(t*2),s=kt(e,0).mul(Ln),r=kt(e,8),a=kt(e,t-8).mul(n),o=kt(e,t-16).mul(Ln),i=gn(s.add(r),43).add(gn(a,30)).add(o),l=Ao(i,s.add(gn(r.add(Ln),18)).add(a),n),c=kt(e,16).mul(n),u=kt(e,24),d=i.add(kt(e,t-32)).mul(n),p=l.add(kt(e,t-24)).mul(n);return Ao(gn(c.add(u),43).add(gn(d,30)).add(p),c.add(gn(u.add(s),18)).add(d),n)}function xE(e,t=e.length){let n=Ui.fromNumber(81,!0);if(t<=32)return t<=16?gE(e,t):AE(e,t);if(t<=64)return yE(e,t);let s=n,r=n.mul(Gi).add(113),a=jg(r.mul(Ln).add(113)).mul(Ln),o=[Ui.UZERO,Ui.UZERO],i=[Ui.UZERO,Ui.UZERO];s=s.mul(Ln).add(kt(e,0));let l=0,c=(t-1>>6)*64,u=c+(t-1&63)-63;do s=gn(s.add(r).add(o[0]).add(kt(e,l+8)),37).mul(Gi),r=gn(r.add(o[1]).add(kt(e,l+48)),42).mul(Gi),s=s.xor(i[1]),r=r.add(o[0]).add(kt(e,l+40)),a=gn(a.add(i[0]),33).mul(Gi),o=Dh(e,l,o[1].mul(Gi),s.add(i[0])),i=Dh(e,l+32,a.add(i[1]),r.add(kt(e,l+16))),[a,s]=[s,a],l+=64;while(l!==c);let d=Gi.add(a.and(255).shl(1));return l=u,i[0]=i[0].add(t-1&63),o[0]=o[0].add(i[0]),i[0]=i[0].add(o[0]),s=gn(s.add(r).add(o[0]).add(kt(e,l+8)),37).mul(d),r=gn(r.add(o[1]).add(kt(e,l+48)),42).mul(d),s=s.xor(i[1].mul(9)),r=r.add(o[0].mul(9).add(kt(e,l+40))),a=gn(a.add(i[0]),33).mul(d),o=Dh(e,l,o[1].mul(d),s.add(i[0])),i=Dh(e,l+32,a.add(i[1]),r.add(kt(e,l+16))),[a,s]=[s,a],Ao(Ao(o[0],i[0],d).add(jg(r).mul(x5)).add(a),Ao(o[1],i[1],d).add(s),d)}function bE(e,t){return t==="string"?Qc(e):_h([e],t)}function vE(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function _h(e,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=ti(e)),K().getBool("DEBUG")&&o5(e,t),vE(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"){let n=new Uint8Array(e.length);for(let s=0;s{s=n()},a,o=Jc();if(this.backendTimer.timerAvailable())a=this.backendTimer.time(r);else{r();for(let l of s)l.dataSync();a=Promise.resolve({kernelMs:Jc()-o})}if(K().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let l=0;l{IE(u,c.dtype,e)})}return{kernelName:e,outputs:s,inputs:t,timeMs:a.then(l=>l.kernelMs),extraInfo:a.then(l=>l.getExtraProfileInfo!=null?l.getExtraProfileInfo():"")}}logKernelProfile(e){let{kernelName:t,outputs:n,timeMs:s,inputs:r,extraInfo:a}=e;n.forEach(o=>{Promise.all([o.data(),s,a]).then(i=>{this.logger.logKernelProfile(t,o,i[0],i[1],r,i[2])})})}};function IE(e,t,n){if(t!=="float32")return!1;for(let s=0;s0?f:""} `}}console.log(`%c${i} %c${o} %c${l}D ${u} %c${c} %c${d} %c${a}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}};function CE(e,t,n){let s={},r={};for(let l=0;ls[m.id]=!0),h=!0,r[c.id]=!0;break}if(h)break}}let a={};a[n.id]=!0;let o={};for(let l=e.length-1;l>=0;l--){let c=e[l],u=c.inputs;for(let d=0;d=0;r--){let a=t[r],o=[];if(a.outputs.forEach(l=>{let c=e[l.id];c!=null?o.push(c):o.push(null)}),a.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${a.kernelName}.`);let i=a.gradient(o);for(let l in a.inputs){if(!(l in i))throw new Error(`Cannot backprop through input ${l}. Available gradients found: ${Object.keys(i)}.`);let c=n(()=>i[l]());if(c.dtype!=="float32")throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input ${l} must have 'float32' dtype, but has '${c.dtype}'`);let u=a.inputs[l];if(!Gr(c.shape,u.shape))throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input '${l}' has shape '${c.shape}', which does not match the shape of the input '${u.shape}'`);if(e[u.id]==null)e[u.id]=c;else{let d=e[u.id];e[u.id]=s(d,c),d.dispose()}}}}var w5=20,ed=3,qg=7;function NE(e,t,n,s){let r=Bl(t),a=EE(e,t,n,r),o=t.length,i=Fh(e,t,n,r,a),l=["Tensor"];return s&&(l.push(` dtype: ${n}`),l.push(` rank: ${o}`),l.push(` shape: [${t}]`),l.push(" values:")),l.push(i.map(c=>" "+c).join(` `)),l.join(` `)}function EE(e,t,n,s){let r=Ut(t),a=s[s.length-1],o=new Array(a).fill(0),i=t.length,l=n==="complex64"?nd(e):e;if(i>1)for(let c=0;cw5){let g=ed*o,A=Array.from(e.slice(0,g)),y=Array.from(e.slice((i-ed)*o,i*o));return n==="complex64"&&(A=nd(A),y=nd(y)),["["+A.map((x,b)=>td(x,r[b],n)).join(", ")+", ..., "+y.map((x,b)=>td(x,r[i-ed+b],n)).join(", ")+"]"]}let m=n==="complex64"?nd(e):Array.from(e);return["["+m.map((g,A)=>td(g,r[A],n)).join(", ")+"]"]}let c=t.slice(1),u=s.slice(1),d=s[0]*o,p=[];if(i>w5){for(let m=0;m`Length of values '${s}' 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||a5(t,this.size),this.strides=Bl(e)}set(e,...t){t.length===0&&(t=[0]),O(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);let n=this.locToIndex(t);this.values[n]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(let s of e){if(s<0||s>=this.shape[t]){let r=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(r)}t++}let n=e[e.length-1];for(let s=0;sPh(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();let e=Sr().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>Ph(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();let e=await Sr().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(Sr().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return mu.print(this,e)}clone(){return this.throwIfDisposed(),mu.clone(this)}toString(e=!1){let t=this.dataSync();return NE(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),mu.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Sr().makeVariable(this,e,t,n)}};Object.defineProperty(Ye,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});function PE(){return Ug("Tensor",()=>Ye)}PE();var sd=class extends Ye{constructor(e,t,n,s){super(e.shape,e.dtype,e.dataId,s);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(!Gr(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Sr().disposeTensor(this),this.dataId=e.dataId,Sr().incRef(this,null)}dispose(){Sr().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(sd,Symbol.hasInstance,{value:e=>e instanceof Ye&&e.assign!=null&&e.assign instanceof Function});var rr={};ze(rr,{assertTypesMatch:()=>I5,getTensorsInContainer:()=>Qg,isTensorInList:()=>OE,makeTypesMatch:()=>Ft});var Xg;(function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"})(Xg||(Xg={}));var Kg;(function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"})(Kg||(Kg={}));var Zg;(function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"})(Zg||(Zg={}));var Yg;(function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"})(Yg||(Yg={}));var Jg;(function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"})(Jg||(Jg={}));var FE={float32:Yg,int32:Kg,bool:Zg,complex64:Jg};function Bn(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return FE[e][t]}function rd(e){return Bn(e,"int32")}function Ft(e,t){if(e.dtype===t.dtype)return[e,t];let n=Bn(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function I5(e,t){O(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function OE(e,t){return t.some(n=>n.id===e.id)}function Qg(e){let t=[],n=new Set;return S5(e,t,n),t}function S5(e,t,n){if(e==null)return;if(e instanceof Ye){t.push(e);return}if(!ME(e))return;let s=e;for(let r in s){let a=s[r];n.has(a)||(n.add(a),S5(a,t,n))}}function ME(e){return Array.isArray(e)||typeof e=="object"}function e2(e){return e.kernelName!=null}var C5=class{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,get kernelNames(){return Array.from(new Set(this.kernels.map(e=>e.name)))}}}dispose(){for(let e in this.registeredVariables)this.registeredVariables[e].dispose()}},t2=class{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new C5}async ready(){if(this.pendingBackendInit!=null)return this.pendingBackendInit.then(()=>{});if(this.backendInstance!=null)return;let e=this.getSortedBackends();for(let t=0;t{t.setupFunc!=null&&t.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){Xr(e).forEach(n=>{n.disposeFunc!=null&&n.disposeFunc(this.registry[e])})}initializeBackend(e){let t=this.registryFactory[e];if(t==null)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{let n=t.factory();if(n&&!(n instanceof Ll)&&typeof n.then=="function"){let s=++this.pendingBackendInitId,r=n.then(a=>s(sthis.registryFactory[t].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){let e=this.getSortedBackends();for(let t=0;tthis.startScope(n),()=>this.endScope(s),()=>(s=t(),s instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),s))}scopedRun(e,t,n){e();try{let s=n();return t(),s}catch(s){throw t(),s}}nextTensorId(){return t2.nextTensorId++}nextVariableId(){return t2.nextVariableId++}clone(e){let t=B.runKernel(Ba,{x:e}),n={x:e},s=a=>({x:()=>{let o="float32",i={x:a},l={dtype:o};return B.runKernel(Ca,i,l)}}),r=[];return this.addTapeNode(this.state.activeScope.name,n,[t],s,r,{}),t}runKernel(e,t,n){if(this.backendName==null&&this.backend,!($h(e,this.backendName)!=null))throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){let s=this.backend.numDataIds(),r=0;n.forEach(i=>{r+=i.dtype==="complex64"?3:1});let a=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],o=s-t-r-a;if(o>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${o} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[],s=this.isTapeOn(),r=this.state.numBytes,a=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let o;this.backendName==null&&this.backend;let i,l=e2(e)?e.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(e2(e)){let{kernelName:h,inputs:f,attrs:m}=e;this.backendName==null&&this.backend;let g=$h(h,this.backendName);O(g!=null,()=>`Cannot find registered kernel '${h}' for backend '${this.backendName}'`),o=()=>{let A=this.backend.numDataIds();i=g.kernelFunc({inputs:f,attrs:m,backend:this.backend});let y=Array.isArray(i)?i:[i];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(h,A,y);let x=y.map(b=>{if(b.rank!=null)return b;let{dataId:w,shape:k,dtype:S}=b;return this.makeTensorFromDataId(w,k,S)});if(s){let b=this.getTensorsForGradient(h,f,x);n=this.saveTensorsForBackwardMode(b)}return x}}else{let{forwardFunc:h}=e,f=m=>{!s||(n=m.map(g=>this.keep(this.clone(g))))};o=()=>{let m=this.backend.numDataIds();i=this.tidy(()=>h(this.backend,f));let g=Array.isArray(i)?i:[i];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,m,g),g}}let{inputs:c,attrs:u}=e,d=e2(e)?null:e.backwardsFunc,p;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?t=o():(p=this.profiler.profileKernel(l,c,()=>o()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(p),t=p.outputs)}),s&&this.addTapeNode(l,c,t,d,n,u),this.state.profiling&&this.state.activeProfile.kernels.push({name:l,bytesAdded:this.state.numBytes-r,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-a,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(c).map(h=>c[h]!=null?c[h].shape:null),outputShapes:t.map(h=>h.shape),kernelTimeMs:p.timeMs,extraInfo:p.extraInfo}),Array.isArray(i)?t:t[0]}saveTensorsForBackwardMode(e){return e.map(n=>this.keep(this.clone(n)))}getTensorsForGradient(e,t,n){let s=Gg(e);if(s!=null){let r=s.inputsToSave||[],a=s.outputsToSave||[],o;s.saveAllInputs?(O(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),o=Object.keys(t).map(l=>t[l])):o=r.map(l=>t[l]);let i=n.filter((l,c)=>a[c]);return o.concat(i)}return[]}makeTensor(e,t,n,s){if(e==null)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",s=s||this.backend;let r=e;n==="string"&&ba(e[0])&&(r=e.map(i=>Qc(i)));let a=s.write(r,t,n),o=new Ye(t,n,a,this.nextTensorId());if(this.trackTensor(o,s),n==="string"){let i=this.state.tensorInfo.get(a),l=l5(r);this.state.numBytes+=l-i.bytes,i.bytes=l}return o}makeTensorFromDataId(e,t,n,s){n=n||"float32";let r=new Ye(t,n,e,this.nextTensorId());return this.trackTensor(r,s),r}makeVariable(e,t=!0,n,s){n=n||this.nextVariableId().toString(),s!=null&&s!==e.dtype&&(e=e.cast(s));let r=new sd(e,t,n,this.nextTensorId());if(this.state.registeredVariables[r.name]!=null)throw new Error(`Variable with name ${r.name} was already registered`);return this.state.registeredVariables[r.name]=r,this.incRef(r,this.backend),r}trackTensor(e,t){this.state.numTensors++,e.dtype==="string"&&this.state.numStringTensors++;let n=0;e.dtype!=="complex64"&&e.dtype!=="string"&&(n=e.size*zg(e.dtype)),this.state.numBytes+=n,this.state.tensorInfo.has(e.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:n})),e instanceof sd||this.track(e)}incRef(e,t){this.trackTensor(e,t),this.backend.incRef(e.dataId)}removeDataId(e,t){this.state.tensorInfo.has(e)&&this.state.tensorInfo.get(e).backend===t&&(this.state.tensorInfo.delete(e),this.state.numDataBuffers--)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;let t=this.state.tensorInfo.get(e.dataId);if(this.state.numTensors--,e.dtype==="string"&&(this.state.numStringTensors--,this.state.numBytes-=t.bytes),e.dtype!=="complex64"&&e.dtype!=="string"){let n=e.size*zg(e.dtype);this.state.numBytes-=n}t.backend.disposeData(e.dataId)&&this.removeDataId(e.dataId,t.backend)}disposeVariables(){for(let e in this.state.registeredVariables){let 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(){let 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;let 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(s=>s.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(let s of this.state.activeProfile.kernels)s.kernelTimeMs=await s.kernelTimeMs,s.extraInfo=await s.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(e,t,n,s,r,a){let o={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:r},i=Gg(e);i!=null&&(s=i.gradFunc),s!=null&&(o.gradient=l=>(l=l.map((c,u)=>{if(c==null){let d=n[u],p=Qp(d.size,d.dtype);return this.makeTensor(p,d.shape,d.dtype)}return c}),s(l.length>1?l:l[0],r,a))),this.state.activeTape.push(o)}keep(e){return e.kept=!0,e}startTape(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){let t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){let t=Qg(e),n=new Set(t.map(r=>r.id));for(let r=0;r{!r.kept&&r.scopeId===s.id&&this.track(r)})}gradients(e,t,n,s=!1){if(O(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}'`);let r=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));O(r instanceof Ye,()=>"The result y returned by f() must be a tensor.");let a=CE(this.state.activeTape,t,r);if(!s&&a.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",()=>{let o={};o[r.id]=n==null?zE(r.shape):n,TE(o,a,l=>this.tidy(l),LE);let i=t.map(l=>o[l.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(l=>{for(let c of l.saved)c.dispose()}),this.state.activeTape=null),{value:r,grads:i}})}customGrad(e){return O(va(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{O(t.every(o=>o instanceof Ye),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let n,s={};t.forEach((o,i)=>{s[i]=o});let r=(o,i)=>(n=e(...t,i),O(n.value instanceof Ye,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),O(va(n.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),n.value),a=(o,i)=>{let l=n.gradFunc(o,i),c=Array.isArray(l)?l:[l];O(c.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(...)."),O(c.every(d=>d instanceof Ye),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");let u={};return c.forEach((d,p)=>{u[p]=()=>d}),u};return this.runKernelFunc({forwardFunc:r,backwardsFunc:a,inputs:s})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}async time(e){let t=Jc(),n=await this.backend.time(e);return n.wallMs=Jc()-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 C5;for(let e in this.registry)this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}},n2=t2;n2.nextTensorId=0;n2.nextVariableId=0;function zE(e){let t=Lg(Ut(e),"float32");return B.makeTensor(t,e,"float32")}function T5(){let e=f5();if(e._tfengine==null){let t=new h5(e);e._tfengine=new n2(t)}return uE(e._tfengine.ENV),$E(()=>e._tfengine),e._tfengine}var B=T5();function LE(e,t){let n={a:e,b:t};return B.runKernel(Hr,n)}var gu={};ze(gu,{isBrowser:()=>N5,isMobile:()=>VE,mockIsMobile:()=>WE});function BE(){return typeof navigator!="undefined"&&navigator!=null}var s2;function WE(e){s2=e}function VE(e){if(s2!==void 0)return s2;if(e||BE()){if(e||(e=navigator),e.product==="ReactNative")return!0;let t=e.userAgent||e.vendor||(typeof window!="undefined"?window.opera:"");if(!t){let n=e;return n.userAgentData&&n.userAgentData.mobile}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(t)||/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(t.substr(0,4))}return!1}function N5(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var ar=K();ar.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.")});ar.registerFlag("IS_BROWSER",()=>N5());ar.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");ar.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));ar.registerFlag("PROD",()=>!1);ar.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>ar.getBool("DEBUG"));ar.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);ar.registerFlag("IS_TEST",()=>!1);ar.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>!0);ar.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1);function Cr(e,t){let n=e;if(Dn(e))return t==="string"?[]:[e.length];if(!Array.isArray(e))return[];let s=[];for(;Array.isArray(n)||Dn(n)&&t!=="string";)s.push(n.length),n=n[0];return Array.isArray(e)&&K().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&E5(e,s,[]),s}function E5(e,t,n){if(n=n||[],!Array.isArray(e)&&!Dn(e)){O(t.length===0,()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}O(t.length>0,()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`),O(e.length===t[0],()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`);let s=t.slice(1);for(let r=0;r=0&&(r=s),R5(s,r,t,n),e==null||!Dn(e)&&!Array.isArray(e)&&typeof e!="number"&&typeof e!="boolean"&&typeof e!="string"){let l=e==null?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${n}' must be a Tensor or TensorLike, but got '${l}'`)}let a=Cr(e,r);!Dn(e)&&!Array.isArray(e)&&(e=[e]);let i=r!=="string"?_h(e,r):ti(e,[],!0);return B.makeTensor(i,a,r)}function ad(e,t,n,s="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);return e.map((a,o)=>D(a,`${t}[${o}]`,n,s))}var $5="__op";function V(e){let 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],s=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1)),n=n+$5;let r=(...a)=>{B.startScope(n);try{let o=s(...a);return Wg(o)&&console.error("Cannot return a Promise inside of tidy."),B.endScope(o),o}catch(o){throw B.endScope(null),o}};return Object.defineProperty(r,"name",{value:n,configurable:!0}),r}function UE(e,t){let n=D(e,"real","complex"),s=D(t,"imag","complex");zn(n.shape,s.shape,`real and imag shapes, ${n.shape} and ${s.shape}, must match in call to tf.complex().`);let r={real:n,imag:s};return B.runKernel(Oc,r)}var yo=V({complex_:UE});function xo(e,t,n,s){if(s==null&&(s=Yp(e)),s==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!Dn(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){Bg(t);let r=Ut(t),a=Ut(n);O(r===a,()=>`Based on the provided shape, [${t}], the tensor should have ${r} values but has ${a}`);for(let o=0;o`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `)}}return!Dn(e)&&!Array.isArray(e)&&(e=[e]),t=t||n,e=s!=="string"?_h(e,s):ti(e,[],!0),B.makeTensor(e,t,s)}function Gt(e,t,n){let s=Cr(e,n);return xo(e,t,s,n)}var r2={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8},Oh=4;async function GE(e,t){let n=[],s=[],r=Array.isArray(e)?e.map(o=>o.name):Object.keys(e);for(let o=0;o{let p=await l.bytes(),h=p.reduce((g,A)=>g+A.length,0)+Oh*p.length,f=new Uint8Array(h),m=0;for(let g=0;g{if(t+=a.byteLength,n.push(a.byteLength===a.buffer.byteLength?a:new a.constructor(a)),!(a instanceof Float32Array||a instanceof Int32Array||a instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${a.constructor.name}`)});let s=new Uint8Array(t),r=0;return n.forEach(a=>{s.set(new Uint8Array(a.buffer),r),r+=a.byteLength}),s.buffer}var a2=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function _5(e){return a2?Buffer.byteLength(e):new Blob([e]).size}function jE(e){if(a2)return Buffer.from(e).toString("base64");let t=new Uint8Array(e),n="";for(let s=0,r=t.length;s{t+=r.byteLength});let n=new Uint8Array(t),s=0;return e.forEach(r=>{n.set(new Uint8Array(r),s),s+=r.byteLength}),n.buffer}function P5(e){let t="/";for(e=e.trim();e.endsWith(t);)e=e.slice(0,e.length-1);let n=e.split(t);return n[n.length-1]}function F5(e,t){let n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:t};return e.signature!=null&&(n.signature=e.signature),e.userDefinedMetadata!=null&&(n.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(n.modelInitializer=e.modelInitializer),e.trainingConfig!=null&&(n.trainingConfig=e.trainingConfig),n}async function i2(e,t){let n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};if(e.trainingConfig!=null&&(n.trainingConfig=e.trainingConfig),e.weightsManifest!=null){let[s,r]=await t(e.weightsManifest);n.weightSpecs=s,n.weightData=r}return e.signature!=null&&(n.signature=e.signature),e.userDefinedMetadata!=null&&(n.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(n.modelInitializer=e.modelInitializer),n}function od(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:_5(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:_5(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:e.weightData.byteLength}}function XE(){let e=n=>{let s=n<<13,r=0;for(;(s&8388608)==0;)r-=8388608,s<<=1;return s&=~8388608,r+=947912704,s|r},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 KE(){let 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 ZE(){let e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function YE(){let e=XE(),t=KE(),n=ZE();return s=>{let r=new ArrayBuffer(4*s.length),a=new Uint32Array(r);for(let o=0;o>10]+(i&1023)]+t[i>>10];a[o]=l}return new Float32Array(r)}}var Bt=class{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return Bt.instance==null&&(Bt.instance=new Bt),Bt.instance}static registerSaveRouter(e){Bt.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Bt.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Bt.getHandlers(e,"save")}static getLoadHandlers(e,t){return Bt.getHandlers(e,"load",t)}static getHandlers(e,t,n){let s=[];return(t==="load"?Bt.getInstance().loadRouters:Bt.getInstance().saveRouters).forEach(a=>{let o=a(e,n);o!==null&&s.push(o)}),s}},JE=e=>Bt.registerSaveRouter(e),QE=e=>Bt.registerLoadRouter(e),e9=e=>Bt.getSaveHandlers(e),t9=(e,t)=>Bt.getLoadHandlers(e,t),l2="tensorflowjs",u2=1,Hi="models_store",bo="model_info_store";function O5(){if(!K().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");let e=typeof window=="undefined"?self:window,t=e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB||e.shimIndexedDB;if(t==null)throw new Error("The current browser does not appear to support IndexedDB.");return t}function c2(e){let t=e.result;t.createObjectStore(Hi,{keyPath:"modelPath"}),t.createObjectStore(bo,{keyPath:"modelPath"})}var ji=class{constructor(e){if(this.indexedDB=O5(),e==null||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return this.databaseAction(this.modelPath,e)}async load(){return this.databaseAction(this.modelPath)}databaseAction(e,t){return new Promise((n,s)=>{let r=this.indexedDB.open(l2,u2);r.onupgradeneeded=()=>c2(r),r.onsuccess=()=>{let a=r.result;if(t==null){let o=a.transaction(Hi,"readonly"),l=o.objectStore(Hi).get(this.modelPath);l.onsuccess=()=>{if(l.result==null)return a.close(),s(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));n(l.result.modelArtifacts)},l.onerror=c=>(a.close(),s(l.error)),o.oncomplete=()=>a.close()}else{let o=od(t),i=a.transaction(bo,"readwrite"),l=i.objectStore(bo),c=l.put({modelPath:this.modelPath,modelArtifactsInfo:o}),u;c.onsuccess=()=>{u=a.transaction(Hi,"readwrite");let p=u.objectStore(Hi).put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:o});p.onsuccess=()=>n({modelArtifactsInfo:o}),p.onerror=h=>{l=i.objectStore(bo);let f=l.delete(this.modelPath);f.onsuccess=()=>(a.close(),s(p.error)),f.onerror=m=>(a.close(),s(p.error))}},c.onerror=d=>(a.close(),s(c.error)),i.oncomplete=()=>{u==null?a.close():u.oncomplete=()=>a.close()}}},r.onerror=a=>s(r.error)})}};ji.URL_SCHEME="indexeddb://";var M5=e=>K().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(ji.URL_SCHEME)?n9(e.slice(ji.URL_SCHEME.length)):null;Bt.registerSaveRouter(M5);Bt.registerLoadRouter(M5);function n9(e){return new ji(e)}function s9(e){return e.startsWith(ji.URL_SCHEME)?e.slice(ji.URL_SCHEME.length):e}var r9=class{constructor(){this.indexedDB=O5()}async listModels(){return new Promise((e,t)=>{let n=this.indexedDB.open(l2,u2);n.onupgradeneeded=()=>c2(n),n.onsuccess=()=>{let s=n.result,r=s.transaction(bo,"readonly"),o=r.objectStore(bo).getAll();o.onsuccess=()=>{let i={};for(let l of o.result)i[l.modelPath]=l.modelArtifactsInfo;e(i)},o.onerror=i=>(s.close(),t(o.error)),r.oncomplete=()=>s.close()},n.onerror=s=>t(n.error)})}async removeModel(e){return e=s9(e),new Promise((t,n)=>{let s=this.indexedDB.open(l2,u2);s.onupgradeneeded=()=>c2(s),s.onsuccess=()=>{let r=s.result,a=r.transaction(bo,"readwrite"),o=a.objectStore(bo),i=o.get(e),l;i.onsuccess=()=>{if(i.result==null)return r.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{let c=o.delete(e),u=()=>{l=r.transaction(Hi,"readwrite");let p=l.objectStore(Hi).delete(e);p.onsuccess=()=>t(i.result.modelArtifactsInfo),p.onerror=h=>n(i.error)};c.onsuccess=u,c.onerror=d=>(u(),r.close(),n(i.error))}},i.onerror=c=>(r.close(),n(i.error)),a.oncomplete=()=>{l==null?r.close():l.oncomplete=()=>r.close()}},s.onerror=r=>n(s.error)})}},Zr="/",Au="tensorflowjs_models",z5="info",a9="model_topology",o9="weight_specs",i9="weight_data",l9="model_metadata";function L5(e){return{info:[Au,e,z5].join(Zr),topology:[Au,e,a9].join(Zr),weightSpecs:[Au,e,o9].join(Zr),weightData:[Au,e,i9].join(Zr),modelMetadata:[Au,e,l9].join(Zr)}}function B5(e){for(let t of Object.values(e))window.localStorage.removeItem(t)}function u9(e){let t=e.split(Zr);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(Zr)}function c9(e){return e.startsWith(qi.URL_SCHEME)?e.slice(qi.URL_SCHEME.length):e}var qi=class{constructor(e){if(!K().getBool("IS_BROWSER")||typeof window=="undefined"||typeof window.localStorage=="undefined")throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,e==null||!e)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=e,this.keys=L5(this.modelPath)}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");{let t=JSON.stringify(e.modelTopology),n=JSON.stringify(e.weightSpecs),s=od(e);try{this.LS.setItem(this.keys.info,JSON.stringify(s)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,jE(e.weightData));let r={format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,signature:e.signature!=null?e.signature:void 0,userDefinedMetadata:e.userDefinedMetadata!=null?e.userDefinedMetadata:void 0,modelInitializer:e.modelInitializer!=null?e.modelInitializer:void 0,trainingConfig:e.trainingConfig!=null?e.trainingConfig:void 0};return this.LS.setItem(this.keys.modelMetadata,JSON.stringify(r)),{modelArtifactsInfo:s}}catch(r){throw B5(this.keys),new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${s.modelTopologyBytes}, weightSpecsBytes=${s.weightSpecsBytes}, weightDataBytes=${s.weightDataBytes}.`)}}}async load(){let e=JSON.parse(this.LS.getItem(this.keys.info));if(e==null)throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);if(e.modelTopologyType!=="JSON")throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");let t={},n=JSON.parse(this.LS.getItem(this.keys.topology));if(n==null)throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);t.modelTopology=n;let s=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(s==null)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);t.weightSpecs=s;let r=this.LS.getItem(this.keys.modelMetadata);if(r!=null){let o=JSON.parse(r);t.format=o.format,t.generatedBy=o.generatedBy,t.convertedBy=o.convertedBy,o.signature!=null&&(t.signature=o.signature),o.userDefinedMetadata!=null&&(t.userDefinedMetadata=o.userDefinedMetadata),o.modelInitializer!=null&&(t.modelInitializer=o.modelInitializer),o.trainingConfig!=null&&(t.trainingConfig=o.trainingConfig)}let a=this.LS.getItem(this.keys.weightData);if(a==null)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return t.weightData=qE(a),t}};qi.URL_SCHEME="localstorage://";var W5=e=>K().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(qi.URL_SCHEME)?d9(e.slice(qi.URL_SCHEME.length)):null;Bt.registerSaveRouter(W5);Bt.registerLoadRouter(W5);function d9(e){return new qi(e)}var p9=class{constructor(){O(K().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),O(typeof window=="undefined"||typeof window.localStorage!="undefined",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){let e={},t=Au+Zr,n=Zr+z5;for(let s=0;s"scheme must not be undefined or null."),e.endsWith(yu)&&(e=e.slice(0,e.indexOf(yu))),O(e.length>0,()=>"scheme must not be an empty string.");let n=Ss.getInstance();O(n.managers[e]==null,()=>`A model store manager is already registered for scheme '${e}'.`),n.managers[e]=t}static getManager(e){let 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 Mh(e){if(e.indexOf(yu)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Ss.getSchemes().join(",")}`);return{scheme:e.split(yu)[0],path:e.split(yu)[1]}}async function V5(e,t,n=!1){O(e!==t,()=>`Old path and new path are the same: '${e}'`);let s=Bt.getLoadHandlers(e);O(s.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),O(s.length<2,()=>`Copying failed because more than one (${s.length}) load handlers for source URL ${e}.`);let r=s[0],a=Bt.getSaveHandlers(t);O(a.length>0,()=>`Copying failed because no save handler is found for destination URL ${t}.`),O(a.length<2,()=>`Copying failed because more than one (${s.length}) save handlers for destination URL ${t}.`);let o=a[0],i=Mh(e).scheme,l=Mh(e).path,c=i===Mh(e).scheme,u=await r.load();n&&c&&await Ss.getManager(i).removeModel(l);let d=await o.save(u);return n&&!c&&await Ss.getManager(i).removeModel(l),d.modelArtifactsInfo}async function h9(){let e=Ss.getSchemes(),t={};for(let n of e){let s=await Ss.getManager(n).listModels();for(let r in s){let a=n+yu+r;t[a]=s[r]}}return t}async function f9(e){let t=Mh(e);return Ss.getManager(t.scheme).removeModel(t.path)}async function m9(e,t){return V5(e,t,!1)}async function g9(e,t){return V5(e,t,!0)}var A9=class{fetch(e,t){return fetch(e,t)}now(){return performance.now()}encode(e,t){if(t!=="utf-8"&&t!=="utf8")throw new Error(`Browser's encoder only supports utf-8, but got ${t}`);return this.textEncoder==null&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(e)}decode(e,t){return new TextDecoder(t).decode(e)}};if(K().get("IS_BROWSER")){K().setPlatform("browser",new A9);try{Ss.registerManager(qi.URL_SCHEME,new p9)}catch(e){}try{Ss.registerManager(ji.URL_SCHEME,new r9)}catch(e){}}var y9={importFetch:()=>RN()},d2,x9=class{constructor(){this.util=$N(),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return K().global.fetch!=null?K().global.fetch(e,t):(d2==null&&(d2=y9.importFetch()),d2(e,t))}now(){let e=process.hrtime();return e[0]*1e3+e[1]/1e6}encode(e,t){if(t!=="utf-8"&&t!=="utf8")throw new Error(`Node built-in encoder only supports utf-8, but got ${t}`);return this.textEncoder.encode(e)}decode(e,t){return e.length===0?"":new this.util.TextDecoder(t).decode(e)}};K().get("IS_NODE")&&K().setPlatform("node",new x9);function Le(e,t="float32",n){return t=t||"float32",Bg(e),new sn(e,t,n)}function b9(e,t){let n=D(e,"x","cast");if(!i5(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");let s={x:n},r={dtype:t};return B.runKernel(Ca,s,r)}var de=V({cast_:b9});function v9(e){let n={x:D(e,"x","clone","string_or_numeric")};return B.runKernel(Ba,n)}var or=V({clone_:v9});function U5(e,t=!1){console.log(e.toString(t))}T5();var w9={buffer:Le,cast:de,clone:or,print:U5};DE(w9);var ns={};ze(ns,{browserFiles:()=>E9,browserHTTPRequest:()=>P9,concatenateArrayBuffers:()=>o2,copyModel:()=>m9,decodeWeights:()=>D5,encodeWeights:()=>GE,fromMemory:()=>O9,getLoadHandlers:()=>t9,getModelArtifactsForJSON:()=>i2,getModelArtifactsInfoForJSON:()=>od,getSaveHandlers:()=>e9,http:()=>m2,isHTTPScheme:()=>f2,listModels:()=>h9,loadWeights:()=>R9,moveModel:()=>g9,registerLoadRouter:()=>QE,registerSaveRouter:()=>JE,removeModel:()=>f9,weightsLoaderFactory:()=>q5,withSaveHandler:()=>M9});var k9="model",I9=".json",S9=".weights.bin";function G5(e){return new Promise(t=>setTimeout(t)).then(e)}var p2=class{constructor(e){if(!K().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(p2.URL_SCHEME)&&(e=e.slice(p2.URL_SCHEME.length)),(e==null||e.length===0)&&(e=k9),this.modelJsonFileName=e+I9,this.weightDataFileName=e+S9}async save(e){if(typeof document=="undefined")throw new Error("Browser downloads are not supported in this environment since `document` is not present");let 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.");{let n=[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}],s=F5(e,n),r=window.URL.createObjectURL(new Blob([JSON.stringify(s)],{type:"application/json"})),a=this.modelJsonAnchor==null?document.createElement("a"):this.modelJsonAnchor;if(a.download=this.modelJsonFileName,a.href=r,await G5(()=>a.dispatchEvent(new MouseEvent("click"))),e.weightData!=null){let o=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor;o.download=this.weightDataFileName,o.href=t,await G5(()=>o.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:od(e)}}}},zh=p2;zh.URL_SCHEME="downloads://";var C9=class{constructor(e){if(e==null||e.length<1)throw new Error(`When calling browserFiles, at least 1 file is required, but received ${e}`);this.jsonFile=e[0],this.weightsFiles=e.slice(1)}async load(){return new Promise((e,t)=>{let n=new FileReader;n.onload=s=>{let r=JSON.parse(s.target.result),a=r.modelTopology;if(a==null){t(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`));return}if(r.weightsManifest==null){t(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`));return}if(this.weightsFiles.length===0){e({modelTopology:a});return}let i=i2(r,l=>this.loadWeights(l));e(i)},n.onerror=s=>t(`Failed to read model topology and weights manifest JSON from file '${this.jsonFile.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),n.readAsText(this.jsonFile)})}loadWeights(e){let t=[],n=[];for(let a of e)t.push(...a.weights),n.push(...a.paths);let s=this.checkManifestAndWeightFiles(e),r=n.map(a=>this.loadWeightsFile(a,s[a]));return Promise.all(r).then(a=>[t,o2(a)])}loadWeightsFile(e,t){return new Promise((n,s)=>{let r=new FileReader;r.onload=a=>{let o=a.target.result;n(o)},r.onerror=a=>s(`Failed to weights data from file of path '${e}'.`),r.readAsArrayBuffer(t)})}checkManifestAndWeightFiles(e){let t=[],n=this.weightsFiles.map(r=>P5(r.name)),s={};for(let r of e)r.paths.forEach(a=>{let o=P5(a);if(t.indexOf(o)!==-1)throw new Error(`Duplicate file basename found in weights manifest: '${o}'`);if(t.push(o),n.indexOf(o)===-1)throw new Error(`Weight file with basename '${o}' is not provided.`);s[a]=this.weightsFiles[n.indexOf(o)]});if(t.length!==this.weightsFiles.length)throw new Error(`Mismatch in the number of files in weights manifest (${t.length}) and the number of weight files provided (${this.weightsFiles.length}).`);return s}},T9=e=>K().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(zh.URL_SCHEME)?N9(e.slice(zh.URL_SCHEME.length)):null;Bt.registerSaveRouter(T9);function N9(e="model"){return new zh(e)}function E9(e){return new C9(e)}function H5(e,t,n,s){o(e),n=n==null?0:n,s=s==null?1:s,i(n,s);let r=0,a=l=>(l.then(c=>{let u=n+ ++r/e.length*(s-n);return t(u),c}),l);function o(l){O(l!=null&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")}function i(l,c){O(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),O(c>=0&&c<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${c}`),O(c>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${c}`)}return Promise.all(e.map(a))}async function j5(e,t){t==null&&(t={});let n=t.fetchFunc==null?K().platform.fetch:t.fetchFunc,s=e.map(d=>n(d,t.requestInit,{isBinary:!0})),r=0,a=.5,i=(t.onProgress==null?await Promise.all(s):await H5(s,t.onProgress,r,a)).map(d=>d.arrayBuffer()),l=.5,c=1;return t.onProgress==null?await Promise.all(i):await H5(i,t.onProgress,l,c)}async function R9(e,t="",n,s){return q5(o=>j5(o,{requestInit:s}))(e,t,n)}function q5(e){return async(t,n="",s)=>{let r=t.map(()=>!1),a={},o=s!=null?s.map(()=>!1):[],i=[];if(t.forEach((h,f)=>{let m=0;h.weights.forEach(g=>{let A="quantization"in g?g.quantization.dtype:g.dtype,y=r2[A]*Ut(g.shape),x=()=>{r[f]=!0,a[f]==null&&(a[f]=[]),a[f].push({manifestEntry:g,groupOffset:m,sizeBytes:y})};s!=null?s.forEach((b,w)=>{b===g.name&&(x(),o[w]=!0)}):x(),i.push(g.name),m+=y})}),!o.every(h=>h)){let h=s.filter((f,m)=>!o[m]);throw new Error(`Could not find weights in manifest with names: ${h.join(", ")}. -Manifest JSON has weights with names: ${i.join(", ")}.`)}let l=r.reduce((h,f,m)=>(f&&h.push(m),h),[]),c=[];l.forEach(h=>{t[h].paths.forEach(f=>{let m=n+(n.endsWith("/")?"":"/")+f;c.push(m)})});let u=await e(c),d={},p=0;return l.forEach(h=>{let f=t[h].paths.length,m=0;for(let b=0;b{let w=g.slice(b.groupOffset,b.groupOffset+b.sizeBytes),k=D5(w,[b.manifestEntry]);for(let S in k)d[S]=k[S]}),p+=f}),d}}var $9="application/octet-stream",D9="application/json",h2=class{constructor(e,t){if(this.DEFAULT_METHOD="POST",t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,this.weightUrlConverter=t.weightUrlConverter,t.fetchFunc!=null?(O(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=K().platform.fetch,O(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&O(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.");let t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;let n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],s=F5(e,n);t.body.append("model.json",new Blob([JSON.stringify(s)],{type:D9}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:$9}),"model.weights.bin");let r=await this.fetch(this.path,t);if(r.ok)return{modelArtifactsInfo:od(e),responses:[r]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${r.status}.`)}async load(){let 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(r){let a=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?a+=" 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.":a+=" Please make sure the server is serving valid JSON for this request.",new Error(a)}let n=t.modelTopology,s=t.weightsManifest;if(n==null&&s==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);return i2(t,r=>this.loadWeights(r))}async loadWeights(e){let t=Array.isArray(this.path)?this.path[1]:this.path,[n,s]=_9(t),r=this.weightPathPrefix||n,a=[];for(let c of e)a.push(...c.weights);let o=[],i=[];for(let c of e)for(let u of c.paths)this.weightUrlConverter!=null?i.push(this.weightUrlConverter(u)):o.push(r+u+s);this.weightUrlConverter&&o.push(...await Promise.all(i));let l=await j5(o,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[a,o2(l)]}};h2.URL_SCHEME_REGEX=/^https?:\/\//;function _9(e){let t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),s=e.substring(0,t),r=n>t?e.substring(n):"";return[s+"/",r]}function f2(e){return e.match(h2.URL_SCHEME_REGEX)!=null}var X5=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let n=!0;if(Array.isArray(e)?n=e.every(s=>f2(s)):n=f2(e),n)return m2(e,t)}return null};Bt.registerSaveRouter(X5);Bt.registerLoadRouter(X5);function m2(e,t){return new h2(e,t)}function P9(e,t){return m2(e,t)}var g2=class{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}},F9=class{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}};function O9(e,t,n,s){return arguments.length===1?e.modelTopology!=null||e.weightSpecs!=null?new g2(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 g2({modelTopology:e})):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new g2({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:s}))}function M9(e){return new F9(e)}var K5={};ze(K5,{confusionMatrix:()=>V9});function z9(e,t,n=!1,s=!1){let r=D(e,"a","matMul"),a=D(t,"b","matMul");[r,a]=Ft(r,a);let o={a:r,b:a},i={transposeA:n,transposeB:s};return B.runKernel(Sa,o,i)}var He=V({matMul_:z9});function L9(e,t,n=1,s=0){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);let a={indices:D(e,"indices","oneHot","int32")},o={depth:t,onValue:n,offValue:s};return B.runKernel(Ii,a,o)}var id=V({oneHot_:L9});function B9(e,t){let n=D(e,"x","transpose");if(t==null&&(t=n.shape.map((a,o)=>o).reverse()),O(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of perm ${t}.`),t.forEach(a=>{O(a>=0&&a`All entries in 'perm' must be between 0 and ${n.rank-1} but got ${t}`)}),n.rank<=1)return n.clone();let s={x:n},r={perm:t};return B.runKernel(po,s,r)}var et=V({transpose_:B9});function W9(e,t,n){let s=D(e,"labels","confusionMatrix"),r=D(t,"predictions","confusionMatrix");O(n==null||n>0&&Number.isInteger(n),()=>`If provided, numClasses must be a positive integer, but got ${n}`),O(s.rank===1,()=>`Expected the rank of labels to be 1, but got ${s.rank}`),O(r.rank===1,()=>`Expected the rank of predictions to be 1, but got ${r.rank}`),O(s.shape[0]===r.shape[0],()=>`Mismatch in the number of examples: ${s.shape[0]} vs. ${r.shape[0]}. Labels and predictions should have the same number of elements.`),O(n>0&&Number.isInteger(n),()=>`numClasses is required to be a positive integer, but got ${n}`);let a=id(de(s,"int32"),n),o=id(de(r,"int32"),n),i=et(a),l=He(i,o);return de(l,"int32")}var V9=V({confusionMatrix_:W9}),Gs={};ze(Gs,{fromPixels:()=>K9,fromPixelsAsync:()=>q9,toPixels:()=>X9});function Z5(e,t,n){if(ei(e),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");let s=Cr(e,n);if(s.length!==3&&s.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return xo(e,t,s,n)}var xu;function Y5(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,s=!1,r=!1,a=!1,o=!1,i=!1;if(e.data instanceof Uint8Array)n=!0;else if(typeof ImageData!="undefined"&&e instanceof ImageData)s=!0;else if(typeof HTMLVideoElement!="undefined"&&e instanceof HTMLVideoElement)r=!0;else if(typeof HTMLImageElement!="undefined"&&e instanceof HTMLImageElement)a=!0;else if(e.getContext!=null)o=!0;else if(typeof ImageBitmap!="undefined"&&e instanceof ImageBitmap)i=!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(r){let f=2;if(r&&e.readyState element.")}if($h(Kc,B.backendName)!=null){let f={pixels:e},m={numChannels:t};return B.runKernel(Kc,f,m)}let[c,u]=r?[e.videoWidth,e.videoHeight]:[e.width,e.height],d;o?d=e.getContext("2d").getImageData(0,0,c,u).data:s||n?d=e.data:(a||r||i)&&(xu==null&&(xu=document.createElement("canvas").getContext("2d")),xu.canvas.width=c,xu.canvas.height=u,xu.drawImage(e,0,0,c,u),d=xu.getImageData(0,0,c,u).data);let p;if(t===4)p=new Int32Array(d);else{let f=c*u;p=new Int32Array(f*t);for(let m=0;m4||a===2)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${a}`);if(n.dtype!=="float32"&&n.dtype!=="int32")throw new Error(`Unsupported type for toPixels: ${n.dtype}. Please use float32 or int32 tensors.`);let o=await n.data(),i=n.dtype==="float32"?255:1,l=new Uint8ClampedArray(r*s*4);for(let c=0;c1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${h}.`)}else if(n.dtype==="int32"&&(h<0||h>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${h}.`);a===1?(u[0]=h*i,u[1]=h*i,u[2]=h*i):u[p]=h*i}let d=c*4;l[d+0]=Math.round(u[0]),l[d+1]=Math.round(u[1]),l[d+2]=Math.round(u[2]),l[d+3]=Math.round(u[3])}if(t!=null){t.width=r,t.height=s;let c=t.getContext("2d"),u=new ImageData(l,r,s);c.putImageData(u,0,0)}return n!==e&&n.dispose(),l}var K9=V({fromPixels_:Y5}),A2={};ze(A2,{prepareAndValidate:()=>J5});function J5(e,t){let n=e.shape.length,s=t.shape.length;if(n<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${n}.`);if(s<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${s}.`);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[s-1]>n)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[s-1]} vs. ${n}`);if(Ut(e.shape)===0)throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);let r=t.shape,a=r[r.length-1],o=1;for(let d=0;dd/c),1].slice(0,a);return[l,o,c,u]}var y2={};ze(y2,{calculateShapes:()=>Q5,validateInput:()=>b2,validateUpdateShape:()=>x2});function x2(e,t,n){let s=t.rank>1?t.shape[t.rank-1]:1,r=t.rank>1?t.rank-1:1,a=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${n.shape}, indices.shape: ${t.shape}, shape: ${e}, sliceDim: ${s}, and batchDim: ${r}.`;if(n.rank1?t.shape[s-1]:1,a=n.length,o=1;for(let d=r;dZ9,computeFlatOffset:()=>J9,computeOutShape:()=>e3,getNormalizedAxes:()=>r3,isSliceContinous:()=>Y9,maskToAxes:()=>Lh,parseSliceParams:()=>c3,sliceInfo:()=>Q9,startForAxis:()=>l3,startIndicesWithElidedDims:()=>a3,stopForAxis:()=>u3,stopIndicesWithElidedDims:()=>o3,stridesForAxis:()=>i3,stridesWithElidedDims:()=>t3});function Z9(e,t,n){let s=e.shape.length;O(s===t.length,()=>`Error in slice${s}D: Length of begin ${t} must match the rank of the array (${s}).`),O(s===n.length,()=>`Error in slice${s}D: Length of size ${n} must match the rank of the array (${s}).`);for(let r=0;r`Error in slice${s}D: begin[${r}] + size[${r}] (${t[r]+n[r]}) would overflow input.shape[${r}] (${e.shape[r]})`)}function Lh(e){let t=[],n=0;for(;e>0;)e&1&&t.push(n),e/=2,n++;return t}function e3(e,t,n){let s=[];for(let r=0;r0){let h=t[0],f=n+1;u=a3(o,h,f,s,e),d=o3(i,h,f,r,e),p=t3(a,h,f,e)}else for(let h=0;h-1)a[i]=0;else{let l=n3(t,n,i),c=s[l];e&1<-1)a[i]=Number.MAX_SAFE_INTEGER;else{let l=n3(t,n,i),c=s[l];e&1<0?o=Number.MIN_SAFE_INTEGER:o=Number.MAX_SAFE_INTEGER);let l=s[r];return o<0&&(o+=l),o=_c(0,o,l-1),o}function u3(e,t,n,s,r,a){let o=t[r],i=n[r]||1;(e&1<0?o=Number.MAX_SAFE_INTEGER:o=Number.MIN_SAFE_INTEGER);let l=s[r];return o<0&&(o+=l),i>0?o=_c(0,o,l):o=_c(-1,o,l-1),o}function Y9(e,t,n){let s=n.length;for(let r=0;r1){s=r;break}for(let r=s+1;r0||n[r]!==e[r])return!1;return!0}function J9(e,t){let n=e.length>0?e[e.length-1]:1;for(let s=0;s{O(o!==-1,()=>"slice() does not support negative begin indexing.")});let a;return n==null?a=new Array(r).fill(-1):typeof n=="number"?a=[n,...new Array(r-1).fill(-1)]:n.lengtho>=0?o:(O(o===-1,()=>`Negative size values should be exactly -1 but got ${o} for the slice() size at index ${i}.`),e.shape[i]-s[i])),[s,a]}function Q9(e,t,n,s,r,a,o,i,l){let c=t.slice(),u=n.slice(),d=s;s==null&&(d=new Array(c.length));let p=Lh(o);if(p.length>1)throw new Error("Multiple ellipses in slice is not allowed.");if(o!==0&&i!==0)throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");if(o!==0&&l!==0)throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");let h=e.length-c.length,f=Lh(i),m=e.slice();f.forEach(S=>{c[S]=0,u[S]=1,m.splice(S,0,1)});let{begin:g,end:A,strides:y}=r3(m,p,h,c,u,d,r,a,o);c=g,u=A,d=y;let x=Lh(l);x.forEach(S=>{u[S]=c[S]+1,d[S]=1});let b=e3(c,u,d),w=b.filter((S,E)=>x.indexOf(E)===-1);return{nonStrided:d.every(S=>S===1),$begin:c,$end:u,$strides:d,size:b,newShape:m,outShape:w}}var le={};ze(le,{Serializable:()=>d3,SerializationMap:()=>Xi,registerClass:()=>vo});var d3=class{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}},Xi=class{constructor(){this.classNameMap={}}static getMap(){return Xi.instance==null&&(Xi.instance=new Xi),Xi.instance}static register(e){Xi.getMap().classNameMap[e.className]=[e,e.fromConfig]}};function vo(e){O(e.className!=null,()=>"Class being registered does not have the static className property defined."),O(typeof e.className=="string",()=>"className is required to be a string, but got type "+typeof e.className),O(e.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),Xi.register(e)}var p3={};ze(p3,{TEST_EPSILON_FLOAT16:()=>h3,encodeStrings:()=>f3,expectArrayBuffersEqual:()=>oR,expectArraysClose:()=>tR,expectArraysEqual:()=>sR,expectNumbersClose:()=>rR,expectPromiseToFail:()=>nR,expectValuesInRange:()=>aR,testEpsilon:()=>v2});var eR=.001,h3=.1;function tR(e,t,n){return n==null&&(n=v2()),w2(e,t,(s,r)=>k2(s,r,n))}function v2(){return B.backend.floatPrecision()===32?eR:h3}function w2(e,t,n){let s=!0;if((Dn(e)||Dn(t))&&(s=!1),Dn(e)&&Dn(t)&&(s=!0),s){let o=e.constructor.name,i=t.constructor.name;if(o!==i)throw new Error(`Arrays are of different type. Actual: ${o}. Expected: ${i}`)}if(Array.isArray(e)&&Array.isArray(t)){let o=Cr(e),i=Cr(t);if(!Gr(o,i))throw new Error(`Arrays have different shapes. Actual: [${o}]. Expected: [${i}]`)}let r=Dn(e)?e:ti(e),a=Dn(t)?t:ti(t);if(r.length!==a.length)throw new Error(`Arrays have different lengths actual: ${r.length} vs expected: ${a.length}. +`;return p[p.length-1]=" "+p[p.length-1]+"]"+(a?"":f),p}function nd(e){let t=[];for(let n=0;n`Length of values '${s}' 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||a5(t,this.size),this.strides=Bl(e)}set(e,...t){t.length===0&&(t=[0]),O(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);let n=this.locToIndex(t);this.values[n]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(let s of e){if(s<0||s>=this.shape[t]){let r=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(r)}t++}let n=e[e.length-1];for(let s=0;sPh(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();let e=Sr().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>Ph(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();let e=await Sr().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(Sr().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return mu.print(this,e)}clone(){return this.throwIfDisposed(),mu.clone(this)}toString(e=!1){let t=this.dataSync();return NE(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),mu.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Sr().makeVariable(this,e,t,n)}};Object.defineProperty(Ye,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});function PE(){return Ug("Tensor",()=>Ye)}PE();var sd=class extends Ye{constructor(e,t,n,s){super(e.shape,e.dtype,e.dataId,s);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(!Gr(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Sr().disposeTensor(this),this.dataId=e.dataId,Sr().incRef(this,null)}dispose(){Sr().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(sd,Symbol.hasInstance,{value:e=>e instanceof Ye&&e.assign!=null&&e.assign instanceof Function});var rr={};ze(rr,{assertTypesMatch:()=>I5,getTensorsInContainer:()=>Qg,isTensorInList:()=>OE,makeTypesMatch:()=>Ft});var Xg;(function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"})(Xg||(Xg={}));var Kg;(function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"})(Kg||(Kg={}));var Zg;(function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"})(Zg||(Zg={}));var Yg;(function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"})(Yg||(Yg={}));var Jg;(function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"})(Jg||(Jg={}));var FE={float32:Yg,int32:Kg,bool:Zg,complex64:Jg};function Bn(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return FE[e][t]}function rd(e){return Bn(e,"int32")}function Ft(e,t){if(e.dtype===t.dtype)return[e,t];let n=Bn(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function I5(e,t){O(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function OE(e,t){return t.some(n=>n.id===e.id)}function Qg(e){let t=[],n=new Set;return S5(e,t,n),t}function S5(e,t,n){if(e==null)return;if(e instanceof Ye){t.push(e);return}if(!ME(e))return;let s=e;for(let r in s){let a=s[r];n.has(a)||(n.add(a),S5(a,t,n))}}function ME(e){return Array.isArray(e)||typeof e=="object"}function e2(e){return e.kernelName!=null}var C5=class{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,get kernelNames(){return Array.from(new Set(this.kernels.map(e=>e.name)))}}}dispose(){for(let e in this.registeredVariables)this.registeredVariables[e].dispose()}},t2=class{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new C5}async ready(){if(this.pendingBackendInit!=null)return this.pendingBackendInit.then(()=>{});if(this.backendInstance!=null)return;let e=this.getSortedBackends();for(let t=0;t{t.setupFunc!=null&&t.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){Xr(e).forEach(n=>{n.disposeFunc!=null&&n.disposeFunc(this.registry[e])})}initializeBackend(e){let t=this.registryFactory[e];if(t==null)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{let n=t.factory();if(n&&!(n instanceof Ll)&&typeof n.then=="function"){let s=++this.pendingBackendInitId,r=n.then(a=>s(sthis.registryFactory[t].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){let e=this.getSortedBackends();for(let t=0;tthis.startScope(n),()=>this.endScope(s),()=>(s=t(),s instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),s))}scopedRun(e,t,n){e();try{let s=n();return t(),s}catch(s){throw t(),s}}nextTensorId(){return t2.nextTensorId++}nextVariableId(){return t2.nextVariableId++}clone(e){let t=B.runKernel(Ba,{x:e}),n={x:e},s=a=>({x:()=>{let o="float32",i={x:a},l={dtype:o};return B.runKernel(Ca,i,l)}}),r=[];return this.addTapeNode(this.state.activeScope.name,n,[t],s,r,{}),t}runKernel(e,t,n){if(this.backendName==null&&this.backend,!($h(e,this.backendName)!=null))throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){let s=this.backend.numDataIds(),r=0;n.forEach(i=>{r+=i.dtype==="complex64"?3:1});let a=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],o=s-t-r-a;if(o>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${o} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[],s=this.isTapeOn(),r=this.state.numBytes,a=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let o;this.backendName==null&&this.backend;let i,l=e2(e)?e.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(e2(e)){let{kernelName:h,inputs:f,attrs:m}=e;this.backendName==null&&this.backend;let g=$h(h,this.backendName);O(g!=null,()=>`Cannot find registered kernel '${h}' for backend '${this.backendName}'`),o=()=>{let A=this.backend.numDataIds();i=g.kernelFunc({inputs:f,attrs:m,backend:this.backend});let y=Array.isArray(i)?i:[i];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(h,A,y);let x=y.map(b=>{if(b.rank!=null)return b;let{dataId:w,shape:k,dtype:S}=b;return this.makeTensorFromDataId(w,k,S)});if(s){let b=this.getTensorsForGradient(h,f,x);n=this.saveTensorsForBackwardMode(b)}return x}}else{let{forwardFunc:h}=e,f=m=>{!s||(n=m.map(g=>this.keep(this.clone(g))))};o=()=>{let m=this.backend.numDataIds();i=this.tidy(()=>h(this.backend,f));let g=Array.isArray(i)?i:[i];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,m,g),g}}let{inputs:c,attrs:u}=e,d=e2(e)?null:e.backwardsFunc,p;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?t=o():(p=this.profiler.profileKernel(l,c,()=>o()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(p),t=p.outputs)}),s&&this.addTapeNode(l,c,t,d,n,u),this.state.profiling&&this.state.activeProfile.kernels.push({name:l,bytesAdded:this.state.numBytes-r,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-a,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(c).map(h=>c[h]!=null?c[h].shape:null),outputShapes:t.map(h=>h.shape),kernelTimeMs:p.timeMs,extraInfo:p.extraInfo}),Array.isArray(i)?t:t[0]}saveTensorsForBackwardMode(e){return e.map(n=>this.keep(this.clone(n)))}getTensorsForGradient(e,t,n){let s=Gg(e);if(s!=null){let r=s.inputsToSave||[],a=s.outputsToSave||[],o;s.saveAllInputs?(O(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),o=Object.keys(t).map(l=>t[l])):o=r.map(l=>t[l]);let i=n.filter((l,c)=>a[c]);return o.concat(i)}return[]}makeTensor(e,t,n,s){if(e==null)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",s=s||this.backend;let r=e;n==="string"&&ba(e[0])&&(r=e.map(i=>Qc(i)));let a=s.write(r,t,n),o=new Ye(t,n,a,this.nextTensorId());if(this.trackTensor(o,s),n==="string"){let i=this.state.tensorInfo.get(a),l=l5(r);this.state.numBytes+=l-i.bytes,i.bytes=l}return o}makeTensorFromDataId(e,t,n,s){n=n||"float32";let r=new Ye(t,n,e,this.nextTensorId());return this.trackTensor(r,s),r}makeVariable(e,t=!0,n,s){n=n||this.nextVariableId().toString(),s!=null&&s!==e.dtype&&(e=e.cast(s));let r=new sd(e,t,n,this.nextTensorId());if(this.state.registeredVariables[r.name]!=null)throw new Error(`Variable with name ${r.name} was already registered`);return this.state.registeredVariables[r.name]=r,this.incRef(r,this.backend),r}trackTensor(e,t){this.state.numTensors++,e.dtype==="string"&&this.state.numStringTensors++;let n=0;e.dtype!=="complex64"&&e.dtype!=="string"&&(n=e.size*zg(e.dtype)),this.state.numBytes+=n,this.state.tensorInfo.has(e.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:n})),e instanceof sd||this.track(e)}incRef(e,t){this.trackTensor(e,t),this.backend.incRef(e.dataId)}removeDataId(e,t){this.state.tensorInfo.has(e)&&this.state.tensorInfo.get(e).backend===t&&(this.state.tensorInfo.delete(e),this.state.numDataBuffers--)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;let t=this.state.tensorInfo.get(e.dataId);if(this.state.numTensors--,e.dtype==="string"&&(this.state.numStringTensors--,this.state.numBytes-=t.bytes),e.dtype!=="complex64"&&e.dtype!=="string"){let n=e.size*zg(e.dtype);this.state.numBytes-=n}t.backend.disposeData(e.dataId)&&this.removeDataId(e.dataId,t.backend)}disposeVariables(){for(let e in this.state.registeredVariables){let 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(){let 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;let 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(s=>s.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(let s of this.state.activeProfile.kernels)s.kernelTimeMs=await s.kernelTimeMs,s.extraInfo=await s.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(e,t,n,s,r,a){let o={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:r},i=Gg(e);i!=null&&(s=i.gradFunc),s!=null&&(o.gradient=l=>(l=l.map((c,u)=>{if(c==null){let d=n[u],p=Qp(d.size,d.dtype);return this.makeTensor(p,d.shape,d.dtype)}return c}),s(l.length>1?l:l[0],r,a))),this.state.activeTape.push(o)}keep(e){return e.kept=!0,e}startTape(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){let t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){let t=Qg(e),n=new Set(t.map(r=>r.id));for(let r=0;r{!r.kept&&r.scopeId===s.id&&this.track(r)})}gradients(e,t,n,s=!1){if(O(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}'`);let r=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));O(r instanceof Ye,()=>"The result y returned by f() must be a tensor.");let a=CE(this.state.activeTape,t,r);if(!s&&a.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",()=>{let o={};o[r.id]=n==null?zE(r.shape):n,TE(o,a,l=>this.tidy(l),LE);let i=t.map(l=>o[l.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(l=>{for(let c of l.saved)c.dispose()}),this.state.activeTape=null),{value:r,grads:i}})}customGrad(e){return O(va(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{O(t.every(o=>o instanceof Ye),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let n,s={};t.forEach((o,i)=>{s[i]=o});let r=(o,i)=>(n=e(...t,i),O(n.value instanceof Ye,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),O(va(n.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),n.value),a=(o,i)=>{let l=n.gradFunc(o,i),c=Array.isArray(l)?l:[l];O(c.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(...)."),O(c.every(d=>d instanceof Ye),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");let u={};return c.forEach((d,p)=>{u[p]=()=>d}),u};return this.runKernelFunc({forwardFunc:r,backwardsFunc:a,inputs:s})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}async time(e){let t=Jc(),n=await this.backend.time(e);return n.wallMs=Jc()-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 C5;for(let e in this.registry)this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}},n2=t2;n2.nextTensorId=0;n2.nextVariableId=0;function zE(e){let t=Lg(Ut(e),"float32");return B.makeTensor(t,e,"float32")}function T5(){let e=f5();if(e._tfengine==null){let t=new h5(e);e._tfengine=new n2(t)}return uE(e._tfengine.ENV),$E(()=>e._tfengine),e._tfengine}var B=T5();function LE(e,t){let n={a:e,b:t};return B.runKernel(Hr,n)}var gu={};ze(gu,{isBrowser:()=>N5,isMobile:()=>VE,mockIsMobile:()=>WE});function BE(){return typeof navigator!="undefined"&&navigator!=null}var s2;function WE(e){s2=e}function VE(e){if(s2!==void 0)return s2;if(e||BE()){if(e||(e=navigator),e.product==="ReactNative")return!0;let t=e.userAgent||e.vendor||(typeof window!="undefined"?window.opera:"");if(!t){let n=e;return n.userAgentData&&n.userAgentData.mobile}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(t)||/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(t.substr(0,4))}return!1}function N5(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var ar=K();ar.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.")});ar.registerFlag("IS_BROWSER",()=>N5());ar.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");ar.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));ar.registerFlag("PROD",()=>!1);ar.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>ar.getBool("DEBUG"));ar.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);ar.registerFlag("IS_TEST",()=>!1);ar.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>!0);ar.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1);function Cr(e,t){let n=e;if(Dn(e))return t==="string"?[]:[e.length];if(!Array.isArray(e))return[];let s=[];for(;Array.isArray(n)||Dn(n)&&t!=="string";)s.push(n.length),n=n[0];return Array.isArray(e)&&K().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&E5(e,s,[]),s}function E5(e,t,n){if(n=n||[],!Array.isArray(e)&&!Dn(e)){O(t.length===0,()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}O(t.length>0,()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`),O(e.length===t[0],()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`);let s=t.slice(1);for(let r=0;r=0&&(r=s),R5(s,r,t,n),e==null||!Dn(e)&&!Array.isArray(e)&&typeof e!="number"&&typeof e!="boolean"&&typeof e!="string"){let l=e==null?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${n}' must be a Tensor or TensorLike, but got '${l}'`)}let a=Cr(e,r);!Dn(e)&&!Array.isArray(e)&&(e=[e]);let i=r!=="string"?_h(e,r):ti(e,[],!0);return B.makeTensor(i,a,r)}function ad(e,t,n,s="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);return e.map((a,o)=>_(a,`${t}[${o}]`,n,s))}var $5="__op";function V(e){let 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],s=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1)),n=n+$5;let r=(...a)=>{B.startScope(n);try{let o=s(...a);return Wg(o)&&console.error("Cannot return a Promise inside of tidy."),B.endScope(o),o}catch(o){throw B.endScope(null),o}};return Object.defineProperty(r,"name",{value:n,configurable:!0}),r}function UE(e,t){let n=_(e,"real","complex"),s=_(t,"imag","complex");zn(n.shape,s.shape,`real and imag shapes, ${n.shape} and ${s.shape}, must match in call to tf.complex().`);let r={real:n,imag:s};return B.runKernel(Oc,r)}var yo=V({complex_:UE});function xo(e,t,n,s){if(s==null&&(s=Yp(e)),s==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!Dn(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){Bg(t);let r=Ut(t),a=Ut(n);O(r===a,()=>`Based on the provided shape, [${t}], the tensor should have ${r} values but has ${a}`);for(let o=0;o`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `)}}return!Dn(e)&&!Array.isArray(e)&&(e=[e]),t=t||n,e=s!=="string"?_h(e,s):ti(e,[],!0),B.makeTensor(e,t,s)}function Gt(e,t,n){let s=Cr(e,n);return xo(e,t,s,n)}var r2={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8},Oh=4;async function GE(e,t){let n=[],s=[],r=Array.isArray(e)?e.map(o=>o.name):Object.keys(e);for(let o=0;o{let p=await l.bytes(),h=p.reduce((g,A)=>g+A.length,0)+Oh*p.length,f=new Uint8Array(h),m=0;for(let g=0;g{if(t+=a.byteLength,n.push(a.byteLength===a.buffer.byteLength?a:new a.constructor(a)),!(a instanceof Float32Array||a instanceof Int32Array||a instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${a.constructor.name}`)});let s=new Uint8Array(t),r=0;return n.forEach(a=>{s.set(new Uint8Array(a.buffer),r),r+=a.byteLength}),s.buffer}var a2=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function _5(e){return a2?Buffer.byteLength(e):new Blob([e]).size}function jE(e){if(a2)return Buffer.from(e).toString("base64");let t=new Uint8Array(e),n="";for(let s=0,r=t.length;s{t+=r.byteLength});let n=new Uint8Array(t),s=0;return e.forEach(r=>{n.set(new Uint8Array(r),s),s+=r.byteLength}),n.buffer}function P5(e){let t="/";for(e=e.trim();e.endsWith(t);)e=e.slice(0,e.length-1);let n=e.split(t);return n[n.length-1]}function F5(e,t){let n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:t};return e.signature!=null&&(n.signature=e.signature),e.userDefinedMetadata!=null&&(n.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(n.modelInitializer=e.modelInitializer),e.trainingConfig!=null&&(n.trainingConfig=e.trainingConfig),n}async function i2(e,t){let n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};if(e.trainingConfig!=null&&(n.trainingConfig=e.trainingConfig),e.weightsManifest!=null){let[s,r]=await t(e.weightsManifest);n.weightSpecs=s,n.weightData=r}return e.signature!=null&&(n.signature=e.signature),e.userDefinedMetadata!=null&&(n.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(n.modelInitializer=e.modelInitializer),n}function od(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:_5(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:_5(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:e.weightData.byteLength}}function XE(){let e=n=>{let s=n<<13,r=0;for(;(s&8388608)==0;)r-=8388608,s<<=1;return s&=~8388608,r+=947912704,s|r},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 KE(){let 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 ZE(){let e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function YE(){let e=XE(),t=KE(),n=ZE();return s=>{let r=new ArrayBuffer(4*s.length),a=new Uint32Array(r);for(let o=0;o>10]+(i&1023)]+t[i>>10];a[o]=l}return new Float32Array(r)}}var Bt=class{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return Bt.instance==null&&(Bt.instance=new Bt),Bt.instance}static registerSaveRouter(e){Bt.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Bt.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Bt.getHandlers(e,"save")}static getLoadHandlers(e,t){return Bt.getHandlers(e,"load",t)}static getHandlers(e,t,n){let s=[];return(t==="load"?Bt.getInstance().loadRouters:Bt.getInstance().saveRouters).forEach(a=>{let o=a(e,n);o!==null&&s.push(o)}),s}},JE=e=>Bt.registerSaveRouter(e),QE=e=>Bt.registerLoadRouter(e),e9=e=>Bt.getSaveHandlers(e),t9=(e,t)=>Bt.getLoadHandlers(e,t),l2="tensorflowjs",u2=1,Hi="models_store",bo="model_info_store";function O5(){if(!K().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");let e=typeof window=="undefined"?self:window,t=e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB||e.shimIndexedDB;if(t==null)throw new Error("The current browser does not appear to support IndexedDB.");return t}function c2(e){let t=e.result;t.createObjectStore(Hi,{keyPath:"modelPath"}),t.createObjectStore(bo,{keyPath:"modelPath"})}var ji=class{constructor(e){if(this.indexedDB=O5(),e==null||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return this.databaseAction(this.modelPath,e)}async load(){return this.databaseAction(this.modelPath)}databaseAction(e,t){return new Promise((n,s)=>{let r=this.indexedDB.open(l2,u2);r.onupgradeneeded=()=>c2(r),r.onsuccess=()=>{let a=r.result;if(t==null){let o=a.transaction(Hi,"readonly"),l=o.objectStore(Hi).get(this.modelPath);l.onsuccess=()=>{if(l.result==null)return a.close(),s(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));n(l.result.modelArtifacts)},l.onerror=c=>(a.close(),s(l.error)),o.oncomplete=()=>a.close()}else{let o=od(t),i=a.transaction(bo,"readwrite"),l=i.objectStore(bo),c=l.put({modelPath:this.modelPath,modelArtifactsInfo:o}),u;c.onsuccess=()=>{u=a.transaction(Hi,"readwrite");let p=u.objectStore(Hi).put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:o});p.onsuccess=()=>n({modelArtifactsInfo:o}),p.onerror=h=>{l=i.objectStore(bo);let f=l.delete(this.modelPath);f.onsuccess=()=>(a.close(),s(p.error)),f.onerror=m=>(a.close(),s(p.error))}},c.onerror=d=>(a.close(),s(c.error)),i.oncomplete=()=>{u==null?a.close():u.oncomplete=()=>a.close()}}},r.onerror=a=>s(r.error)})}};ji.URL_SCHEME="indexeddb://";var M5=e=>K().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(ji.URL_SCHEME)?n9(e.slice(ji.URL_SCHEME.length)):null;Bt.registerSaveRouter(M5);Bt.registerLoadRouter(M5);function n9(e){return new ji(e)}function s9(e){return e.startsWith(ji.URL_SCHEME)?e.slice(ji.URL_SCHEME.length):e}var r9=class{constructor(){this.indexedDB=O5()}async listModels(){return new Promise((e,t)=>{let n=this.indexedDB.open(l2,u2);n.onupgradeneeded=()=>c2(n),n.onsuccess=()=>{let s=n.result,r=s.transaction(bo,"readonly"),o=r.objectStore(bo).getAll();o.onsuccess=()=>{let i={};for(let l of o.result)i[l.modelPath]=l.modelArtifactsInfo;e(i)},o.onerror=i=>(s.close(),t(o.error)),r.oncomplete=()=>s.close()},n.onerror=s=>t(n.error)})}async removeModel(e){return e=s9(e),new Promise((t,n)=>{let s=this.indexedDB.open(l2,u2);s.onupgradeneeded=()=>c2(s),s.onsuccess=()=>{let r=s.result,a=r.transaction(bo,"readwrite"),o=a.objectStore(bo),i=o.get(e),l;i.onsuccess=()=>{if(i.result==null)return r.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{let c=o.delete(e),u=()=>{l=r.transaction(Hi,"readwrite");let p=l.objectStore(Hi).delete(e);p.onsuccess=()=>t(i.result.modelArtifactsInfo),p.onerror=h=>n(i.error)};c.onsuccess=u,c.onerror=d=>(u(),r.close(),n(i.error))}},i.onerror=c=>(r.close(),n(i.error)),a.oncomplete=()=>{l==null?r.close():l.oncomplete=()=>r.close()}},s.onerror=r=>n(s.error)})}},Zr="/",Au="tensorflowjs_models",z5="info",a9="model_topology",o9="weight_specs",i9="weight_data",l9="model_metadata";function L5(e){return{info:[Au,e,z5].join(Zr),topology:[Au,e,a9].join(Zr),weightSpecs:[Au,e,o9].join(Zr),weightData:[Au,e,i9].join(Zr),modelMetadata:[Au,e,l9].join(Zr)}}function B5(e){for(let t of Object.values(e))window.localStorage.removeItem(t)}function u9(e){let t=e.split(Zr);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(Zr)}function c9(e){return e.startsWith(qi.URL_SCHEME)?e.slice(qi.URL_SCHEME.length):e}var qi=class{constructor(e){if(!K().getBool("IS_BROWSER")||typeof window=="undefined"||typeof window.localStorage=="undefined")throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,e==null||!e)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=e,this.keys=L5(this.modelPath)}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");{let t=JSON.stringify(e.modelTopology),n=JSON.stringify(e.weightSpecs),s=od(e);try{this.LS.setItem(this.keys.info,JSON.stringify(s)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,jE(e.weightData));let r={format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,signature:e.signature!=null?e.signature:void 0,userDefinedMetadata:e.userDefinedMetadata!=null?e.userDefinedMetadata:void 0,modelInitializer:e.modelInitializer!=null?e.modelInitializer:void 0,trainingConfig:e.trainingConfig!=null?e.trainingConfig:void 0};return this.LS.setItem(this.keys.modelMetadata,JSON.stringify(r)),{modelArtifactsInfo:s}}catch(r){throw B5(this.keys),new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${s.modelTopologyBytes}, weightSpecsBytes=${s.weightSpecsBytes}, weightDataBytes=${s.weightDataBytes}.`)}}}async load(){let e=JSON.parse(this.LS.getItem(this.keys.info));if(e==null)throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);if(e.modelTopologyType!=="JSON")throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");let t={},n=JSON.parse(this.LS.getItem(this.keys.topology));if(n==null)throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);t.modelTopology=n;let s=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(s==null)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);t.weightSpecs=s;let r=this.LS.getItem(this.keys.modelMetadata);if(r!=null){let o=JSON.parse(r);t.format=o.format,t.generatedBy=o.generatedBy,t.convertedBy=o.convertedBy,o.signature!=null&&(t.signature=o.signature),o.userDefinedMetadata!=null&&(t.userDefinedMetadata=o.userDefinedMetadata),o.modelInitializer!=null&&(t.modelInitializer=o.modelInitializer),o.trainingConfig!=null&&(t.trainingConfig=o.trainingConfig)}let a=this.LS.getItem(this.keys.weightData);if(a==null)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return t.weightData=qE(a),t}};qi.URL_SCHEME="localstorage://";var W5=e=>K().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(qi.URL_SCHEME)?d9(e.slice(qi.URL_SCHEME.length)):null;Bt.registerSaveRouter(W5);Bt.registerLoadRouter(W5);function d9(e){return new qi(e)}var p9=class{constructor(){O(K().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),O(typeof window=="undefined"||typeof window.localStorage!="undefined",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){let e={},t=Au+Zr,n=Zr+z5;for(let s=0;s"scheme must not be undefined or null."),e.endsWith(yu)&&(e=e.slice(0,e.indexOf(yu))),O(e.length>0,()=>"scheme must not be an empty string.");let n=Ss.getInstance();O(n.managers[e]==null,()=>`A model store manager is already registered for scheme '${e}'.`),n.managers[e]=t}static getManager(e){let 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 Mh(e){if(e.indexOf(yu)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Ss.getSchemes().join(",")}`);return{scheme:e.split(yu)[0],path:e.split(yu)[1]}}async function V5(e,t,n=!1){O(e!==t,()=>`Old path and new path are the same: '${e}'`);let s=Bt.getLoadHandlers(e);O(s.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),O(s.length<2,()=>`Copying failed because more than one (${s.length}) load handlers for source URL ${e}.`);let r=s[0],a=Bt.getSaveHandlers(t);O(a.length>0,()=>`Copying failed because no save handler is found for destination URL ${t}.`),O(a.length<2,()=>`Copying failed because more than one (${s.length}) save handlers for destination URL ${t}.`);let o=a[0],i=Mh(e).scheme,l=Mh(e).path,c=i===Mh(e).scheme,u=await r.load();n&&c&&await Ss.getManager(i).removeModel(l);let d=await o.save(u);return n&&!c&&await Ss.getManager(i).removeModel(l),d.modelArtifactsInfo}async function h9(){let e=Ss.getSchemes(),t={};for(let n of e){let s=await Ss.getManager(n).listModels();for(let r in s){let a=n+yu+r;t[a]=s[r]}}return t}async function f9(e){let t=Mh(e);return Ss.getManager(t.scheme).removeModel(t.path)}async function m9(e,t){return V5(e,t,!1)}async function g9(e,t){return V5(e,t,!0)}var A9=class{fetch(e,t){return fetch(e,t)}now(){return performance.now()}encode(e,t){if(t!=="utf-8"&&t!=="utf8")throw new Error(`Browser's encoder only supports utf-8, but got ${t}`);return this.textEncoder==null&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(e)}decode(e,t){return new TextDecoder(t).decode(e)}};if(K().get("IS_BROWSER")){K().setPlatform("browser",new A9);try{Ss.registerManager(qi.URL_SCHEME,new p9)}catch(e){}try{Ss.registerManager(ji.URL_SCHEME,new r9)}catch(e){}}var y9={importFetch:()=>RN()},d2,x9=class{constructor(){this.util=$N(),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return K().global.fetch!=null?K().global.fetch(e,t):(d2==null&&(d2=y9.importFetch()),d2(e,t))}now(){let e=process.hrtime();return e[0]*1e3+e[1]/1e6}encode(e,t){if(t!=="utf-8"&&t!=="utf8")throw new Error(`Node built-in encoder only supports utf-8, but got ${t}`);return this.textEncoder.encode(e)}decode(e,t){return e.length===0?"":new this.util.TextDecoder(t).decode(e)}};K().get("IS_NODE")&&K().setPlatform("node",new x9);function Le(e,t="float32",n){return t=t||"float32",Bg(e),new sn(e,t,n)}function b9(e,t){let n=_(e,"x","cast");if(!i5(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");let s={x:n},r={dtype:t};return B.runKernel(Ca,s,r)}var he=V({cast_:b9});function v9(e){let n={x:_(e,"x","clone","string_or_numeric")};return B.runKernel(Ba,n)}var or=V({clone_:v9});function U5(e,t=!1){console.log(e.toString(t))}T5();var w9={buffer:Le,cast:he,clone:or,print:U5};DE(w9);var ns={};ze(ns,{browserFiles:()=>E9,browserHTTPRequest:()=>P9,concatenateArrayBuffers:()=>o2,copyModel:()=>m9,decodeWeights:()=>D5,encodeWeights:()=>GE,fromMemory:()=>O9,getLoadHandlers:()=>t9,getModelArtifactsForJSON:()=>i2,getModelArtifactsInfoForJSON:()=>od,getSaveHandlers:()=>e9,http:()=>m2,isHTTPScheme:()=>f2,listModels:()=>h9,loadWeights:()=>R9,moveModel:()=>g9,registerLoadRouter:()=>QE,registerSaveRouter:()=>JE,removeModel:()=>f9,weightsLoaderFactory:()=>q5,withSaveHandler:()=>M9});var k9="model",I9=".json",S9=".weights.bin";function G5(e){return new Promise(t=>setTimeout(t)).then(e)}var p2=class{constructor(e){if(!K().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(p2.URL_SCHEME)&&(e=e.slice(p2.URL_SCHEME.length)),(e==null||e.length===0)&&(e=k9),this.modelJsonFileName=e+I9,this.weightDataFileName=e+S9}async save(e){if(typeof document=="undefined")throw new Error("Browser downloads are not supported in this environment since `document` is not present");let 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.");{let n=[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}],s=F5(e,n),r=window.URL.createObjectURL(new Blob([JSON.stringify(s)],{type:"application/json"})),a=this.modelJsonAnchor==null?document.createElement("a"):this.modelJsonAnchor;if(a.download=this.modelJsonFileName,a.href=r,await G5(()=>a.dispatchEvent(new MouseEvent("click"))),e.weightData!=null){let o=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor;o.download=this.weightDataFileName,o.href=t,await G5(()=>o.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:od(e)}}}},zh=p2;zh.URL_SCHEME="downloads://";var C9=class{constructor(e){if(e==null||e.length<1)throw new Error(`When calling browserFiles, at least 1 file is required, but received ${e}`);this.jsonFile=e[0],this.weightsFiles=e.slice(1)}async load(){return new Promise((e,t)=>{let n=new FileReader;n.onload=s=>{let r=JSON.parse(s.target.result),a=r.modelTopology;if(a==null){t(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`));return}if(r.weightsManifest==null){t(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`));return}if(this.weightsFiles.length===0){e({modelTopology:a});return}let i=i2(r,l=>this.loadWeights(l));e(i)},n.onerror=s=>t(`Failed to read model topology and weights manifest JSON from file '${this.jsonFile.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),n.readAsText(this.jsonFile)})}loadWeights(e){let t=[],n=[];for(let a of e)t.push(...a.weights),n.push(...a.paths);let s=this.checkManifestAndWeightFiles(e),r=n.map(a=>this.loadWeightsFile(a,s[a]));return Promise.all(r).then(a=>[t,o2(a)])}loadWeightsFile(e,t){return new Promise((n,s)=>{let r=new FileReader;r.onload=a=>{let o=a.target.result;n(o)},r.onerror=a=>s(`Failed to weights data from file of path '${e}'.`),r.readAsArrayBuffer(t)})}checkManifestAndWeightFiles(e){let t=[],n=this.weightsFiles.map(r=>P5(r.name)),s={};for(let r of e)r.paths.forEach(a=>{let o=P5(a);if(t.indexOf(o)!==-1)throw new Error(`Duplicate file basename found in weights manifest: '${o}'`);if(t.push(o),n.indexOf(o)===-1)throw new Error(`Weight file with basename '${o}' is not provided.`);s[a]=this.weightsFiles[n.indexOf(o)]});if(t.length!==this.weightsFiles.length)throw new Error(`Mismatch in the number of files in weights manifest (${t.length}) and the number of weight files provided (${this.weightsFiles.length}).`);return s}},T9=e=>K().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(zh.URL_SCHEME)?N9(e.slice(zh.URL_SCHEME.length)):null;Bt.registerSaveRouter(T9);function N9(e="model"){return new zh(e)}function E9(e){return new C9(e)}function H5(e,t,n,s){o(e),n=n==null?0:n,s=s==null?1:s,i(n,s);let r=0,a=l=>(l.then(c=>{let u=n+ ++r/e.length*(s-n);return t(u),c}),l);function o(l){O(l!=null&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")}function i(l,c){O(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),O(c>=0&&c<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${c}`),O(c>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${c}`)}return Promise.all(e.map(a))}async function j5(e,t){t==null&&(t={});let n=t.fetchFunc==null?K().platform.fetch:t.fetchFunc,s=e.map(d=>n(d,t.requestInit,{isBinary:!0})),r=0,a=.5,i=(t.onProgress==null?await Promise.all(s):await H5(s,t.onProgress,r,a)).map(d=>d.arrayBuffer()),l=.5,c=1;return t.onProgress==null?await Promise.all(i):await H5(i,t.onProgress,l,c)}async function R9(e,t="",n,s){return q5(o=>j5(o,{requestInit:s}))(e,t,n)}function q5(e){return async(t,n="",s)=>{let r=t.map(()=>!1),a={},o=s!=null?s.map(()=>!1):[],i=[];if(t.forEach((h,f)=>{let m=0;h.weights.forEach(g=>{let A="quantization"in g?g.quantization.dtype:g.dtype,y=r2[A]*Ut(g.shape),x=()=>{r[f]=!0,a[f]==null&&(a[f]=[]),a[f].push({manifestEntry:g,groupOffset:m,sizeBytes:y})};s!=null?s.forEach((b,w)=>{b===g.name&&(x(),o[w]=!0)}):x(),i.push(g.name),m+=y})}),!o.every(h=>h)){let h=s.filter((f,m)=>!o[m]);throw new Error(`Could not find weights in manifest with names: ${h.join(", ")}. +Manifest JSON has weights with names: ${i.join(", ")}.`)}let l=r.reduce((h,f,m)=>(f&&h.push(m),h),[]),c=[];l.forEach(h=>{t[h].paths.forEach(f=>{let m=n+(n.endsWith("/")?"":"/")+f;c.push(m)})});let u=await e(c),d={},p=0;return l.forEach(h=>{let f=t[h].paths.length,m=0;for(let b=0;b{let w=g.slice(b.groupOffset,b.groupOffset+b.sizeBytes),k=D5(w,[b.manifestEntry]);for(let S in k)d[S]=k[S]}),p+=f}),d}}var $9="application/octet-stream",D9="application/json",h2=class{constructor(e,t){if(this.DEFAULT_METHOD="POST",t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,this.weightUrlConverter=t.weightUrlConverter,t.fetchFunc!=null?(O(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=K().platform.fetch,O(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&O(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.");let t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;let n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],s=F5(e,n);t.body.append("model.json",new Blob([JSON.stringify(s)],{type:D9}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:$9}),"model.weights.bin");let r=await this.fetch(this.path,t);if(r.ok)return{modelArtifactsInfo:od(e),responses:[r]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${r.status}.`)}async load(){let 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(r){let a=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?a+=" 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.":a+=" Please make sure the server is serving valid JSON for this request.",new Error(a)}let n=t.modelTopology,s=t.weightsManifest;if(n==null&&s==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);return i2(t,r=>this.loadWeights(r))}async loadWeights(e){let t=Array.isArray(this.path)?this.path[1]:this.path,[n,s]=_9(t),r=this.weightPathPrefix||n,a=[];for(let c of e)a.push(...c.weights);let o=[],i=[];for(let c of e)for(let u of c.paths)this.weightUrlConverter!=null?i.push(this.weightUrlConverter(u)):o.push(r+u+s);this.weightUrlConverter&&o.push(...await Promise.all(i));let l=await j5(o,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[a,o2(l)]}};h2.URL_SCHEME_REGEX=/^https?:\/\//;function _9(e){let t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),s=e.substring(0,t),r=n>t?e.substring(n):"";return[s+"/",r]}function f2(e){return e.match(h2.URL_SCHEME_REGEX)!=null}var X5=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let n=!0;if(Array.isArray(e)?n=e.every(s=>f2(s)):n=f2(e),n)return m2(e,t)}return null};Bt.registerSaveRouter(X5);Bt.registerLoadRouter(X5);function m2(e,t){return new h2(e,t)}function P9(e,t){return m2(e,t)}var g2=class{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}},F9=class{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}};function O9(e,t,n,s){return arguments.length===1?e.modelTopology!=null||e.weightSpecs!=null?new g2(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 g2({modelTopology:e})):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new g2({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:s}))}function M9(e){return new F9(e)}var K5={};ze(K5,{confusionMatrix:()=>V9});function z9(e,t,n=!1,s=!1){let r=_(e,"a","matMul"),a=_(t,"b","matMul");[r,a]=Ft(r,a);let o={a:r,b:a},i={transposeA:n,transposeB:s};return B.runKernel(Sa,o,i)}var He=V({matMul_:z9});function L9(e,t,n=1,s=0){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);let a={indices:_(e,"indices","oneHot","int32")},o={depth:t,onValue:n,offValue:s};return B.runKernel(Ii,a,o)}var id=V({oneHot_:L9});function B9(e,t){let n=_(e,"x","transpose");if(t==null&&(t=n.shape.map((a,o)=>o).reverse()),O(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of perm ${t}.`),t.forEach(a=>{O(a>=0&&a`All entries in 'perm' must be between 0 and ${n.rank-1} but got ${t}`)}),n.rank<=1)return n.clone();let s={x:n},r={perm:t};return B.runKernel(po,s,r)}var et=V({transpose_:B9});function W9(e,t,n){let s=_(e,"labels","confusionMatrix"),r=_(t,"predictions","confusionMatrix");O(n==null||n>0&&Number.isInteger(n),()=>`If provided, numClasses must be a positive integer, but got ${n}`),O(s.rank===1,()=>`Expected the rank of labels to be 1, but got ${s.rank}`),O(r.rank===1,()=>`Expected the rank of predictions to be 1, but got ${r.rank}`),O(s.shape[0]===r.shape[0],()=>`Mismatch in the number of examples: ${s.shape[0]} vs. ${r.shape[0]}. Labels and predictions should have the same number of elements.`),O(n>0&&Number.isInteger(n),()=>`numClasses is required to be a positive integer, but got ${n}`);let a=id(he(s,"int32"),n),o=id(he(r,"int32"),n),i=et(a),l=He(i,o);return he(l,"int32")}var V9=V({confusionMatrix_:W9}),Gs={};ze(Gs,{fromPixels:()=>K9,fromPixelsAsync:()=>q9,toPixels:()=>X9});function Z5(e,t,n){if(ei(e),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");let s=Cr(e,n);if(s.length!==3&&s.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return xo(e,t,s,n)}var xu;function Y5(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,s=!1,r=!1,a=!1,o=!1,i=!1;if(e.data instanceof Uint8Array)n=!0;else if(typeof ImageData!="undefined"&&e instanceof ImageData)s=!0;else if(typeof HTMLVideoElement!="undefined"&&e instanceof HTMLVideoElement)r=!0;else if(typeof HTMLImageElement!="undefined"&&e instanceof HTMLImageElement)a=!0;else if(e.getContext!=null)o=!0;else if(typeof ImageBitmap!="undefined"&&e instanceof ImageBitmap)i=!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(r){let f=2;if(r&&e.readyState element.")}if($h(Kc,B.backendName)!=null){let f={pixels:e},m={numChannels:t};return B.runKernel(Kc,f,m)}let[c,u]=r?[e.videoWidth,e.videoHeight]:[e.width,e.height],d;o?d=e.getContext("2d").getImageData(0,0,c,u).data:s||n?d=e.data:(a||r||i)&&(xu==null&&(xu=document.createElement("canvas").getContext("2d")),xu.canvas.width=c,xu.canvas.height=u,xu.drawImage(e,0,0,c,u),d=xu.getImageData(0,0,c,u).data);let p;if(t===4)p=new Int32Array(d);else{let f=c*u;p=new Int32Array(f*t);for(let m=0;m4||a===2)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${a}`);if(n.dtype!=="float32"&&n.dtype!=="int32")throw new Error(`Unsupported type for toPixels: ${n.dtype}. Please use float32 or int32 tensors.`);let o=await n.data(),i=n.dtype==="float32"?255:1,l=new Uint8ClampedArray(r*s*4);for(let c=0;c1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${h}.`)}else if(n.dtype==="int32"&&(h<0||h>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${h}.`);a===1?(u[0]=h*i,u[1]=h*i,u[2]=h*i):u[p]=h*i}let d=c*4;l[d+0]=Math.round(u[0]),l[d+1]=Math.round(u[1]),l[d+2]=Math.round(u[2]),l[d+3]=Math.round(u[3])}if(t!=null){t.width=r,t.height=s;let c=t.getContext("2d"),u=new ImageData(l,r,s);c.putImageData(u,0,0)}return n!==e&&n.dispose(),l}var K9=V({fromPixels_:Y5}),A2={};ze(A2,{prepareAndValidate:()=>J5});function J5(e,t){let n=e.shape.length,s=t.shape.length;if(n<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${n}.`);if(s<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${s}.`);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[s-1]>n)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[s-1]} vs. ${n}`);if(Ut(e.shape)===0)throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);let r=t.shape,a=r[r.length-1],o=1;for(let d=0;dd/c),1].slice(0,a);return[l,o,c,u]}var y2={};ze(y2,{calculateShapes:()=>Q5,validateInput:()=>b2,validateUpdateShape:()=>x2});function x2(e,t,n){let s=t.rank>1?t.shape[t.rank-1]:1,r=t.rank>1?t.rank-1:1,a=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${n.shape}, indices.shape: ${t.shape}, shape: ${e}, sliceDim: ${s}, and batchDim: ${r}.`;if(n.rank1?t.shape[s-1]:1,a=n.length,o=1;for(let d=r;dZ9,computeFlatOffset:()=>J9,computeOutShape:()=>e3,getNormalizedAxes:()=>r3,isSliceContinous:()=>Y9,maskToAxes:()=>Lh,parseSliceParams:()=>c3,sliceInfo:()=>Q9,startForAxis:()=>l3,startIndicesWithElidedDims:()=>a3,stopForAxis:()=>u3,stopIndicesWithElidedDims:()=>o3,stridesForAxis:()=>i3,stridesWithElidedDims:()=>t3});function Z9(e,t,n){let s=e.shape.length;O(s===t.length,()=>`Error in slice${s}D: Length of begin ${t} must match the rank of the array (${s}).`),O(s===n.length,()=>`Error in slice${s}D: Length of size ${n} must match the rank of the array (${s}).`);for(let r=0;r`Error in slice${s}D: begin[${r}] + size[${r}] (${t[r]+n[r]}) would overflow input.shape[${r}] (${e.shape[r]})`)}function Lh(e){let t=[],n=0;for(;e>0;)e&1&&t.push(n),e/=2,n++;return t}function e3(e,t,n){let s=[];for(let r=0;r0){let h=t[0],f=n+1;u=a3(o,h,f,s,e),d=o3(i,h,f,r,e),p=t3(a,h,f,e)}else for(let h=0;h-1)a[i]=0;else{let l=n3(t,n,i),c=s[l];e&1<-1)a[i]=Number.MAX_SAFE_INTEGER;else{let l=n3(t,n,i),c=s[l];e&1<0?o=Number.MIN_SAFE_INTEGER:o=Number.MAX_SAFE_INTEGER);let l=s[r];return o<0&&(o+=l),o=_c(0,o,l-1),o}function u3(e,t,n,s,r,a){let o=t[r],i=n[r]||1;(e&1<0?o=Number.MAX_SAFE_INTEGER:o=Number.MIN_SAFE_INTEGER);let l=s[r];return o<0&&(o+=l),i>0?o=_c(0,o,l):o=_c(-1,o,l-1),o}function Y9(e,t,n){let s=n.length;for(let r=0;r1){s=r;break}for(let r=s+1;r0||n[r]!==e[r])return!1;return!0}function J9(e,t){let n=e.length>0?e[e.length-1]:1;for(let s=0;s{O(o!==-1,()=>"slice() does not support negative begin indexing.")});let a;return n==null?a=new Array(r).fill(-1):typeof n=="number"?a=[n,...new Array(r-1).fill(-1)]:n.lengtho>=0?o:(O(o===-1,()=>`Negative size values should be exactly -1 but got ${o} for the slice() size at index ${i}.`),e.shape[i]-s[i])),[s,a]}function Q9(e,t,n,s,r,a,o,i,l){let c=t.slice(),u=n.slice(),d=s;s==null&&(d=new Array(c.length));let p=Lh(o);if(p.length>1)throw new Error("Multiple ellipses in slice is not allowed.");if(o!==0&&i!==0)throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");if(o!==0&&l!==0)throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");let h=e.length-c.length,f=Lh(i),m=e.slice();f.forEach(S=>{c[S]=0,u[S]=1,m.splice(S,0,1)});let{begin:g,end:A,strides:y}=r3(m,p,h,c,u,d,r,a,o);c=g,u=A,d=y;let x=Lh(l);x.forEach(S=>{u[S]=c[S]+1,d[S]=1});let b=e3(c,u,d),w=b.filter((S,E)=>x.indexOf(E)===-1);return{nonStrided:d.every(S=>S===1),$begin:c,$end:u,$strides:d,size:b,newShape:m,outShape:w}}var le={};ze(le,{Serializable:()=>d3,SerializationMap:()=>Xi,registerClass:()=>vo});var d3=class{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}},Xi=class{constructor(){this.classNameMap={}}static getMap(){return Xi.instance==null&&(Xi.instance=new Xi),Xi.instance}static register(e){Xi.getMap().classNameMap[e.className]=[e,e.fromConfig]}};function vo(e){O(e.className!=null,()=>"Class being registered does not have the static className property defined."),O(typeof e.className=="string",()=>"className is required to be a string, but got type "+typeof e.className),O(e.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),Xi.register(e)}var p3={};ze(p3,{TEST_EPSILON_FLOAT16:()=>h3,encodeStrings:()=>f3,expectArrayBuffersEqual:()=>oR,expectArraysClose:()=>tR,expectArraysEqual:()=>sR,expectNumbersClose:()=>rR,expectPromiseToFail:()=>nR,expectValuesInRange:()=>aR,testEpsilon:()=>v2});var eR=.001,h3=.1;function tR(e,t,n){return n==null&&(n=v2()),w2(e,t,(s,r)=>k2(s,r,n))}function v2(){return B.backend.floatPrecision()===32?eR:h3}function w2(e,t,n){let s=!0;if((Dn(e)||Dn(t))&&(s=!1),Dn(e)&&Dn(t)&&(s=!0),s){let o=e.constructor.name,i=t.constructor.name;if(o!==i)throw new Error(`Arrays are of different type. Actual: ${o}. Expected: ${i}`)}if(Array.isArray(e)&&Array.isArray(t)){let o=Cr(e),i=Cr(t);if(!Gr(o,i))throw new Error(`Arrays have different shapes. Actual: [${o}]. Expected: [${i}]`)}let r=Dn(e)?e:ti(e),a=Dn(t)?t:ti(t);if(r.length!==a.length)throw new Error(`Arrays have different lengths actual: ${r.length} vs expected: ${a.length}. Actual: ${r}. Expected: ${a}.`);for(let o=0;ot.fail(),()=>t())}function sR(e,t){let n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return ba(e)||ba(e[0])||ba(t)||ba(t[0])?w2(e,n,(s,r)=>s==r):w2(e,t,(s,r)=>k2(s,r,0))}function rR(e,t,n){if(n==null&&(n=v2()),!k2(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function k2(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function aR(e,t,n){for(let s=0;sn)throw new Error(`Value out of range:${e[s]} low: ${t}, high: ${n}`)}function oR(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}function f3(e){for(let t=0;tn.dispose())}function yn(e){return B.keep(e)}function dR(e){return B.time(e)}function g3(e){return B.setBackend(e)}function Wh(){return B.ready()}function ir(){return B.backendName}function pR(e){B.removeBackend(e)}function S2(e){return B.findBackend(e)}function hR(e){return B.findBackendFactory(e)}function Ki(e,t,n=1){return B.registerBackend(e,t,n)}function Tr(){return B.backend}function fR(e,t){K().setPlatform(e,t)}function mR(e,t){let n=D(e,"a","add"),s=D(t,"b","add");[n,s]=Ft(n,s);let r={a:n,b:s};return B.runKernel(Hr,r)}var ie=V({add_:mR});function gR(e,t){let n=D(e,"a","floorDiv"),s=D(t,"b","floorDiv");[n,s]=Ft(n,s);let r={a:n,b:s};return B.runKernel(Ma,r)}var C2=V({floorDiv_:gR});function AR(e,t){let n=D(e,"a","div"),s=D(t,"b","div");if([n,s]=Ft(n,s),n.dtype==="int32"&&s.dtype==="int32")return C2(n,s);let r={a:n,b:s},a={};return B.runKernel(_a,r,a)}var he=V({div_:AR});function yR(e,t){let n=D(e,"a","mul"),s=D(t,"b","mul");[n,s]=Ft(n,s);let r={a:n,b:s};return B.runKernel(Ka,r)}var W=V({mul_:yR});function xR(e){let t=D(e,"x","abs");if(t.dtype==="complex64"){let n={x:t};return B.runKernel(Mc,n)}else{let n={x:t};return B.runKernel(ni,n)}}var rn=V({abs_:xR});function bR(e){let n={x:D(e,"x","acos")};return B.runKernel(Vl,n)}var A3=V({acos_:bR});function vR(e){let n={x:D(e,"x","acosh")};return B.runKernel(Ul,n)}var y3=V({acosh_:vR});function wR(e){O(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),O(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);let t=e.map((r,a)=>D(r,`tensors${a}`,"addN")),n=t[0];t.forEach(r=>{if(r.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(r=>{if(!Gr(r.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let s=t;return B.runKernel(wa,s)}var Vh=V({addN_:wR});function kR(e,t=null,n=!1){let r={x:D(e,"x","all","bool")},a={axis:t,keepDims:n};return B.runKernel(Gl,r,a)}var T2=V({all_:kR});function IR(e,t=null,n=!1){let r={x:D(e,"x","any","bool")},a={axis:t,keepDims:n};return B.runKernel(Hl,r,a)}var Uh=V({any_:IR});function SR(e,t=0){let s={x:D(e,"x","argMax")},r={axis:t};return B.runKernel(ka,s,r)}var Hs=V({argMax_:SR});function CR(e,t=0){let s={x:D(e,"x","argMin")},r={axis:t};return B.runKernel(jl,s,r)}var x3=V({argMin_:CR});function TR(e){let n={x:D(e,"x","asin")};return B.runKernel(ql,n)}var b3=V({asin_:TR});function NR(e){let n={x:D(e,"x","asinh")};return B.runKernel(Xl,n)}var v3=V({asinh_:NR});function ER(e){let n={x:D(e,"x","atan")};return B.runKernel(Kl,n)}var w3=V({atan_:ER});function RR(e,t){let n=D(e,"a","atan2"),s=D(t,"b","atan2");[n,s]=Ft(n,s);let r={a:n,b:s};return B.runKernel(Yl,r)}var k3=V({atan2_:RR});function $R(e){let n={x:D(e,"x","atanh")};return B.runKernel(Zl,n)}var I3=V({atanh_:$R});function DR(e,t,n,s,r="NHWC",a){let o=e[3],i=[...t,o],l=T3(r);return ld(e,i,n,a,s,null,null,l)}function S3(e,t,n,s,r,a,o="channelsLast"){let[i,l]=Gh(t),c;if(o==="channelsLast")c=[i,l,e[3],e[3]];else if(o==="channelsFirst")c=[i,l,e[1],e[1]];else throw new Error(`Unknown dataFormat ${o}`);return ld(e,c,n,s,r,a,!1,o)}function _R(e,t,n,s,r,a,o="NDHWC"){let[i,l,c]=E2(t),u,d;if(o==="NDHWC")d="channelsLast",u=[i,l,c,e[4],e[4]];else if(o==="NCDHW")d="channelsFirst",u=[i,l,c,e[1],e[1]];else throw new Error(`Unknown dataFormat ${o}`);return C3(e,u,n,s,r,!1,d,a)}function ld(e,t,n,s,r,a,o=!1,i="channelsLast"){let[l,c,u,d]=[-1,-1,-1,-1];if(i==="channelsLast")[l,c,u,d]=e;else if(i==="channelsFirst")[l,d,c,u]=e;else throw new Error(`Unknown dataFormat ${i}`);let[p,h,,f]=t,[m,g]=Gh(n),[A,y]=Gh(s),x=bu(p,A),b=bu(h,y),{padInfo:w,outHeight:k,outWidth:S}=OR(r,c,u,m,g,x,b,a,i),E=o?f*d:f,P;return i==="channelsFirst"?P=[l,E,k,S]:i==="channelsLast"&&(P=[l,k,S,E]),{batchSize:l,dataFormat:i,inHeight:c,inWidth:u,inChannels:d,outHeight:k,outWidth:S,outChannels:E,padInfo:w,strideHeight:m,strideWidth:g,filterHeight:p,filterWidth:h,effectiveFilterHeight:x,effectiveFilterWidth:b,dilationHeight:A,dilationWidth:y,inShape:e,outShape:P,filterShape:t}}function C3(e,t,n,s,r,a=!1,o="channelsLast",i){let[l,c,u,d,p]=[-1,-1,-1,-1,-1];if(o==="channelsLast")[l,c,u,d,p]=e;else if(o==="channelsFirst")[l,p,c,u,d]=e;else throw new Error(`Unknown dataFormat ${o}`);let[h,f,m,,g]=t,[A,y,x]=E2(n),[b,w,k]=E2(s),S=bu(h,b),E=bu(f,w),P=bu(m,k),{padInfo:F,outDepth:R,outHeight:_,outWidth:T}=MR(r,c,u,d,A,y,x,S,E,P,i),M=a?g*p:g,U;return o==="channelsFirst"?U=[l,M,R,_,T]:o==="channelsLast"&&(U=[l,R,_,T,M]),{batchSize:l,dataFormat:o,inDepth:c,inHeight:u,inWidth:d,inChannels:p,outDepth:R,outHeight:_,outWidth:T,outChannels:M,padInfo:F,strideDepth:A,strideHeight:y,strideWidth:x,filterDepth:h,filterHeight:f,filterWidth:m,effectiveFilterDepth:S,effectiveFilterHeight:E,effectiveFilterWidth:P,dilationDepth:b,dilationHeight:w,dilationWidth:k,inShape:e,outShape:U,filterShape:t}}function PR(e,t,n,s,r){s==null&&(s=N2(e,t,n));let a=e[0],o=e[1],i=Zi((a-t+2*s)/n+1,r),l=Zi((o-t+2*s)/n+1,r);return[i,l]}function FR(e,t,n,s,r,a){r==null&&(r=N2(e,t,s));let o=e[0],i=e[1],l=e[2],c=Zi((o-t+2*r)/s+1,a),u=Zi((i-t+2*r)/s+1,a),d=Zi((l-t+2*r)/s+1,a);return[c,u,d,n]}function N2(e,t,n,s=1){let r=bu(t,s);return Math.floor((e[0]*(n-1)-n+r)/2)}function Gh(e){return typeof e=="number"?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function E2(e){return typeof e=="number"?[e,e,e]:e}function bu(e,t){return t<=1?e:e+(e-1)*(t-1)}function OR(e,t,n,s,r,a,o,i,l){let c,u,d;if(typeof e=="number"){c={top:e,bottom:e,left:e,right:e,type:e===0?"VALID":"NUMBER"};let h=PR([t,n],a,s,e,i);u=h[0],d=h[1]}else if(e==="same"){u=Math.ceil(t/s),d=Math.ceil(n/r);let p=Math.max(0,(u-1)*s+a-t),h=Math.max(0,(d-1)*r+o-n),f=Math.floor(p/2),m=p-f,g=Math.floor(h/2),A=h-g;c={top:f,bottom:m,left:g,right:A,type:"SAME"}}else if(e==="valid")c={top:0,bottom:0,left:0,right:0,type:"VALID"},u=Math.ceil((t-a+1)/s),d=Math.ceil((n-o+1)/r);else if(typeof e=="object"){let p=l==="channelsLast"?e[1][0]:e[2][0],h=l==="channelsLast"?e[1][1]:e[2][1],f=l==="channelsLast"?e[2][0]:e[3][0],m=l==="channelsLast"?e[2][1]:e[3][1];c={top:p,bottom:h,left:f,right:m,type:p===0&&h===0&&f===0&&m===0?"VALID":"EXPLICIT"},u=Zi((t-a+p+h)/s+1,i),d=Zi((n-o+f+m)/r+1,i)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:c,outHeight:u,outWidth:d}}function MR(e,t,n,s,r,a,o,i,l,c,u){let d,p,h,f;if(typeof e=="number"){d={top:e,bottom:e,left:e,right:e,front:e,back:e,type:e===0?"VALID":"NUMBER"};let g=FR([t,n,s,1],i,1,r,e,u);p=g[0],h=g[1],f=g[2]}else if(e==="same"){p=Math.ceil(t/r),h=Math.ceil(n/a),f=Math.ceil(s/o);let m=(p-1)*r+i-t,g=(h-1)*a+l-n,A=(f-1)*o+c-s,y=Math.floor(m/2),x=m-y,b=Math.floor(g/2),w=g-b,k=Math.floor(A/2),S=A-k;d={top:b,bottom:w,left:k,right:S,front:y,back:x,type:"SAME"}}else if(e==="valid")d={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},p=Math.ceil((t-i+1)/r),h=Math.ceil((n-l+1)/a),f=Math.ceil((s-c+1)/o);else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:d,outDepth:p,outHeight:h,outWidth:f}}function Zi(e,t){if(!t)return Math.trunc(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 wo(e){let[t,n,s]=Gh(e);return t===1&&n===1&&s===1}function Nr(e,t){return wo(e)||wo(t)}function T3(e){if(e==="NHWC")return"channelsLast";if(e==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function zR(e,t){let s={x:D(e,"x","reshape","string_or_numeric")},r={shape:t};return B.runKernel(Ti,s,r)}var G=V({reshape_:zR});function LR(e,t,n,s,r){let a=D(e,"x","avgPool","float32"),o=1;O(Nr(n,o),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`);let i=a,l=!1;a.rank===3&&(l=!0,i=G(a,[1,a.shape[0],a.shape[1],a.shape[2]])),O(i.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${i.rank}.`),r!=null&&O(mn(s),()=>`Error in avgPool: pad must be an integer when using, dimRoundingMode ${r} but got pad ${s}.`);let c={x:i},u={filterSize:t,strides:n,pad:s,dimRoundingMode:r},d=B.runKernel(Ia,c,u);return d=de(d,a.dtype),l?G(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Hh=V({avgPool_:LR});function BR(e,t,n,s,r,a="NDHWC"){let o=D(e,"x","avgPool3d","float32"),i=o,l=!1;o.rank===4&&(l=!0,i=G(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),O(i.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${i.rank}.`),O(a==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`),r!=null&&O(mn(s),()=>`Error in avgPool3d: pad must be an integer when using, dimRoundingMode ${r} but got pad ${s}.`);let c={x:i},u={filterSize:t,strides:n,pad:s,dimRoundingMode:r,dataFormat:a},d=B.runKernel(Fc,c,u);return d=de(d,i.dtype),l?G(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var R2=V({avgPool3d_:BR});function WR(e,t=0){O(e.length>=1,()=>"Pass at least one tensor to concat");let n=ad(e,"tensors","concat","string_or_numeric");if(n[0].dtype==="complex64"&&n.forEach(a=>{if(a.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor - with dtype ${a.dtype}. `)}),n.length===1)return or(n[0]);let s=n,r={axis:t};return B.runKernel(ri,s,r)}var It=V({concat_:WR});function VR(e){let n={x:D(e,"x","sigmoid","float32")};return B.runKernel(ro,n)}var hs=V({sigmoid_:VR});function UR(e,t,n){let s=D(e,"x","slice","string_or_numeric");if(s.rank===0)throw new Error("Slicing scalar is not possible");let r={x:s},a={begin:t,size:n};return B.runKernel(Di,r,a)}var _e=V({slice_:UR});function GR(e){let n={x:D(e,"x","tanh","float32")};return B.runKernel(co,n)}var vu=V({tanh_:GR});function HR(e,t,n,s,r,a){let o=D(e,"forgetBias","basicLSTMCell"),i=D(t,"lstmKernel","basicLSTMCell"),l=D(n,"lstmBias","basicLSTMCell"),c=D(s,"data","basicLSTMCell"),u=D(r,"c","basicLSTMCell"),d=D(a,"h","basicLSTMCell"),p=It([c,d],1),h=He(p,i),f=ie(h,l),m=f.shape[0],g=f.shape[1]/4,A=[m,g],y=_e(f,[0,0],A),x=_e(f,[0,g],A),b=_e(f,[0,g*2],A),w=_e(f,[0,g*3],A),k=ie(W(hs(y),vu(x)),W(u,hs(ie(o,b)))),S=W(vu(k),hs(w));return[k,S]}var jR=V({basicLSTMCell_:HR});function qR(e,t,n){let s=D(e,"x","batchToSpaceND"),r=t.reduce((i,l)=>i*l);O(s.rank>=1+t.length,()=>`input rank is ${s.rank} but should be > than blockShape.length ${t.length}`),O(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),O(s.shape[0]%r==0,()=>`input tensor batch is ${s.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${r}`);let a={x:s},o={blockShape:t,crops:n};return B.runKernel(si,a,o)}var jh=V({batchToSpaceND_:qR});function XR(e){let t;return e.rank===0||e.rank===1?t=G(e,[1,1,1,e.size]):e.rank===2?t=G(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=G(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function KR(e,t,n,s,r,a){a==null&&(a=.001);let o=D(e,"x","batchNorm"),i=D(t,"mean","batchNorm"),l=D(n,"variance","batchNorm"),c;r!=null&&(c=D(r,"scale","batchNorm"));let u;s!=null&&(u=D(s,"offset","batchNorm")),O(i.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),O(u==null||i.rank===u.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),O(c==null||i.rank===c.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let p={x:XR(o),scale:c,offset:u,mean:i,variance:l},h={varianceEpsilon:a},f=B.runKernel(za,p,h);return G(f,o.shape)}var wu=V({batchNorm_:KR});function ZR(e,t,n,s,r,a){let o=D(e,"x","batchNorm"),i=D(t,"mean","batchNorm"),l=D(n,"variance","batchNorm"),c;r!=null&&(c=D(r,"scale","batchNorm"));let u;return s!=null&&(u=D(s,"offset","batchNorm")),O(o.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${o.rank}.`),O(i.rank===2||i.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${i.rank}.`),O(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),c!=null&&O(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${c.rank}.`),u!=null&&O(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${u.rank}.`),wu(o,i,l,u,c,a)}var N3=V({batchNorm2d_:ZR});function YR(e,t,n,s,r,a){let o=D(e,"x","batchNorm"),i=D(t,"mean","batchNorm"),l=D(n,"variance","batchNorm"),c;r!=null&&(c=D(r,"scale","batchNorm"));let u;return s!=null&&(u=D(s,"offset","batchNorm")),O(o.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${o.rank}.`),O(i.rank===3||i.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${i.rank}.`),O(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),c!=null&&O(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${c.rank}.`),u!=null&&O(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${u.rank}.`),wu(o,i,l,u,c,a)}var E3=V({batchNorm3d_:YR});function JR(e,t,n,s,r,a){let o=D(e,"x","batchNorm"),i=D(t,"mean","batchNorm"),l=D(n,"variance","batchNorm"),c;r!=null&&(c=D(r,"scale","batchNorm"));let u;return s!=null&&(u=D(s,"offset","batchNorm")),O(o.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${o.rank}.`),O(i.rank===4||i.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${i.rank}.`),O(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),c!=null&&O(c.rank===4||c.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${c.rank}.`),u!=null&&O(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${u.rank}.`),wu(o,i,l,u,c,a)}var R3=V({batchNorm4d_:JR});function QR(e,t,n){let s=D(e,"x","bincount"),r=D(t,"weights","bincount");O(s.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${s.dtype}`),O(n>=0,()=>`size must be non-negative, but got ${n}.`),O(r.size===s.size||r.size===0,()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${s.shape}, weights shape: ${r.shape}.`);let a={x:s,weights:r},o={size:n};return B.runKernel(nh,a,o)}var $2=V({bincount_:QR});function e$(e,t){let n=D(e,"s0","broadcastArgs","int32"),s=D(t,"s1","broadcastArgs","int32");if(n.rank!==1)throw new Error(`broadcastArgs(): first input must be a vector (rank=1). Has rank ${n.rank}`);if(s.rank!==1)throw new Error(`broadcastArgs(): second input must be a vector (rank=1). Has rank ${s.rank}`);let r={s0:n,s1:s};return B.runKernel(sh,r)}var $3=V({broadcastArgs_:e$});function t$(e,t){let n=D(e,"broadcastTo","x"),s=n.shape;if(t.some(c=>!(c>0)||c%1!=0))throw new Error(`broadcastTo(): Invalid broadcast shape [${t}].`);if(t.lengthn.rank){let c=n.shape.slice();for(;c.length=0;c--)if(r[c]===t[c])a[c]=1;else if(n.shape[c]!==1)throw new Error(`broadcastTo(): [${s}] cannot be broadcast to [${t}].`);if(a.map((c,u)=>c>1?u:-1).filter(c=>c>=0).length===0)return or(n);let i={x:n},l={reps:a};return B.runKernel(qr,i,l)}var ud=V({broadcastTo_:t$});function n$(e){let n={x:D(e,"x","ceil","float32")};return B.runKernel(Ta,n)}var D3=V({ceil_:n$});function s$(e,t,n){let s=D(e,"x","clipByValue");O(t<=n,()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`);let r={x:s},a={clipValueMin:t,clipValueMax:n};return B.runKernel(jr,r,a)}var fs=V({clipByValue_:s$});function r$(e){return It(e,0)}var _3=V({concat1d_:r$});function a$(e,t){return It(e,t)}var ku=V({concat2d_:a$});function o$(e,t){return It(e,t)}var P3=V({concat3d_:o$});function i$(e,t){return It(e,t)}var F3=V({concat4d_:i$});function l$(e,t,n,s,r="NHWC",a=[1,1],o){let i=D(e,"x","conv2d","float32"),l=D(t,"filter","conv2d","float32"),c=i,u=!1;i.rank===3&&(u=!0,c=G(i,[1,i.shape[0],i.shape[1],i.shape[2]])),O(c.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${c.rank}.`),O(l.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),o!=null&&O(mn(s),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${s}.`);let d=r==="NHWC"?c.shape[3]:c.shape[1];O(d===l.shape[2],()=>`Error in conv2d: depth of input (${d}) must match input depth for filter ${l.shape[2]}.`),O(Nr(n,a),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`);let p={x:c,filter:l},h={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:o},f=B.runKernel(Na,p,h);return u?G(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var ko=V({conv2d_:l$});function u$(e,t,n,s,r="NWC",a=1,o){let i=D(e,"x","conv1d"),l=D(t,"filter","conv1d"),c=i,u=!1;i.rank===2&&(u=!0,c=G(i,[1,i.shape[0],i.shape[1]])),O(c.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${c.rank}.`),O(l.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),o!=null&&O(mn(s),()=>`Error in conv1d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${s}.`),O(c.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${c.shape[2]}) must match input depth for filter ${l.shape[1]}.`),O(Nr(n,a),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${a}'`),O(r==="NWC",()=>`Error in conv1d: got dataFormat of ${r} but only NWC is currently supported.`);let d=G(l,[1,l.shape[0],l.shape[1],l.shape[2]]),p=G(c,[c.shape[0],1,c.shape[1],c.shape[2]]),g=ko(p,d,[1,n],s,"NHWC",[1,a],o);return u?G(g,[g.shape[2],g.shape[3]]):G(g,[g.shape[0],g.shape[2],g.shape[3]])}var D2=V({conv1d_:u$});function c$(e,t,n,s,r,a="NHWC",o){O(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let i=e,l=t,c=!1;t.rank===3&&(c=!0,l=G(t,[1,t.shape[0],t.shape[1],t.shape[2]]),i=[1,e[0],e[1],e[2]]),O(i.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${i.length}.`),O(l.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),O(n.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`);let u=a==="NHWC"?i[3]:i[1],d=a==="NHWC"?l.shape[3]:l.shape[1];O(u===n.shape[2],()=>`Error in conv2dDerInput: depth of input (${u}) must match input depth for filter ${n.shape[2]}.`),O(d===n.shape[3],()=>`Error in conv2dDerInput: depth of output (${d}) must match output depth for filter ${n.shape[3]}.`),o!=null&&O(mn(r),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);let p={dy:l,filter:n},h={strides:s,pad:r,dataFormat:a,dimRoundingMode:o,inputShape:i},f=B.runKernel(Ea,p,h);return c?G(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var _2=V({conv2DBackpropInput_:c$});function d$(e,t,n,s,r,a){let o=D(e,"x","conv2dTranspose"),i=D(t,"filter","conv2dTranspose");return _2(n,o,i,s,r,"NHWC",a)}var P2=V({conv2dTranspose_:d$});function p$(e,t,n,s,r="NDHWC",a=[1,1,1]){let o=D(e,"x","conv3d"),i=D(t,"filter","conv3d"),l=o,c=!1;o.rank===4&&(c=!0,l=G(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),O(l.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),O(i.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${i.rank}.`),O(l.shape[4]===i.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${i.shape[3]}.`),O(Nr(n,a),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),O(r==="NDHWC",()=>`Error in conv3d: got dataFormat of ${r} but only NDHWC is currently supported.`);let u={x:l,filter:i},d={strides:n,pad:s,dataFormat:r,dilations:a},p=B.runKernel(zc,u,d);return c?G(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var F2=V({conv3d_:p$});function h$(e,t,n,s,r){O(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let a=e,o=t,i=!1;t.rank===4&&(i=!0,o=G(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),a=[1,e[0],e[1],e[2],e[3]]);let l=a[4],c=o.shape[4];O(a.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${a.length}.`),O(o.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${o.rank}`),O(n.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`),O(l===n.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${n.shape[3]}.`),O(c===n.shape[4],()=>`Error in conv3dDerInput: depth of output (${c}) must match output depth for filter ${n.shape[4]}.`);let u={dy:o,filter:n},d={pad:r,strides:s,inputShape:a},p=B.runKernel(oh,u,d);return i?G(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var O3=V({conv3DBackpropInput_:h$});function f$(e,t,n,s,r){let a=D(e,"x","conv3dTranspose"),o=D(t,"filter","conv3dTranspose");return O3(n,a,o,s,r)}var M3=V({conv3dTranspose_:f$});function m$(e){let n={x:D(e,"x","cos","float32")};return B.runKernel(Ra,n)}var qh=V({cos_:m$});function g$(e){let n={x:D(e,"x","cosh","float32")};return B.runKernel($a,n)}var O2=V({cosh_:g$});function A$(e,t=0,n=!1,s=!1){let a={x:D(e,"x","cumsum")},o={axis:t,exclusive:n,reverse:s};return B.runKernel(ai,a,o)}var M2=V({cumsum_:A$});function y$(e,t,n,s=!1){let r=D(e,"x","denseBincount"),a=D(t,"weights","denseBincount");O(r.dtype==="int32",()=>`Error in denseBincount: input dtype must be int32, but got ${r.dtype}`),O(r.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${r.rank}.`),O(n>=0,()=>`size must be non-negative, but got ${n}.`),O(a.size===r.size||a.size===0,()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${r.shape}, weights shape: ${a.shape}.`);let o={x:r,weights:a},i={size:n,binaryOutput:s};return B.runKernel(ih,o,i)}var z3=V({denseBincount_:y$});function x$(e,t,n="NHWC"){let s=D(e,"x","depthToSpace","float32"),r=n==="NHWC"?s.shape[1]:s.shape[2],a=n==="NHWC"?s.shape[2]:s.shape[3],o=n==="NHWC"?s.shape[3]:s.shape[1];O(t>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`),O(r*t>=0,()=>`Negative dimension size caused by overflow when multiplying +Expected: ${a}.`)}}function nR(e,t){e().then(()=>t.fail(),()=>t())}function sR(e,t){let n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return ba(e)||ba(e[0])||ba(t)||ba(t[0])?w2(e,n,(s,r)=>s==r):w2(e,t,(s,r)=>k2(s,r,0))}function rR(e,t,n){if(n==null&&(n=v2()),!k2(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function k2(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function aR(e,t,n){for(let s=0;sn)throw new Error(`Value out of range:${e[s]} low: ${t}, high: ${n}`)}function oR(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}function f3(e){for(let t=0;tn.dispose())}function yn(e){return B.keep(e)}function dR(e){return B.time(e)}function g3(e){return B.setBackend(e)}function Wh(){return B.ready()}function ir(){return B.backendName}function pR(e){B.removeBackend(e)}function S2(e){return B.findBackend(e)}function hR(e){return B.findBackendFactory(e)}function Ki(e,t,n=1){return B.registerBackend(e,t,n)}function Tr(){return B.backend}function fR(e,t){K().setPlatform(e,t)}function mR(e,t){let n=_(e,"a","add"),s=_(t,"b","add");[n,s]=Ft(n,s);let r={a:n,b:s};return B.runKernel(Hr,r)}var ie=V({add_:mR});function gR(e,t){let n=_(e,"a","floorDiv"),s=_(t,"b","floorDiv");[n,s]=Ft(n,s);let r={a:n,b:s};return B.runKernel(Ma,r)}var C2=V({floorDiv_:gR});function AR(e,t){let n=_(e,"a","div"),s=_(t,"b","div");if([n,s]=Ft(n,s),n.dtype==="int32"&&s.dtype==="int32")return C2(n,s);let r={a:n,b:s},a={};return B.runKernel(_a,r,a)}var fe=V({div_:AR});function yR(e,t){let n=_(e,"a","mul"),s=_(t,"b","mul");[n,s]=Ft(n,s);let r={a:n,b:s};return B.runKernel(Ka,r)}var W=V({mul_:yR});function xR(e){let t=_(e,"x","abs");if(t.dtype==="complex64"){let n={x:t};return B.runKernel(Mc,n)}else{let n={x:t};return B.runKernel(ni,n)}}var rn=V({abs_:xR});function bR(e){let n={x:_(e,"x","acos")};return B.runKernel(Vl,n)}var A3=V({acos_:bR});function vR(e){let n={x:_(e,"x","acosh")};return B.runKernel(Ul,n)}var y3=V({acosh_:vR});function wR(e){O(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),O(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);let t=e.map((r,a)=>_(r,`tensors${a}`,"addN")),n=t[0];t.forEach(r=>{if(r.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(r=>{if(!Gr(r.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let s=t;return B.runKernel(wa,s)}var Vh=V({addN_:wR});function kR(e,t=null,n=!1){let r={x:_(e,"x","all","bool")},a={axis:t,keepDims:n};return B.runKernel(Gl,r,a)}var T2=V({all_:kR});function IR(e,t=null,n=!1){let r={x:_(e,"x","any","bool")},a={axis:t,keepDims:n};return B.runKernel(Hl,r,a)}var Uh=V({any_:IR});function SR(e,t=0){let s={x:_(e,"x","argMax")},r={axis:t};return B.runKernel(ka,s,r)}var Hs=V({argMax_:SR});function CR(e,t=0){let s={x:_(e,"x","argMin")},r={axis:t};return B.runKernel(jl,s,r)}var x3=V({argMin_:CR});function TR(e){let n={x:_(e,"x","asin")};return B.runKernel(ql,n)}var b3=V({asin_:TR});function NR(e){let n={x:_(e,"x","asinh")};return B.runKernel(Xl,n)}var v3=V({asinh_:NR});function ER(e){let n={x:_(e,"x","atan")};return B.runKernel(Kl,n)}var w3=V({atan_:ER});function RR(e,t){let n=_(e,"a","atan2"),s=_(t,"b","atan2");[n,s]=Ft(n,s);let r={a:n,b:s};return B.runKernel(Yl,r)}var k3=V({atan2_:RR});function $R(e){let n={x:_(e,"x","atanh")};return B.runKernel(Zl,n)}var I3=V({atanh_:$R});function DR(e,t,n,s,r="NHWC",a){let o=e[3],i=[...t,o],l=T3(r);return ld(e,i,n,a,s,null,null,l)}function S3(e,t,n,s,r,a,o="channelsLast"){let[i,l]=Gh(t),c;if(o==="channelsLast")c=[i,l,e[3],e[3]];else if(o==="channelsFirst")c=[i,l,e[1],e[1]];else throw new Error(`Unknown dataFormat ${o}`);return ld(e,c,n,s,r,a,!1,o)}function _R(e,t,n,s,r,a,o="NDHWC"){let[i,l,c]=E2(t),u,d;if(o==="NDHWC")d="channelsLast",u=[i,l,c,e[4],e[4]];else if(o==="NCDHW")d="channelsFirst",u=[i,l,c,e[1],e[1]];else throw new Error(`Unknown dataFormat ${o}`);return C3(e,u,n,s,r,!1,d,a)}function ld(e,t,n,s,r,a,o=!1,i="channelsLast"){let[l,c,u,d]=[-1,-1,-1,-1];if(i==="channelsLast")[l,c,u,d]=e;else if(i==="channelsFirst")[l,d,c,u]=e;else throw new Error(`Unknown dataFormat ${i}`);let[p,h,,f]=t,[m,g]=Gh(n),[A,y]=Gh(s),x=bu(p,A),b=bu(h,y),{padInfo:w,outHeight:k,outWidth:S}=OR(r,c,u,m,g,x,b,a,i),E=o?f*d:f,$;return i==="channelsFirst"?$=[l,E,k,S]:i==="channelsLast"&&($=[l,k,S,E]),{batchSize:l,dataFormat:i,inHeight:c,inWidth:u,inChannels:d,outHeight:k,outWidth:S,outChannels:E,padInfo:w,strideHeight:m,strideWidth:g,filterHeight:p,filterWidth:h,effectiveFilterHeight:x,effectiveFilterWidth:b,dilationHeight:A,dilationWidth:y,inShape:e,outShape:$,filterShape:t}}function C3(e,t,n,s,r,a=!1,o="channelsLast",i){let[l,c,u,d,p]=[-1,-1,-1,-1,-1];if(o==="channelsLast")[l,c,u,d,p]=e;else if(o==="channelsFirst")[l,p,c,u,d]=e;else throw new Error(`Unknown dataFormat ${o}`);let[h,f,m,,g]=t,[A,y,x]=E2(n),[b,w,k]=E2(s),S=bu(h,b),E=bu(f,w),$=bu(m,k),{padInfo:F,outDepth:R,outHeight:P,outWidth:T}=MR(r,c,u,d,A,y,x,S,E,$,i),M=a?g*p:g,U;return o==="channelsFirst"?U=[l,M,R,P,T]:o==="channelsLast"&&(U=[l,R,P,T,M]),{batchSize:l,dataFormat:o,inDepth:c,inHeight:u,inWidth:d,inChannels:p,outDepth:R,outHeight:P,outWidth:T,outChannels:M,padInfo:F,strideDepth:A,strideHeight:y,strideWidth:x,filterDepth:h,filterHeight:f,filterWidth:m,effectiveFilterDepth:S,effectiveFilterHeight:E,effectiveFilterWidth:$,dilationDepth:b,dilationHeight:w,dilationWidth:k,inShape:e,outShape:U,filterShape:t}}function PR(e,t,n,s,r){s==null&&(s=N2(e,t,n));let a=e[0],o=e[1],i=Zi((a-t+2*s)/n+1,r),l=Zi((o-t+2*s)/n+1,r);return[i,l]}function FR(e,t,n,s,r,a){r==null&&(r=N2(e,t,s));let o=e[0],i=e[1],l=e[2],c=Zi((o-t+2*r)/s+1,a),u=Zi((i-t+2*r)/s+1,a),d=Zi((l-t+2*r)/s+1,a);return[c,u,d,n]}function N2(e,t,n,s=1){let r=bu(t,s);return Math.floor((e[0]*(n-1)-n+r)/2)}function Gh(e){return typeof e=="number"?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function E2(e){return typeof e=="number"?[e,e,e]:e}function bu(e,t){return t<=1?e:e+(e-1)*(t-1)}function OR(e,t,n,s,r,a,o,i,l){let c,u,d;if(typeof e=="number"){c={top:e,bottom:e,left:e,right:e,type:e===0?"VALID":"NUMBER"};let h=PR([t,n],a,s,e,i);u=h[0],d=h[1]}else if(e==="same"){u=Math.ceil(t/s),d=Math.ceil(n/r);let p=Math.max(0,(u-1)*s+a-t),h=Math.max(0,(d-1)*r+o-n),f=Math.floor(p/2),m=p-f,g=Math.floor(h/2),A=h-g;c={top:f,bottom:m,left:g,right:A,type:"SAME"}}else if(e==="valid")c={top:0,bottom:0,left:0,right:0,type:"VALID"},u=Math.ceil((t-a+1)/s),d=Math.ceil((n-o+1)/r);else if(typeof e=="object"){let p=l==="channelsLast"?e[1][0]:e[2][0],h=l==="channelsLast"?e[1][1]:e[2][1],f=l==="channelsLast"?e[2][0]:e[3][0],m=l==="channelsLast"?e[2][1]:e[3][1];c={top:p,bottom:h,left:f,right:m,type:p===0&&h===0&&f===0&&m===0?"VALID":"EXPLICIT"},u=Zi((t-a+p+h)/s+1,i),d=Zi((n-o+f+m)/r+1,i)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:c,outHeight:u,outWidth:d}}function MR(e,t,n,s,r,a,o,i,l,c,u){let d,p,h,f;if(typeof e=="number"){d={top:e,bottom:e,left:e,right:e,front:e,back:e,type:e===0?"VALID":"NUMBER"};let g=FR([t,n,s,1],i,1,r,e,u);p=g[0],h=g[1],f=g[2]}else if(e==="same"){p=Math.ceil(t/r),h=Math.ceil(n/a),f=Math.ceil(s/o);let m=(p-1)*r+i-t,g=(h-1)*a+l-n,A=(f-1)*o+c-s,y=Math.floor(m/2),x=m-y,b=Math.floor(g/2),w=g-b,k=Math.floor(A/2),S=A-k;d={top:b,bottom:w,left:k,right:S,front:y,back:x,type:"SAME"}}else if(e==="valid")d={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},p=Math.ceil((t-i+1)/r),h=Math.ceil((n-l+1)/a),f=Math.ceil((s-c+1)/o);else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:d,outDepth:p,outHeight:h,outWidth:f}}function Zi(e,t){if(!t)return Math.trunc(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 wo(e){let[t,n,s]=Gh(e);return t===1&&n===1&&s===1}function Nr(e,t){return wo(e)||wo(t)}function T3(e){if(e==="NHWC")return"channelsLast";if(e==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function zR(e,t){let s={x:_(e,"x","reshape","string_or_numeric")},r={shape:t};return B.runKernel(Ti,s,r)}var G=V({reshape_:zR});function LR(e,t,n,s,r){let a=_(e,"x","avgPool","float32"),o=1;O(Nr(n,o),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`);let i=a,l=!1;a.rank===3&&(l=!0,i=G(a,[1,a.shape[0],a.shape[1],a.shape[2]])),O(i.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${i.rank}.`),r!=null&&O(mn(s),()=>`Error in avgPool: pad must be an integer when using, dimRoundingMode ${r} but got pad ${s}.`);let c={x:i},u={filterSize:t,strides:n,pad:s,dimRoundingMode:r},d=B.runKernel(Ia,c,u);return d=he(d,a.dtype),l?G(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Hh=V({avgPool_:LR});function BR(e,t,n,s,r,a="NDHWC"){let o=_(e,"x","avgPool3d","float32"),i=o,l=!1;o.rank===4&&(l=!0,i=G(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),O(i.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${i.rank}.`),O(a==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`),r!=null&&O(mn(s),()=>`Error in avgPool3d: pad must be an integer when using, dimRoundingMode ${r} but got pad ${s}.`);let c={x:i},u={filterSize:t,strides:n,pad:s,dimRoundingMode:r,dataFormat:a},d=B.runKernel(Fc,c,u);return d=he(d,i.dtype),l?G(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var R2=V({avgPool3d_:BR});function WR(e,t=0){O(e.length>=1,()=>"Pass at least one tensor to concat");let n=ad(e,"tensors","concat","string_or_numeric");if(n[0].dtype==="complex64"&&n.forEach(a=>{if(a.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor + with dtype ${a.dtype}. `)}),n.length===1)return or(n[0]);let s=n,r={axis:t};return B.runKernel(ri,s,r)}var It=V({concat_:WR});function VR(e){let n={x:_(e,"x","sigmoid","float32")};return B.runKernel(ro,n)}var hs=V({sigmoid_:VR});function UR(e,t,n){let s=_(e,"x","slice","string_or_numeric");if(s.rank===0)throw new Error("Slicing scalar is not possible");let r={x:s},a={begin:t,size:n};return B.runKernel(Di,r,a)}var _e=V({slice_:UR});function GR(e){let n={x:_(e,"x","tanh","float32")};return B.runKernel(co,n)}var vu=V({tanh_:GR});function HR(e,t,n,s,r,a){let o=_(e,"forgetBias","basicLSTMCell"),i=_(t,"lstmKernel","basicLSTMCell"),l=_(n,"lstmBias","basicLSTMCell"),c=_(s,"data","basicLSTMCell"),u=_(r,"c","basicLSTMCell"),d=_(a,"h","basicLSTMCell"),p=It([c,d],1),h=He(p,i),f=ie(h,l),m=f.shape[0],g=f.shape[1]/4,A=[m,g],y=_e(f,[0,0],A),x=_e(f,[0,g],A),b=_e(f,[0,g*2],A),w=_e(f,[0,g*3],A),k=ie(W(hs(y),vu(x)),W(u,hs(ie(o,b)))),S=W(vu(k),hs(w));return[k,S]}var jR=V({basicLSTMCell_:HR});function qR(e,t,n){let s=_(e,"x","batchToSpaceND"),r=t.reduce((i,l)=>i*l);O(s.rank>=1+t.length,()=>`input rank is ${s.rank} but should be > than blockShape.length ${t.length}`),O(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),O(s.shape[0]%r==0,()=>`input tensor batch is ${s.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${r}`);let a={x:s},o={blockShape:t,crops:n};return B.runKernel(si,a,o)}var jh=V({batchToSpaceND_:qR});function XR(e){let t;return e.rank===0||e.rank===1?t=G(e,[1,1,1,e.size]):e.rank===2?t=G(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=G(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function KR(e,t,n,s,r,a){a==null&&(a=.001);let o=_(e,"x","batchNorm"),i=_(t,"mean","batchNorm"),l=_(n,"variance","batchNorm"),c;r!=null&&(c=_(r,"scale","batchNorm"));let u;s!=null&&(u=_(s,"offset","batchNorm")),O(i.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),O(u==null||i.rank===u.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),O(c==null||i.rank===c.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let p={x:XR(o),scale:c,offset:u,mean:i,variance:l},h={varianceEpsilon:a},f=B.runKernel(za,p,h);return G(f,o.shape)}var wu=V({batchNorm_:KR});function ZR(e,t,n,s,r,a){let o=_(e,"x","batchNorm"),i=_(t,"mean","batchNorm"),l=_(n,"variance","batchNorm"),c;r!=null&&(c=_(r,"scale","batchNorm"));let u;return s!=null&&(u=_(s,"offset","batchNorm")),O(o.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${o.rank}.`),O(i.rank===2||i.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${i.rank}.`),O(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),c!=null&&O(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${c.rank}.`),u!=null&&O(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${u.rank}.`),wu(o,i,l,u,c,a)}var N3=V({batchNorm2d_:ZR});function YR(e,t,n,s,r,a){let o=_(e,"x","batchNorm"),i=_(t,"mean","batchNorm"),l=_(n,"variance","batchNorm"),c;r!=null&&(c=_(r,"scale","batchNorm"));let u;return s!=null&&(u=_(s,"offset","batchNorm")),O(o.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${o.rank}.`),O(i.rank===3||i.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${i.rank}.`),O(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),c!=null&&O(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${c.rank}.`),u!=null&&O(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${u.rank}.`),wu(o,i,l,u,c,a)}var E3=V({batchNorm3d_:YR});function JR(e,t,n,s,r,a){let o=_(e,"x","batchNorm"),i=_(t,"mean","batchNorm"),l=_(n,"variance","batchNorm"),c;r!=null&&(c=_(r,"scale","batchNorm"));let u;return s!=null&&(u=_(s,"offset","batchNorm")),O(o.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${o.rank}.`),O(i.rank===4||i.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${i.rank}.`),O(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),c!=null&&O(c.rank===4||c.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${c.rank}.`),u!=null&&O(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${u.rank}.`),wu(o,i,l,u,c,a)}var R3=V({batchNorm4d_:JR});function QR(e,t,n){let s=_(e,"x","bincount"),r=_(t,"weights","bincount");O(s.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${s.dtype}`),O(n>=0,()=>`size must be non-negative, but got ${n}.`),O(r.size===s.size||r.size===0,()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${s.shape}, weights shape: ${r.shape}.`);let a={x:s,weights:r},o={size:n};return B.runKernel(nh,a,o)}var $2=V({bincount_:QR});function e$(e,t){let n=_(e,"s0","broadcastArgs","int32"),s=_(t,"s1","broadcastArgs","int32");if(n.rank!==1)throw new Error(`broadcastArgs(): first input must be a vector (rank=1). Has rank ${n.rank}`);if(s.rank!==1)throw new Error(`broadcastArgs(): second input must be a vector (rank=1). Has rank ${s.rank}`);let r={s0:n,s1:s};return B.runKernel(sh,r)}var $3=V({broadcastArgs_:e$});function t$(e,t){let n=_(e,"broadcastTo","x"),s=n.shape;if(t.some(c=>!(c>0)||c%1!=0))throw new Error(`broadcastTo(): Invalid broadcast shape [${t}].`);if(t.lengthn.rank){let c=n.shape.slice();for(;c.length=0;c--)if(r[c]===t[c])a[c]=1;else if(n.shape[c]!==1)throw new Error(`broadcastTo(): [${s}] cannot be broadcast to [${t}].`);if(a.map((c,u)=>c>1?u:-1).filter(c=>c>=0).length===0)return or(n);let i={x:n},l={reps:a};return B.runKernel(qr,i,l)}var ud=V({broadcastTo_:t$});function n$(e){let n={x:_(e,"x","ceil","float32")};return B.runKernel(Ta,n)}var D3=V({ceil_:n$});function s$(e,t,n){let s=_(e,"x","clipByValue");O(t<=n,()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`);let r={x:s},a={clipValueMin:t,clipValueMax:n};return B.runKernel(jr,r,a)}var fs=V({clipByValue_:s$});function r$(e){return It(e,0)}var _3=V({concat1d_:r$});function a$(e,t){return It(e,t)}var ku=V({concat2d_:a$});function o$(e,t){return It(e,t)}var P3=V({concat3d_:o$});function i$(e,t){return It(e,t)}var F3=V({concat4d_:i$});function l$(e,t,n,s,r="NHWC",a=[1,1],o){let i=_(e,"x","conv2d","float32"),l=_(t,"filter","conv2d","float32"),c=i,u=!1;i.rank===3&&(u=!0,c=G(i,[1,i.shape[0],i.shape[1],i.shape[2]])),O(c.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${c.rank}.`),O(l.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),o!=null&&O(mn(s),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${s}.`);let d=r==="NHWC"?c.shape[3]:c.shape[1];O(d===l.shape[2],()=>`Error in conv2d: depth of input (${d}) must match input depth for filter ${l.shape[2]}.`),O(Nr(n,a),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`);let p={x:c,filter:l},h={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:o},f=B.runKernel(Na,p,h);return u?G(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var ko=V({conv2d_:l$});function u$(e,t,n,s,r="NWC",a=1,o){let i=_(e,"x","conv1d"),l=_(t,"filter","conv1d"),c=i,u=!1;i.rank===2&&(u=!0,c=G(i,[1,i.shape[0],i.shape[1]])),O(c.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${c.rank}.`),O(l.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),o!=null&&O(mn(s),()=>`Error in conv1d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${s}.`),O(c.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${c.shape[2]}) must match input depth for filter ${l.shape[1]}.`),O(Nr(n,a),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${a}'`),O(r==="NWC",()=>`Error in conv1d: got dataFormat of ${r} but only NWC is currently supported.`);let d=G(l,[1,l.shape[0],l.shape[1],l.shape[2]]),p=G(c,[c.shape[0],1,c.shape[1],c.shape[2]]),g=ko(p,d,[1,n],s,"NHWC",[1,a],o);return u?G(g,[g.shape[2],g.shape[3]]):G(g,[g.shape[0],g.shape[2],g.shape[3]])}var D2=V({conv1d_:u$});function c$(e,t,n,s,r,a="NHWC",o){O(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let i=e,l=t,c=!1;t.rank===3&&(c=!0,l=G(t,[1,t.shape[0],t.shape[1],t.shape[2]]),i=[1,e[0],e[1],e[2]]),O(i.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${i.length}.`),O(l.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),O(n.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`);let u=a==="NHWC"?i[3]:i[1],d=a==="NHWC"?l.shape[3]:l.shape[1];O(u===n.shape[2],()=>`Error in conv2dDerInput: depth of input (${u}) must match input depth for filter ${n.shape[2]}.`),O(d===n.shape[3],()=>`Error in conv2dDerInput: depth of output (${d}) must match output depth for filter ${n.shape[3]}.`),o!=null&&O(mn(r),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);let p={dy:l,filter:n},h={strides:s,pad:r,dataFormat:a,dimRoundingMode:o,inputShape:i},f=B.runKernel(Ea,p,h);return c?G(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var _2=V({conv2DBackpropInput_:c$});function d$(e,t,n,s,r,a){let o=_(e,"x","conv2dTranspose"),i=_(t,"filter","conv2dTranspose");return _2(n,o,i,s,r,"NHWC",a)}var P2=V({conv2dTranspose_:d$});function p$(e,t,n,s,r="NDHWC",a=[1,1,1]){let o=_(e,"x","conv3d"),i=_(t,"filter","conv3d"),l=o,c=!1;o.rank===4&&(c=!0,l=G(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),O(l.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),O(i.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${i.rank}.`),O(l.shape[4]===i.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${i.shape[3]}.`),O(Nr(n,a),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),O(r==="NDHWC",()=>`Error in conv3d: got dataFormat of ${r} but only NDHWC is currently supported.`);let u={x:l,filter:i},d={strides:n,pad:s,dataFormat:r,dilations:a},p=B.runKernel(zc,u,d);return c?G(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var F2=V({conv3d_:p$});function h$(e,t,n,s,r){O(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let a=e,o=t,i=!1;t.rank===4&&(i=!0,o=G(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),a=[1,e[0],e[1],e[2],e[3]]);let l=a[4],c=o.shape[4];O(a.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${a.length}.`),O(o.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${o.rank}`),O(n.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`),O(l===n.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${n.shape[3]}.`),O(c===n.shape[4],()=>`Error in conv3dDerInput: depth of output (${c}) must match output depth for filter ${n.shape[4]}.`);let u={dy:o,filter:n},d={pad:r,strides:s,inputShape:a},p=B.runKernel(oh,u,d);return i?G(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var O3=V({conv3DBackpropInput_:h$});function f$(e,t,n,s,r){let a=_(e,"x","conv3dTranspose"),o=_(t,"filter","conv3dTranspose");return O3(n,a,o,s,r)}var M3=V({conv3dTranspose_:f$});function m$(e){let n={x:_(e,"x","cos","float32")};return B.runKernel(Ra,n)}var qh=V({cos_:m$});function g$(e){let n={x:_(e,"x","cosh","float32")};return B.runKernel($a,n)}var O2=V({cosh_:g$});function A$(e,t=0,n=!1,s=!1){let a={x:_(e,"x","cumsum")},o={axis:t,exclusive:n,reverse:s};return B.runKernel(ai,a,o)}var M2=V({cumsum_:A$});function y$(e,t,n,s=!1){let r=_(e,"x","denseBincount"),a=_(t,"weights","denseBincount");O(r.dtype==="int32",()=>`Error in denseBincount: input dtype must be int32, but got ${r.dtype}`),O(r.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${r.rank}.`),O(n>=0,()=>`size must be non-negative, but got ${n}.`),O(a.size===r.size||a.size===0,()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${r.shape}, weights shape: ${a.shape}.`);let o={x:r,weights:a},i={size:n,binaryOutput:s};return B.runKernel(ih,o,i)}var z3=V({denseBincount_:y$});function x$(e,t,n="NHWC"){let s=_(e,"x","depthToSpace","float32"),r=n==="NHWC"?s.shape[1]:s.shape[2],a=n==="NHWC"?s.shape[2]:s.shape[3],o=n==="NHWC"?s.shape[3]:s.shape[1];O(t>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`),O(r*t>=0,()=>`Negative dimension size caused by overflow when multiplying ${r} and ${t} for depthToSpace with input shape ${s.shape}`),O(a*t>=0,()=>`Negative dimension size caused by overflow when multiplying ${a} and ${t} for depthToSpace with input shape - ${s.shape}`),O(o%(t*t)==0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${o} for depthToSpace with input shape ${s.shape}`);let i={x:s},l={blockSize:t,dataFormat:n};return B.runKernel(ii,i,l)}var L3=V({depthToSpace_:x$});function b$(e,t,n,s,r="NHWC",a=[1,1],o){let i=D(e,"x","depthwiseConv2d","float32"),l=D(t,"filter","depthwiseConv2d","float32"),c=i,u=!1;i.rank===3&&(u=!0,c=G(i,[1,i.shape[0],i.shape[1],i.shape[2]])),O(c.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${c.rank}.`),O(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`),O(c.shape[3]===l.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${c.shape[3]}) must match the inChannels dimension in filter ${l.shape[2]}.`),o!=null&&O(mn(s),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${s}.`);let d={x:c,filter:l},p={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:o},h=B.runKernel(Da,d,p);return u?G(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var cd=V({depthwiseConv2d_:b$});function v$(e){let n={x:D(e,"x","diag")};return B.runKernel(ch,n)}var w$=V({diag_:v$});function k$(e,t,n,s,r=[1,1],a="NHWC"){let o=D(e,"x","dilation2d"),i=D(t,"filter","dilation2d");O(o.rank===3||o.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${o.rank}.`),O(i.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${i.rank}.`),O(a==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${a}`);let l=o,c=!1;o.rank===3&&(l=G(o,[1,o.shape[0],o.shape[1],o.shape[2]]),c=!0);let u={x:l,filter:i},d={strides:n,pad:s,dilations:r},p=B.runKernel(Lc,u,d);return c?G(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var B3=V({dilation2d_:k$});function I$(e,t){let n=e.length,s=[];for(let r=0;r1&&o===1&&s.unshift(a)}return s}function an(e,t){let n=[];for(let s=0;s1)&&n.unshift(a)}return n}function St(e,t){let n=[],s=Math.max(e.length,t.length);for(let r=0;r`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${s.rank}.`);let r=n.rank===1?n.size:n.shape[1],a=s.rank===1?s.size:s.shape[0];if(O(r===a,()=>`Error in dot: inner dimensions of inputs must match, but got ${r} and ${a}.`),n.rank===1&&s.rank===1){let o=G(n,[1,-1]),i=G(s,[-1,1]),l=He(o,i);return G(l,[])}else if(n.rank===1&&s.rank===2){let o=G(n,[1,-1]),i=G(s,[s.shape[0],s.shape[1]]),l=He(o,i);return G(l,[l.size])}else if(n.rank===2&&s.rank===1){let o=G(s,[-1,1]),i=He(n,o);return G(i,[i.size])}else{let o=G(s,[s.shape[0],s.shape[1]]);return He(n,o)}}var R$=V({dot_:E$});function $$(e,...t){let n=t.map((r,a)=>D(r,`tensors${a}`,"einsum")),s={equation:e};return B.runKernel(Bc,n,s)}var V3=V({einsum_:$$});function D$(e){let n={x:D(e,"x","elu","float32")};return B.runKernel(Pa,n)}var dd=V({elu_:D$});function _$(e){let t=D(e,"x","erf");O(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),t.dtype==="int32"&&(t=de(t,"float32"));let n={x:t};return B.runKernel(Jl,n)}var U3=V({erf_:_$});function P$(e){let n={x:D(e,"x","exp")};return B.runKernel(Fa,n)}var Ts=V({exp_:P$});function F$(e,t=0){let n=D(e,"x","expandDims","string_or_numeric");O(t<=n.rank,()=>"Axis must be <= rank of the tensor");let s={input:n},r={dim:t};return B.runKernel(ui,s,r)}var Kt=V({expandDims_:F$});function O$(e){let n={x:D(e,"x","expm1")};return B.runKernel(ci,n)}var G3=V({expm1_:O$});function M$(e,t){let n=D(e,"x","tile","string_or_numeric");O(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`);let s={x:n},r={reps:t};return B.runKernel(qr,s,r)}var js=V({tile_:M$});function z$(e,t,n,s="float32"){t==null&&(t=e);let r=Le([e,t],s),a=e<=t?e:t;for(let i=0;i`Error in localResponseNormalization: x must be rank 3 or 4 but got - rank ${a.rank}.`),O(mn(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let o=a,i=!1;a.rank===3&&(i=!0,o=G(a,[1,a.shape[0],a.shape[1],a.shape[2]]));let l={x:o},c={depthRadius:t,bias:n,alpha:s,beta:r},u=B.runKernel(Uc,l,c);return i?G(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var q3=V({localResponseNormalization_:J$});function Q$(e){let n={x:D(e,"x","log","float32")};return B.runKernel(Wa,n)}var Ns=V({log_:Q$});function eD(e){let n={x:D(e,"x","log1p")};return B.runKernel(su,n)}var Zh=V({log1p_:eD});function tD(e){return O(va(e),()=>"The f passed in grad(f) must be a function"),(t,n)=>{let s=D(t,"x","tf.grad","string_or_numeric"),r=n!=null?D(n,"dy","tf.grad"):null;return B.tidy(()=>{let{value:a,grads:o}=B.gradients(()=>e(s),[s],r);return r!=null&&zn(a.shape,r.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Yh(o),o[0]})}}function nD(e){return O(va(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{O(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");let s=ad(t,"args","tf.grads","string_or_numeric"),r=n!=null?D(n,"dy","tf.grads"):null;return B.tidy(()=>{let{value:a,grads:o}=B.gradients(()=>e(...s),s,r);return r!=null&&zn(a.shape,r.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Yh(o),o})}}function sD(e){return O(va(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{O(t instanceof Ye,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),O(n==null||n instanceof Ye,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:s,value:r}=B.gradients(()=>e(t),[t],n);return Yh(s),{grad:s[0],value:r}}}function rD(e){return O(va(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{O(Array.isArray(t)&&t.every(r=>r instanceof Ye),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),O(n==null||n instanceof Ye,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let s=B.gradients(()=>e(...t),t,n);return n!=null&&zn(s.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Yh(s.grads),s}}function X3(e,t){O(va(e),()=>"The f passed in variableGrads(f) must be a function"),O(t==null||Array.isArray(t)&&t.every(c=>c instanceof sd),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let n=t!=null;if(!n){t=[];for(let c in B.registeredVariables)t.push(B.registeredVariables[c])}let s=n?t.filter(c=>!c.trainable):null,r=t.length;t=t.filter(c=>c.trainable),O(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${r} variables is trainable.`);let a=!0,{value:o,grads:i}=B.gradients(e,t,null,a);O(i.some(c=>c!=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()."),O(o.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${o.rank} tensor`);let l={};return t.forEach((c,u)=>{i[u]!=null&&(l[c.name]=i[u])}),s!=null&&s.forEach(c=>l[c.name]=null),{value:o,grads:l}}function Er(e){return B.customGrad(e)}function Yh(e){if(e.filter(n=>n==null).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.`)}function aD(e){let n={x:D(e,"x","neg")};return B.runKernel(xi,n)}var Ot=V({neg_:aD});function oD(e){let n={x:D(e,"x","softplus")};return B.runKernel(pu,n)}var Cu=V({softplus_:oD});function iD(e){let t=D(e,"x","logSigmoid");return Er(s=>({value:Ot(Cu(Ot(s))),gradFunc:o=>W(o,hs(Ot(s)))}))(t)}var lD=V({logSigmoid_:iD});function uD(e,t=null,n=!1){let r={x:D(e,"x","max")},a={reductionIndices:t,keepDims:n};return B.runKernel(Va,r,a)}var rs=V({max_:uD});function cD(e,t){let n=D(e,"a","sub"),s=D(t,"b","sub");[n,s]=Ft(n,s);let r={a:n,b:s};return B.runKernel(uo,r)}var ye=V({sub_:cD});function dD(e,t=null,n=!1){let s=D(e,"x","sum");s.dtype==="bool"&&(s=de(s,"int32"));let r={x:s},a={axis:t,keepDims:n};return B.runKernel(oo,r,a)}var Ie=V({sum_:dD});function pD(e,t=-1){let n=D(e,"logits","logSoftmax");if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and axis was ${t}`);return Er((r,a)=>{let o=!0,i=rs(r,t,!0),l=ye(r,i),c=ye(de(l,"float32"),Ns(Ie(Ts(l),t,o)));return a([c]),{value:c,gradFunc:(d,p)=>{let[h]=p,f=!0,m=Ts(h);return ye(d,W(Ie(d,t,f),m))}}})(n)}var B2=V({logSoftmax_:pD});function W2(e,t){for(let n=0;ne[a]);return[n,r]}function Qi(e,t){let n=t.map(s=>1);return K3(e,n,t)}function hD(e,t,n){O(W2(t,n),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`)}function Y3(e,t){if(W2(e,t))return null;let n=[];for(let s=0;sn.push(s)),n}function V2(e){return e.map((t,n)=>[n,t]).sort((t,n)=>t[1]-n[1]).map(t=>t[0])}function fD(e,t){let n=[];for(let s=t-e;s`Error in maxPool: input must be rank 4 but got rank ${i.rank}.`),O(Nr(n,o),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`),r!=null&&O(mn(s),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${r} but got pad ${s}.`);let c={x:i},u={filterSize:t,strides:n,pad:s,dimRoundingMode:r},d=B.runKernel(Ga,c,u);return l?G(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Qh=V({maxPool_:vD});function wD(e,t=[1,1,1],n,s,r,a="NDHWC"){let o=D(e,"x","maxPool3d"),i=o,l=!1;o.rank===4&&(l=!0,i=G(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),O(i.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${i.rank}.`),O(a==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`),r!=null&&O(mn(s),()=>`Error in maxPool3d: pad must be an integer when using, dimRoundingMode ${r} but got pad ${s}.`);let c={x:i},u={filterSize:t,strides:n,pad:s,dimRoundingMode:r,dataFormat:a},d=B.runKernel(Gc,c,u);return l?G(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var G2=V({maxPool3d_:wD});function kD(e,t,n,s,r=!1){let o={x:D(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:n,pad:s,includeBatchInIndex:r},l=B.runKernel(bh,o,i);return{result:l[0],indexes:l[1]}}var Q3=V({maxPoolWithArgmax_:kD});function ID(e,t){let n=D(e,"a","maximum"),s=D(t,"b","maximum");[n,s]=Ft(n,s),n.dtype==="bool"&&(n=de(n,"int32"),s=de(s,"int32")),St(n.shape,s.shape);let r={a:n,b:s};return B.runKernel(Ua,r)}var Yr=V({maximum_:ID});function SD(e,t=null,n=!1){let r={x:D(e,"x","mean")},a={axis:t,keepDims:n};return B.runKernel(Ha,r,a)}var Wt=V({mean_:SD});function Ht(e,t="float32"){if(t==="complex64"){let s=Ht(e,"float32"),r=Ht(e,"float32");return yo(s,r)}let n=Qp(Ut(e),t);return B.makeTensor(n,e,t)}function gs(e,t="float32"){if(t==="complex64"){let s=gs(e,"float32"),r=Ht(e,"float32");return yo(s,r)}let n=Lg(Ut(e),t);return B.makeTensor(n,e,t)}function CD(e,t,{indexing:n="xy"}={}){if(n!=="xy"&&n!=="ij")throw new TypeError(`${n} is not a valid third argument to meshgrid`);if(e===void 0)return[];let s=D(e,"x","meshgrid",e instanceof Ye?e.dtype:"float32");if(t===void 0)return[s];let r=D(t,"y","meshgrid",t instanceof Ye?t.dtype:"float32"),a=Ut(s.shape),o=Ut(r.shape);return n==="xy"?(s=G(s,[1,-1]),r=G(r,[-1,1]),[He(gs([o,1],s.dtype),s),He(r,gs([1,a],r.dtype))]):(s=G(s,[-1,1]),r=G(r,[1,-1]),[He(s,gs([1,o],s.dtype)),He(gs([a,1],r.dtype),r)])}function TD(e,t=null,n=!1){let r={x:D(e,"x","min")},a={axis:t,keepDims:n};return B.runKernel(ja,r,a)}var ef=V({min_:TD});function ND(e,t){let n=D(e,"a","minimum"),s=D(t,"b","minimum");[n,s]=Ft(n,s),n.dtype==="bool"&&(n=de(n,"int32"),s=de(s,"int32")),St(n.shape,s.shape);let r={a:n,b:s};return B.runKernel(qa,r)}var hd=V({minimum_:ND});function ED(e,t,n){O(n==="reflect"||n==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`);let s=D(e,"x","mirrorPad");if(s.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");O(t.length===s.rank,()=>`Padding doesn't match input. Must be ${s.rank}. Got ${t.length}.`);let r=n==="reflect"?1:0;for(let i=0;i"Invalid number of paddings. Must be length of 2 each."),O(t[i][0]>=0&&t[i][0]<=s.shape[i]-r&&t[i][1]>=0&&t[i][1]<=s.shape[i]-r,()=>`Padding in dimension ${i} cannot be greater than or equal to ${s.shape[i]-r} or less than 0 for input of shape ${s.shape}`);let a={paddings:t,mode:n},o={x:s};return B.runKernel(Xa,o,a)}var ev=V({mirrorPad_:ED});function RD(e,t){let n=D(e,"a","mod"),s=D(t,"b","mod");[n,s]=Ft(n,s);let r={a:n,b:s};return B.runKernel(au,r)}var tv=V({mod_:RD});function $D(e){let t=D(e,"x","square"),n={};return B.runKernel("Square",{x:t},n)}var xt=V({square_:$D});function DD(e,t=null,n=!1){e=D(e,"x","moments");let s=Us(t,e.shape),r=Wt(e,s,n),a=r.shape;n||(a=Qi(r.shape,s));let o=xt(ye(de(e,"float32"),G(r,a))),i=Wt(o,s,n);return{mean:r,variance:i}}var tf=V({moments_:DD});function _D(e,t,n,s){let r=D(t,"data","multiRNNCell"),a=ad(n,"c","multiRNNCell"),o=ad(s,"h","multiRNNCell"),i=r,l=[];for(let d=0;d2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${o}`);n=n||Math.random();let l={logits:o===1?G(r,[1,-1]):r},c={numSamples:t,seed:n,normalized:s},u=B.runKernel(vh,l,c);return o===1?G(u,[u.size]):u}var nv=V({multinomial_:FD});function OD(e,t){let n=D(e,"a","notEqual","string_or_numeric"),s=D(t,"b","notEqual","string_or_numeric");[n,s]=Ft(n,s),St(n.shape,s.shape);let r={a:n,b:s};return B.runKernel(bi,r)}var Tu=V({notEqual_:OD});function MD(e){let n={x:D(e,"x","onesLike")};return B.runKernel(ki,n)}var Es=V({onesLike_:MD});function zD(e,t){let n=D(e,"v1","outerProduct"),s=D(t,"v2","outerProduct");O(n.rank===1&&s.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${s.rank}.`);let r=G(n,[-1,1]),a=G(s,[1,-1]);return He(r,a)}var LD=V({outerProduct_:zD});function BD(e,t,n=0){let s=D(e,"x","pad");if(s.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");let r={paddings:t,constantValue:n},a={x:s};return B.runKernel(Za,a,r)}var qs=V({pad_:BD});function WD(e,t,n=0){return O(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),qs(e,[t],n)}var VD=V({pad1d_:WD});function UD(e,t,n=0){return O(t.length===2&&t[0].length===2&&t[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),qs(e,t,n)}var GD=V({pad2d_:UD});function HD(e,t,n=0){return O(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."),qs(e,t,n)}var jD=V({pad3d_:HD});function qD(e,t,n=0){return O(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."),qs(e,t,n)}var XD=V({pad4d_:qD});function KD(e,t,n){let s=D(e,"x","spaceToBatchND");O(s.rank>=1+t.length,()=>`input rank ${s.rank} should be > than [blockShape] ${t.length}`),O(n.length===t.length,()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`),O(s.shape.reduce((o,i,l)=>l>0&&l<=t.length?o&&(i+n[l-1][0]+n[l-1][1])%t[l-1]==0:o,!0),()=>`input spatial dimensions ${s.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`);let r={x:s},a={blockShape:t,paddings:n};return B.runKernel(Pi,r,a)}var nf=V({spaceToBatchND_:KD});function ZD(e,t,n,s,r,a){r==null&&(r=[1,1]),a==null&&(a=1),s===0&&(s="valid");let o=D(e,"x","maxPool"),i=o,l=!1;o.rank===3&&(l=!0,i=G(o,[1,o.shape[0],o.shape[1],o.shape[2]])),O(Nr(a,r),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${a} and dilations '${r}'`);let c=S3(i.shape,t,a,r,s),u=[c.dilationHeight,c.dilationWidth],d;s==="same"?d=JD([c.filterHeight,c.filterWidth],u):d=[[0,0],[0,0]];let p=u[0]===1&&u[1]===1,[h,f]=YD([c.inHeight,c.inWidth],u,d),m=p?s:"valid",g=p?i:nf(i,u,h),y=(n==="avg"?()=>Hh(g,t,a,m):()=>Qh(g,t,a,m))(),x=p?y:jh(y,u,f);return l?G(x,[x.shape[1],x.shape[2],x.shape[3]]):x}function YD(e,t,n){let s=n.map(u=>u[0]),r=n.map(u=>u[1]),a=e.concat(s,r),o=t.map((u,d)=>(u-a[d]%u)%u),i=r.map((u,d)=>u+o[d]),l=t.map((u,d)=>[s[d],i[d]]),c=t.map((u,d)=>[0,o[d]]);return[l,c]}function JD(e,t){let s=e.map((o,i)=>o+(o-1)*(t[i]-1)).map(o=>o-1),r=s.map(o=>Math.floor(o/2)),a=s.map((o,i)=>o-r[i]);return s.map((o,i)=>[r[i],a[i]])}var QD=V({pool_:ZD});function e_(e,t){let n=D(e,"base","pow"),s=D(t,"exp","pow");[n,s]=Ft(n,s);let r={a:n,b:s};return B.runKernel(Ya,r)}var Io=V({pow_:e_});function t_(e,t){let n=D(e,"x","prelu"),s=D(t,"alpha","prelu"),r={x:n,alpha:s};return B.runKernel(Ja,r)}var sf=V({prelu_:t_});function n_(e,t=null,n=!1){let s=D(e,"x","prod");s.dtype==="bool"&&(s=de(s,"int32"));let r={x:s},a={axis:t,keepDims:n};return B.runKernel(Ci,r,a)}var H2=V({prod_:n_});function s_(e,t,n){let s=Ut(e),r=null;if(n==null||n==="float32")r=new Float32Array(s);else if(n==="int32")r=new Int32Array(s);else if(n==="bool")r=new Uint8Array(s);else throw new Error(`Unknown data type ${n}`);for(let a=0;a=1||a===0);let o=Math.sqrt(-2*Math.log(a)/a);e=this.mean+this.stdDev*s*o,t=this.mean+this.stdDev*r*o,(!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}},a_=class{constructor(e,t,n,s){this.alpha=e,this.beta=1/t,this.dtype=n;let r=s||Math.random();this.randu=j2.alea(r.toString()),this.randn=new q2(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,s,r,a;for(;;){do s=this.randn.nextValue(),a=1+this.c*s;while(a<=0);if(a*=a*a,e=s*s,t=1-.331*e*e,n=.5*e+this.d*(1-a+Math.log(a)),r=this.randu(),rthis.dtype==null||this.dtype==="float32",this.min=e,this.range=t-e,this.dtype=n,s==null&&(s=Math.random()),typeof s=="number"&&(s=s.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=j2.alea(s)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}};function i_(e,t,n=1,s="float32",r){if(n==null&&(n=1),s==null&&(s="float32"),s!=="float32"&&s!=="int32")throw new Error(`Unsupported data type ${s}`);let a=new a_(t,n,s,r),o=Le(e,s);for(let i=0;i`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),Rs(t,0)}var A_=V({reverse1d_:g_});function y_(e,t){let n=D(e,"x","reverse");return O(n.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`),Rs(n,t)}var x_=V({reverse2d_:y_});function b_(e,t){let n=D(e,"x","reverse");return O(n.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`),Rs(n,t)}var v_=V({reverse3d_:b_});function w_(e,t){let n=D(e,"x","reverse");return O(n.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`),Rs(n,t)}var k_=V({reverse4d_:w_});function I_(e){let n={x:D(e,"x","round")};return B.runKernel(Ei,n)}var K2=V({round_:I_});function S_(e){let n={x:D(e,"x","rsqrt","float32")};return B.runKernel(no,n)}var Z2=V({rsqrt_:S_});function Ee(e,t){if((Dn(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"&&Dn(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return xo(e,[],[],t)}function C_(e){let n={x:D(e,"x","selu")};return B.runKernel(cu,n)}var Y2=V({selu_:C_});function T_(e,t,n,s,r,a=[1,1],o="NHWC"){let i=D(e,"x","separableConv2d"),l=D(t,"depthwiseFilter","separableConv2d"),c=D(n,"pointwiseFilter","separableConv2d"),u=i,d=!1;if(i.rank===3&&(d=!0,u=G(i,[1,i.shape[0],i.shape[1],i.shape[2]])),o==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");O(u.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${u.rank}.`),O(l.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),O(c.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),O(c.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${c.shape[0]}.`),O(c.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${c.shape[1]}.`);let p=l.shape[2],h=l.shape[3];O(c.shape[2]===p*h,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${p*h}, but got ${c.shape[2]}.`);let f=cd(u,l,s,r,o,a),g=ko(f,c,1,"valid",o);return d?G(g,[g.shape[1],g.shape[2],g.shape[3]]):g}var av=V({separableConv2d_:T_});async function N_(e,t){let n=D(e,"x","setdiff1d"),s=D(t,"y","setdiff1d");O(n.dtype===s.dtype,()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${s.dtype}).`),O(n.rank===1,()=>`x should be 1D tensor, but got x (${n.shape}).`),O(s.rank===1,()=>`y should be 1D tensor, but got y (${s.shape}).`);let r=await n.data(),a=await s.data(),o=new Set(a),i=0;for(let u=0;u`slice1d expects a rank-1 tensor, but got a rank-${s.rank} tensor`),_e(s,[t],[n])}var rf=V({slice1d_:D_});function __(e,t,n){let s=D(e,"x","slice2d");return O(s.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${s.rank} tensor`),_e(s,t,n)}var e1=V({slice2d_:__});function P_(e,t,n){let s=D(e,"x","slice3d");return O(s.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${s.rank} tensor`),_e(s,t,n)}var Ru=V({slice3d_:P_});function F_(e,t,n){let s=D(e,"x","slice4d");return O(s.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${s.rank} tensor`),_e(s,t,n)}var md=V({slice4d_:F_});function O_(e,t=-1){let n=D(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}`);let s={logits:n},r={dim:t};return B.runKernel(io,s,r)}var $u=V({softmax_:O_});function M_(e){O(e.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);let t={input:e};return B.runKernel(fh,t)}var af=V({fft_:M_});function z_(e){O(e.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);let t={input:e};return B.runKernel(mh,t)}var gd=V({ifft_:z_});function L_(e){let t=e.shape[e.shape.length-1],n=e.size/t,s;if(t<=2){let r=G(e,[n,t]);s=gd(r)}else{let r=[n,2*(t-1)],a=G(fd(e),[n,t]),o=G(Xh(e),[n,t]),i=Rs(_e(a,[0,1],[n,t-2]),1),l=W(Rs(_e(o,[0,1],[n,t-2]),1),Ee(-1)),c=It([a,i],1),u=It([o,l],1),d=G(yo(c,u),[r[0],r[1]]);s=gd(d)}if(s=fd(s),e.rank===3&&e.shape[0]!==0){let r=s,a=e.shape[0];s=G(s,[a,s.shape[0]/a,s.shape[1]]),r.dispose()}return s}var t1=V({irfft_:L_});function B_(e,t,n=0){let r={x:D(e,"x","split")},a={numOrSizeSplits:t,axis:n};return B.runKernel(Fi,r,a)}var Sn=V({split_:B_});function W_(e,t){O(e.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${e.dtype}`);let n=e.shape[e.shape.length-1],s=e.size/n,r;if(t!=null&&t0),m=e.shape.map(g=>g);m[e.shape.length-1]=t,r=_e(e,f,m),n=t}else if(t!=null&&t>n){let f=e.shape.map(m=>m);f[e.shape.length-1]=t-n,r=It([e,Ht(f)],e.shape.length-1),n=t}else r=e;let a=tt(r),o=G(yo(r,a),[s,n]),i=af(o),l=Math.floor(n/2)+1,c=fd(i),u=Xh(i),d=Sn(c,[l,n-l],c.shape.length-1),p=Sn(u,[l,n-l],u.shape.length-1),h=r.shape.slice();return h[r.shape.length-1]=l,G(yo(d[0],p[0]),h)}var of=V({rfft_:W_});function V_(e){let n={x:D(e,"x","sqrt","float32")};return B.runKernel(ao,n)}var _n=V({sqrt_:V_});function U_(e,t){let n=D(e,"a","squaredDifference"),s=D(t,"b","squaredDifference");[n,s]=Ft(n,s),St(n.shape,s.shape);let r={a:n,b:s},a={};return B.runKernel(lo,r,a)}var n1=V({squaredDifference_:U_});function G_(e,t){let n=D(e,"x","squeeze");return G(n,s5(n.shape,t).newShape)}var pt=V({squeeze_:G_});function H_(e,t=0){let n=ad(e,"tensors","stack","string_or_numeric");O(n.length>=1,()=>"Pass at least one tensor to tf.stack"),n.length>0&&O(t<=n[0].rank,()=>"Axis must be <= rank of the tensor");let s=n,r={axis:t};return B.runKernel(Si,s,r)}var Pn=V({stack_:H_});function j_(e,t=0){let s={x:D(e,"x","step")},r={alpha:t};return B.runKernel(ho,s,r)}var Ad=V({step_:j_});function q_(e,t,n,s,r=0,a=0,o=0,i=0,l=0){let u={x:D(e,"x","stridedSlice","string_or_numeric")},d={begin:t,end:n,strides:s,beginMask:r,endMask:a,ellipsisMask:o,newAxisMask:i,shrinkAxisMask:l};return B.runKernel(Oi,u,d)}var lv=V({stridedSlice_:q_});function X_(e){let n={x:D(e,"x","tan","float32")};return B.runKernel(Mi,n)}var uv=V({tan_:X_});function Zt(e,t){ei(e);let n=Cr(e,t);if(n.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return xo(e,null,n,t)}function ur(e,t,n){if(ei(e),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");let s=Cr(e,n);if(s.length!==2&&s.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return xo(e,t,s,n)}function K_(e,t,n){if(ei(e),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");let s=Cr(e,n);if(s.length!==4&&s.length!==1)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return xo(e,t,s,n)}function Z_(e,t,n){if(ei(e),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");let s=Cr(e,n);if(s.length!==5&&s.length!==1)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return xo(e,t,s,n)}function Y_(e,t,n){if(ei(e),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");let s=Cr(e,n);if(s.length!==6&&s.length!==1)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return t=t||s,xo(e,t,s,n)}function J_(e,t=1,n=!0){let s=D(e,"x","topk");if(s.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");let r=s.shape[s.shape.length-1];if(t<0)throw new Error(`'k' passed to topk() must be >= 0 but got ${t}`);if(t>r)throw new Error(`'k' passed to topk() must be <= the last dimension (${r}) but got ${t}`);let a={x:s},o={k:t,sorted:n},[i,l]=B.runKernel(zi,a,o);return{values:i,indices:l}}var cv=V({topk_:J_});function Q_(e,t=0,n=1,s,r){if(s!=null&&s==="bool")throw new Error("Unsupported data type $ { dtype }");let a=new q2(t,n,s,!0,r),o=Le(e,s);for(let i=0;i0,()=>"The input tensor must be at least 1D");let s={x:n},r={axis:t},[a,o]=B.runKernel(Rh,s,r);return{values:a,indices:o}}var s1=V({unique_:eP});function tP(e,t,n){let s=D(e,"x","unsortedSegmentSum"),r=D(t,"segmentIds","unsortedSegmentSum","int32");O(mn(n),()=>"numSegments must be of dtype int");let a={x:s,segmentIds:r},o={numSegments:n};return B.runKernel(Xc,a,o)}var dv=V({unsortedSegmentSum_:tP});function nP(e,t=0){let n=D(e,"x","unstack","string_or_numeric");O(t>=-n.shape.length&&t`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`);let s={value:n},r={axis:t};return B.runKernel(Bi,s,r)}var as=V({unstack_:nP});function pv(e,t=!0,n,s){return B.makeVariable(e,t,n,s)}function hv(e,t){let n=[];for(let a=0;a0,()=>"mask cannot be scalar"),zn(i.slice(a,a+o),r.shape,"mask's shape must match the first K dimensions of tensor's shape,");let l=1;for(let m=a;m"Shape mismatch in v and x");let l=Ee(1),c=ye(l,i),u=W(ye(o,a),c);if(r){O(s!=null,()=>"When using zeroDebias: true, step is required.");let d=D(s,"step","movingAverage");u=he(u,ye(l,Io(i,d)))}return ie(a,u)}var lP=V({movingAverage_:iP});function uP(e,t,n){let s=D(e,"indices","scatterND","int32"),r=D(t,"updates","scatterND");b2(r,s,n);let a={indices:s,updates:r},o={shape:n};return B.runKernel(Ri,a,o)}var mv=V({scatterND_:uP});function cP(e,t,n,s){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}.`);let r=e.rank>0?e.shape[0]:1,a=e.rank>1?e.shape[1]:1;if(n.length!==a)throw new Error(`outputShape has incorrect number of elements:, ${n.length}, should be: ${a}.`);let o=t.size;if(!(t.rank===0||t.rank===1&&o===r))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${r}]`);if(t.dtype!==s.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}function dP(e,t,n,s=0){let r=D(e,"sparseIndices","sparseToDense","int32"),a=D(t,"sparseValues","sparseToDense"),o=D(s,"defaultValue","sparseToDense",a.dtype);cP(r,a,n,o);let i={sparseIndices:r,sparseValues:a,defaultValue:o},l={outputShape:n};return B.runKernel(jc,i,l)}var o1=V({sparseToDense_:dP});function pP(e,t){let n=D(t,"indices","gatherND","int32"),r={params:D(e,"x","gatherND","string_or_numeric"),indices:n};return B.runKernel(hi,r)}var gv=V({gatherND_:pP});function hP(e,t){if(t==null)return e.shape.slice();if(Gr(e.shape,t))return t;if(e.shape.length===t.length){let n=[];for(let s=0;s`x has to be a floating point tensor since it's going to be scaled, but got a ${r.dtype} tensor instead.`),O(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),t===0)return e instanceof Ye?r.clone():r;let a=hP(r,n),o=1-t,i=he(pd(ie(Nu(a,0,1,"float32",s),o)),o);return W(r,i)}var Av=V({dropout_:fP});function yv(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function i1(e,t,n){let s=1-e%2,r=new Float32Array(e);for(let a=0;a1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${s.rank}`),O(s.rank-1===r.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${s.rank} and targets rank ${r.rank}`),zn(s.shape.slice(0,s.shape.length-1),r.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");let a=s.shape[s.shape.length-1];O(n>0&&n<=a,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${a}), but got ${n}`);let o=await s.data(),i=await r.data(),[l,c]=[o.length/a,a],u=r5("bool",l);for(let d=0;dg.value-m.value),u[d]=0;for(let m=0;mxP,depthwiseConv2d:()=>kP,matMul:()=>SP});function AP(e,t,n,s,r,a="NHWC",o){let i=e;e.rank===3&&(i=G(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=G(t,[1,t.shape[0],t.shape[1],t.shape[2]])),O(i.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${i.shape}.`),O(l.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),O(n.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`);let c=a==="NHWC"?i.shape[3]:i.shape[1],u=a==="NHWC"?l.shape[3]:l.shape[1];O(c===n[2],()=>`Error in conv2dDerFilter: depth of input ${c}) must match input depth in filter (${n[2]}.`),O(u===n[3],()=>`Error in conv2dDerFilter: depth of dy (${u}) must match output depth for filter (${n[3]}).`),o!=null&&O(mn(r),()=>`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);let d={x:i,dy:l},p={strides:s,pad:r,dataFormat:a,dimRoundingMode:o,filterShape:n};return B.runKernel(rh,d,p)}var l1=V({conv2DBackpropFilter_:AP});function uf(e,t,n){if(n==null||n==="linear")return e;if(n==="relu")return W(e,Ad(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function cf(e,t){let n=t,s=an(e.shape,t.shape);return s.length>0&&(n=Ie(n,s)),G(n,e.shape)}function df(e,t,n,s){if(t==="linear")return e;if(t==="relu")return Rr(e);if(t==="elu")return dd(e);if(t==="relu6")return X2(e);if(t==="prelu")return sf(e,n);if(t==="leakyrelu")return Kh(e,s);if(t==="sigmoid")return hs(e);throw new Error(`Unknown fused activation ${t}.`)}var pf=(e,t)=>!(e>0)||t==="linear";function yP({x:e,filter:t,strides:n,pad:s,dataFormat:r="NHWC",dilations:a=[1,1],dimRoundingMode:o,bias:i,activation:l="linear",preluActivationWeights:c,leakyreluAlpha:u}){if(l=l||"linear",pf(B.state.gradientDepth,l)===!1){let w=ko(e,t,n,s,r,a,o);return i!=null&&(w=ie(w,i)),df(w,l,c,u)}let d=D(e,"x","conv2d","float32"),p=D(t,"filter","conv2d","float32"),h=d,f=!1;d.rank===3&&(f=!0,h=G(d,[1,d.shape[0],d.shape[1],d.shape[2]])),O(h.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${h.rank}.`),O(p.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${p.rank}.`),o!=null&&O(mn(s),()=>`Error in fused conv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${s}.`),O(h.shape[3]===p.shape[2],()=>`Error in conv2d: depth of input (${h.shape[3]}) must match input depth for filter ${p.shape[2]}.`),O(Nr(n,a),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),O(r==="NHWC",()=>`Error in conv2d: got dataFormat of ${r} but only NHWC is currently supported.`);let m=ld(h.shape,p.shape,n,a,s,o),g;i!=null&&(g=D(i,"bias","fused conv2d"),[g]=Ft(g,d),St(m.outShape,g.shape));let A;c!=null&&(A=D(c,"prelu weights","fused conv2d"));let y=(w,k)=>{let[S,E,P,F]=k,R=uf(w,P,l);O(wo(a),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`);let _=_2(E.shape,R,S,n,s),T=l1(E,R,S.shape,n,s),M=[_,T];if(F!=null){let U=cf(F,R);M.push(U)}return M},x={x:h,filter:p,bias:g,preluActivationWeights:A},b={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:o,activation:l,leakyreluAlpha:u};return i==null?Er((k,S,E)=>{let P=B.runKernel(mo,x,b);return E([S,k,P]),f&&(P=G(P,[P.shape[1],P.shape[2],P.shape[3]])),{value:P,gradFunc:y}})(h,p):Er((k,S,E,P)=>{let F=B.runKernel(mo,x,b);return P([S,k,F,E]),f&&(F=G(F,[F.shape[1],F.shape[2],F.shape[3]])),{value:F,gradFunc:y}})(h,p,g)}var xP=V({fusedConv2d_:yP});function bP(e,t,n,s,r,a=[1,1],o){let i=e;e.rank===3&&(i=G(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=G(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let c={x:i,dy:l},u={strides:s,pad:r,dimRoundingMode:o,dilations:a,filterShape:n};return B.runKernel(lh,c,u)}var xv=V({depthwiseConv2dNativeBackpropFilter_:bP});function vP(e,t,n,s,r,a=[1,1],o){let i=t,l=!1;t.rank===3&&(l=!0,i=G(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let c={dy:i,filter:n},u={strides:s,pad:r,dimRoundingMode:o,dilations:a,inputShape:e},d=B.runKernel(uh,c,u);return l?G(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var bv=V({depthwiseConv2dNativeBackpropInput_:vP});function wP({x:e,filter:t,strides:n,pad:s,dataFormat:r="NHWC",dilations:a=[1,1],dimRoundingMode:o,bias:i,activation:l="linear",preluActivationWeights:c,leakyreluAlpha:u}){if(pf(B.state.gradientDepth,l)===!1){let w=cd(e,t,n,s,r,a,o);return i!=null&&(w=ie(w,i)),df(w,l,c,u)}let d=D(e,"x","depthwiseConv2d","float32"),p=D(t,"filter","depthwiseConv2d","float32"),h=d,f=!1;d.rank===3&&(f=!0,h=G(d,[1,d.shape[0],d.shape[1],d.shape[2]])),O(h.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${h.rank}.`),O(p.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${p.rank}.`),O(h.shape[3]===p.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${h.shape[3]}) must match the inChannels dimension in filter ${p.shape[2]}.`),a==null&&(a=[1,1]),O(Nr(n,a),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),o!=null&&O(mn(s),()=>`Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode ${o} but got pad ${s}.`);let m=ld(h.shape,p.shape,n,a,s,o,!0),g;i!=null&&(g=D(i,"bias","fused conv2d"),[g]=Ft(g,d),St(m.outShape,g.shape));let A;c!=null&&(A=D(c,"prelu weights","fused depthwiseConv2d"));let y=(w,k)=>{O(wo(a),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${a}'`);let[S,E,P,F]=k,R=uf(w,P,l),_=bv(E.shape,R,S,n,s,a,o),T=xv(E,R,S.shape,n,s,a,o);if(F!=null){let M=cf(g,R);return[_,T,M]}return[_,T]},x={x:h,filter:p,bias:g,preluActivationWeights:A},b={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:o,activation:l,leakyreluAlpha:u};return i==null?Er((k,S,E)=>{let P=B.runKernel(go,x,b);return E([S,k,P]),f&&(P=G(P,[P.shape[1],P.shape[2],P.shape[3]])),{value:P,gradFunc:y}})(h,p):Er((k,S,E,P)=>{let F=B.runKernel(go,x,b);return P([S,k,F,E]),f&&(F=G(F,[F.shape[1],F.shape[2],F.shape[3]])),{value:F,gradFunc:y}})(h,p,g)}var kP=V({fusedDepthwiseConv2d_:wP});function IP({a:e,b:t,transposeA:n=!1,transposeB:s=!1,bias:r,activation:a="linear",preluActivationWeights:o,leakyreluAlpha:i}){if(pf(B.state.gradientDepth,a)===!1){let F=He(e,t,n,s);return r!=null&&(F=ie(F,r)),df(F,a,o,i)}let l=D(e,"a","fused matMul"),c=D(t,"b","fused matMul");[l,c]=Ft(l,c);let u=n?l.shape[l.rank-2]:l.shape[l.rank-1],d=s?c.shape[c.rank-1]:c.shape[c.rank-2],p=n?l.shape[l.rank-1]:l.shape[l.rank-2],h=s?c.shape[c.rank-2]:c.shape[c.rank-1],f=l.shape.slice(0,-2),m=c.shape.slice(0,-2),g=Ut(f),A=Ut(m);O(l.rank>=2&&c.rank>=2&&l.rank===c.rank,()=>`Error in fused matMul: inputs must have the same rank of at least 2, got ranks ${l.rank} and ${c.rank}.`),O(Gr(f,m),()=>`Error in fused matMul: outer dimensions (${f}) and (${m}) of Tensors with shapes ${l.shape} and ${c.shape} must match.`),O(u===d,()=>`Error in fused matMul: inner shapes (${u}) and (${d}) of Tensors with shapes ${l.shape} and ${c.shape} and transposeA=${n} and transposeB=${s} must match.`);let y=l.shape.slice(0,-2).concat([p,h]),x=n?G(l,[g,u,p]):G(l,[g,p,u]),b=s?G(c,[A,h,d]):G(c,[A,d,h]),w;r!=null&&(w=D(r,"bias","fused matMul"),[w]=Ft(w,l),St(y,w.shape));let k;o!=null&&(k=D(o,"prelu weights","fused matMul"));let S=(F,R)=>{let[_,T,M,U]=R,H=uf(G(F,M.shape),M,a),z,X;if(!n&&!s?(z=He(H,T,!1,!0),X=He(_,H,!0,!1)):!n&&s?(z=He(H,T,!1,!1),X=He(H,_,!0,!1)):n&&!s?(z=He(T,H,!1,!0),X=He(_,H,!1,!1)):(z=He(T,H,!0,!0),X=He(H,_,!0,!0)),r!=null){let ee=cf(U,H);return[z,X,ee]}else return[z,X]},E={a:x,b,bias:w,preluActivationWeights:k},P={transposeA:n,transposeB:s,activation:a,leakyreluAlpha:i};return r==null?Er((R,_,T)=>{let M=B.runKernel(fo,E,P);return T([R,_,M]),{value:G(M,y),gradFunc:S}})(x,b):Er((R,_,T,M)=>{let U=B.runKernel(fo,E,P);return M([R,_,U,T]),{value:G(U,y),gradFunc:S}})(x,b,w)}var SP=V({fusedMatMul_:IP});function CP(e){return i1(e,.54,.46)}var TP=V({hammingWindow_:CP});function NP(e){return i1(e,.5,.5)}var vv=V({hannWindow_:NP});function EP(e,t,n,s=!1,r=0){let a=0,o=[];for(;a+t<=e.size;)o.push(_e(e,a,t)),a+=n;if(s)for(;a`Error in cropAndResize: image must be rank 4,but got rank ${o.rank}.`),O(i.rank===2&&i.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${c},4] but had shape ${i.shape}.`),O(l.rank===1&&l.shape[0]===c,()=>`Error in cropAndResize: boxInd must be have size [${c}] but had shape ${i.shape}.`),O(s.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${s.length}.`),O(s[0]>=1&&s[1]>=1,()=>`cropSize must be atleast [1,1], but was ${s}`),O(r==="bilinear"||r==="nearest",()=>`method must be bilinear or nearest, but was ${r}`);let u={image:o,boxes:i,boxInd:l},d={method:r,extrapolationValue:a,cropSize:s};return B.runKernel(oi,u,d)}var _P=V({cropAndResize_:DP});function PP(e){let t=D(e,"image","flipLeftRight","float32");O(t.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);let n={image:t};return B.runKernel(di,n,{})}var FP=V({flipLeftRight_:PP});function OP(e){let t=D(e,"image","grayscaleToRGB"),n=t.rank-1,s=t.shape[n];O(t.rank>=2,()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`),O(s===1,()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${s}.`);let r=new Array(t.rank);return r.fill(1,0,n),r[n]=3,js(t,r)}var MP=V({grayscaleToRGB_:OP});function zP(e,t,n=0,s=.5){let r=D(e,"image","rotateWithOffset","float32");O(r.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${r.rank}.`);let a={image:r},o={radians:t,fillValue:n,center:s};return B.runKernel(Vi,a,o)}var LP=V({rotateWithOffset_:zP});function Du(e,t,n,s,r,a){s==null&&(s=.5),r==null&&(r=Number.NEGATIVE_INFINITY),a==null&&(a=0);let o=e.shape[0];return n=Math.min(n,o),O(0<=s&&s<=1,()=>`iouThreshold must be in [0, 1], but was '${s}'`),O(e.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`),O(e.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`),O(t.rank===1,()=>"scores must be a 1D tensor"),O(t.shape[0]===o,()=>`scores has incompatible shape with boxes. Expected ${o}, but was ${t.shape[0]}`),O(0<=a&&a<=1,()=>`softNmsSigma must be in [0, 1], but was '${a}'`),{maxOutputSize:n,iouThreshold:s,scoreThreshold:r,softNmsSigma:a}}function BP(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY){let a=D(e,"boxes","nonMaxSuppression","float32"),o=D(t,"scores","nonMaxSuppression","float32"),i=Du(a,o,n,s,r);n=i.maxOutputSize,s=i.iouThreshold,r=i.scoreThreshold;let l={maxOutputSize:n,iouThreshold:s,scoreThreshold:r};return B.runKernel(vi,{boxes:a,scores:o},l)}var WP=V({nonMaxSuppression_:BP});function VP(e,t,n){let s=UP(e,t,n),r=s<0?-(s+1):s;e.splice(r,0,t)}function UP(e,t,n){return HP(e,t,n||GP)}function GP(e,t){return e>t?1:e>>1);let i=n(t,e[a]);i>0?s=a+1:(r=a,o=!i)}return o?s:-s-1}function kv(e,t,n,s,r){return u1(e,t,n,s,r,0)}function Iv(e,t,n,s,r,a){return u1(e,t,n,s,r,0,!1,a,!0)}function Sv(e,t,n,s,r,a){return u1(e,t,n,s,r,a,!0)}function u1(e,t,n,s,r,a,o=!1,i=!1,l=!1){let c=[];for(let g=0;gr&&c.push({score:t[g],boxIndex:g,suppressBeginIndex:0});c.sort(Cv);let u=a>0?-.5/a:0,d=[],p=[];for(;d.length0;){let g=c.pop(),{score:A,boxIndex:y,suppressBeginIndex:x}=g;if(A=x;--w){let k=jP(e,y,d[w]);if(k>=s){b=!0;break}if(g.score=g.score*qP(s,u,k),g.score<=r)break}g.suppressBeginIndex=d.length,b||(g.score===A?(d.push(y),p.push(g.score)):g.score>r&&VP(c,g,Cv))}let h=d.length,f=n-h;i&&f>0&&(d.push(...new Array(f).fill(0)),p.push(...new Array(f).fill(0)));let m={selectedIndices:d};return o&&(m.selectedScores=p),l&&(m.validOutputs=h),m}function jP(e,t,n){let s=e.subarray(t*4,t*4+4),r=e.subarray(n*4,n*4+4),a=Math.min(s[0],s[2]),o=Math.min(s[1],s[3]),i=Math.max(s[0],s[2]),l=Math.max(s[1],s[3]),c=Math.min(r[0],r[2]),u=Math.min(r[1],r[3]),d=Math.max(r[0],r[2]),p=Math.max(r[1],r[3]),h=(i-a)*(l-o),f=(d-c)*(p-u);if(h<=0||f<=0)return 0;let m=Math.max(a,c),g=Math.max(o,u),A=Math.min(i,d),y=Math.min(l,p),x=Math.max(A-m,0)*Math.max(y-g,0);return x/(h+f-x)}function qP(e,t,n){let s=Math.exp(t*n*n);return n<=e?s:0}function Cv(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function XP(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY){let a=D(e,"boxes","nonMaxSuppressionAsync"),o=D(t,"scores","nonMaxSuppressionAsync"),i=Du(a,o,n,s,r);n=i.maxOutputSize,s=i.iouThreshold,r=i.scoreThreshold;let l=await Promise.all([a.data(),o.data()]),c=l[0],u=l[1],{selectedIndices:d}=kv(c,u,n,s,r);return a!==e&&a.dispose(),o!==t&&o.dispose(),Zt(d,"int32")}var KP=XP;function ZP(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=0){let o=D(e,"boxes","nonMaxSuppression"),i=D(t,"scores","nonMaxSuppression"),l=Du(o,i,n,s,r,a);n=l.maxOutputSize,s=l.iouThreshold,r=l.scoreThreshold,a=l.softNmsSigma;let c={boxes:o,scores:i},u={maxOutputSize:n,iouThreshold:s,scoreThreshold:r,softNmsSigma:a},d=B.runKernel(wi,c,u);return{selectedIndices:d[0],selectedScores:d[1]}}var YP=V({nonMaxSuppressionWithScore_:ZP});async function JP(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=0){let o=D(e,"boxes","nonMaxSuppressionAsync"),i=D(t,"scores","nonMaxSuppressionAsync"),l=Du(o,i,n,s,r,a);n=l.maxOutputSize,s=l.iouThreshold,r=l.scoreThreshold,a=l.softNmsSigma;let c=await Promise.all([o.data(),i.data()]),u=c[0],d=c[1],{selectedIndices:p,selectedScores:h}=Sv(u,d,n,s,r,a);return o!==e&&o.dispose(),i!==t&&i.dispose(),{selectedIndices:Zt(p,"int32"),selectedScores:Zt(h)}}var QP=JP;function eF(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=!1){let o=D(e,"boxes","nonMaxSuppression"),i=D(t,"scores","nonMaxSuppression"),l=Du(o,i,n,s,r,null),c=l.maxOutputSize,u=l.iouThreshold,d=l.scoreThreshold,p={boxes:o,scores:i},h={maxOutputSize:c,iouThreshold:u,scoreThreshold:d,padToMaxOutputSize:a},f=B.runKernel(ou,p,h);return{selectedIndices:f[0],validOutputs:f[1]}}var tF=V({nonMaxSuppressionPadded_:eF});async function nF(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=!1){let o=D(e,"boxes","nonMaxSuppressionAsync"),i=D(t,"scores","nonMaxSuppressionAsync"),l=Du(o,i,n,s,r,null),c=l.maxOutputSize,u=l.iouThreshold,d=l.scoreThreshold,[p,h]=await Promise.all([o.data(),i.data()]),{selectedIndices:f,validOutputs:m}=Iv(p,h,c,u,d,a);return o!==e&&o.dispose(),i!==t&&i.dispose(),{selectedIndices:Zt(f,"int32"),validOutputs:Ee(m,"int32")}}var sF=nF;function rF(e,t,n=!1,s=!1){let r=D(e,"images","resizeBilinear");O(r.rank===3||r.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${r.rank}.`),O(t.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`),O(s===!1||n===!1,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let a=r,o=!1;r.rank===3&&(o=!0,a=G(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,i={images:a},l={alignCorners:n,halfPixelCenters:s,size:t},c=B.runKernel(eo,i,l);return o?G(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var aF=V({resizeBilinear_:rF});function oF(e,t,n=!1,s=!1){let r=D(e,"images","resizeNearestNeighbor");O(r.rank===3||r.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${r.rank}.`),O(t.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),O(r.dtype==="float32"||r.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype"),O(s===!1||n===!1,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let a=r,o=!1;r.rank===3&&(o=!0,a=G(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,i={images:a},l={alignCorners:n,halfPixelCenters:s,size:t},c=B.runKernel(uu,i,l);return o?G(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var iF=V({resizeNearestNeighbor_:oF});function lF(e,t="binary",n=!1,s=.5){let r=D(e,"image","threshold"),a=.2989,o=.587,i=.114,l=r.shape[0]*r.shape[1],c=W(Zt([s]),255),u,d,p,h;if(O(r.rank===3,()=>`Error in threshold: image must be rank 3,but got rank ${r.rank}.`),O(r.shape[2]===3||r.shape[2]===1,()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${r.shape[2]}.`),O(r.dtype==="int32"||r.dtype==="float32",()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${r.dtype}.`),O(t==="otsu"||t==="binary",()=>`Method must be binary or otsu, but was ${t}`),r.shape[2]===3){[u,d,p]=Sn(r,[1,1,1],-1);let g=W(u,a),A=W(d,o),y=W(p,i);h=ie(ie(g,A),y)}else h=e;if(t==="otsu"){let g=$2(de(K2(h),"int32"),Gt([]),256);c=uF(g,l)}let f=n?Ji(h,c):ms(h,c);return de(W(f,255),"int32")}function uF(e,t){let n=Zt([-1]),s=Zt([0]),r=Zt([0]),a,o,i,l,c,u;for(let d=0;d`Error in transform: image must be rank 4,but got rank ${o.rank}.`),O(i.rank===2&&(i.shape[0]===o.shape[0]||i.shape[0]===1)&&i.shape[1]===8,()=>"Error in transform: Input transform should be batch x 8 or 1 x 8"),O(a==null||a.length===2,()=>`Error in transform: outputShape must be [height, width] or null, but got ${a}.`);let l={image:o,transforms:i},c={interpolation:n,fillMode:s,fillValue:r,outputShape:a};return B.runKernel(Li,l,c)}var pF=V({transform_:dF});function hF(e,t,n){O(t%1==0,()=>`bandPart(): numLower must be an integer, got ${t}.`),O(n%1==0,()=>`bandPart(): numUpper must be an integer, got ${n}.`);let s=D(e,"a","bandPart");O(s.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${s.rank}.`);let r=s.shape,[a,o]=s.shape.slice(-2);if(!(t<=a))throw new Error(`bandPart(): numLower (${t}) must not be greater than the number of rows (${a}).`);if(!(n<=o))throw new Error(`bandPart(): numUpper (${n}) must not be greater than the number of columns (${o}).`);t<0&&(t=a),n<0&&(n=o);let i=G(Eu(0,a,1,"int32"),[-1,1]),l=Eu(0,o,1,"int32"),c=ye(i,l),u=lr(Ji(c,Ee(+t,"int32")),Yi(c,Ee(-n,"int32"))),d=Ht([a,o],s.dtype);return G(Pn(as(G(s,[-1,a,o])).map(p=>Wn(u,p,d))),r)}var fF=V({bandPart_:hF});function mF(e){let t;if(Array.isArray(e)){t=!1,O(e!=null&&e.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");let r=e[0].shape[0];for(let a=1;a`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[a].shape[0]} vs. ${r})`)}else t=!0,e=Sn(e,e.shape[0],0).map(r=>pt(r,[0]));O(e.length<=e[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`);let n=[],s=e;for(let r=0;r{let a=s[r];if(r>0)for(let o=0;o=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`),e.rank===2)return Tv(e,t);{let n=e.shape.slice(0,e.shape.length-2).reduce((l,c)=>l*c),s=as(G(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),r=[],a=[];s.forEach(l=>{let[c,u]=Tv(l,t);r.push(c),a.push(u)});let o=G(Pn(r,0),e.shape),i=G(Pn(a,0),e.shape);return[o,i]}}function Tv(e,t=!1){return B.tidy(()=>{O(e.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`);let n=e.shape[0],s=e.shape[1],r=z2(n),a=or(e),o=ur([[1]],[1,1]),i=or(o),l=n>=s?s:n;for(let c=0;c{let h=_e(a,[c,c],[n-c,1]),f=a1(h),m=_e(a,[c,c],[1,1]),g=Wn(ms(m,0),ur([[-1]]),ur([[1]])),A=ye(m,W(g,f)),y=he(h,A);y.shape[0]===1?i=or(o):i=It([o,_e(y,[1,0],[y.shape[0]-1,y.shape[1]])],0);let x=Ot(he(He(g,A),f)),b=_e(a,[c,0],[n-c,s]),w=W(x,i),k=et(i);if(c===0)a=ye(b,He(w,He(k,b)));else{let P=ye(b,He(w,He(k,b)));a=It([_e(a,[0,0],[c,s]),P],0)}let S=et(w),E=_e(r,[0,c],[n,r.shape[1]-c]);if(c===0)r=ye(E,He(He(E,i),S));else{let P=ye(E,He(He(E,i),S));r=It([_e(r,[0,0],[n,c]),P],1)}return[i,a,r]}),Q([u,d,p])}return!t&&n>s&&(r=_e(r,[0,0],[n,s]),a=_e(a,[0,0],[s,s])),[r,a]})}var yF=V({qr_:AF}),Vn;(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"})(Vn||(Vn={}));function xF(e,t,n=Vn.SUM_BY_NONZERO_WEIGHTS){let s=D(e,"losses","computeWeightedLoss"),r=null;t!=null&&(r=D(t,"weights","computeWeightedLoss"));let a=r==null?s:W(s,r);if(n===Vn.NONE)return a;if(n===Vn.SUM)return Ie(a);if(n===Vn.MEAN){if(r==null)return Wt(a);{let o=s.size/r.size,i=he(Ie(a),Ie(r));return o>1?he(i,Ee(o)):i}}if(n===Vn.SUM_BY_NONZERO_WEIGHTS){if(r==null)return he(Ie(a),Ee(s.size));{let o=W(r,gs(s.shape)),i=de(Ie(Tu(o,Ee(0))),"float32");return he(Ie(a),i)}}throw Error(`Unknown reduction: ${n}`)}var Jr=V({computeWeightedLoss_:xF});function bF(e,t,n,s=Vn.SUM_BY_NONZERO_WEIGHTS){let r=D(e,"labels","absoluteDifference"),a=D(t,"predictions","absoluteDifference"),o=null;n!=null&&(o=D(n,"weights","absoluteDifference")),zn(r.shape,a.shape,"Error in absoluteDifference: ");let i=rn(ye(r,a));return Jr(i,o,s)}var vF=V({absoluteDifference_:bF});function wF(e,t,n,s,r=Vn.SUM_BY_NONZERO_WEIGHTS){let a=D(e,"labels","cosineDistance"),o=D(t,"predictions","cosineDistance"),i=null;s!=null&&(i=D(s,"weights","cosineDistance")),zn(a.shape,o.shape,"Error in cosineDistance: ");let l=Ee(1),c=ye(l,Ie(W(a,o),n,!0));return Jr(c,i,r)}var kF=V({cosineDistance_:wF});function IF(e,t,n,s=Vn.SUM_BY_NONZERO_WEIGHTS){let r=D(e,"labels","hingeLoss"),a=D(t,"predictions","hingeLoss"),o=null;n!=null&&(o=D(n,"weights","hingeLoss")),zn(r.shape,a.shape,"Error in hingeLoss: ");let i=Ee(1);r=ye(W(Ee(2),r),i);let l=Rr(ye(i,W(r,a)));return Jr(l,o,s)}var SF=V({hingeLoss_:IF});function CF(e,t,n,s=1,r=Vn.SUM_BY_NONZERO_WEIGHTS){let a=D(e,"labels","huberLoss"),o=D(t,"predictions","huberLoss"),i=null;n!=null&&(i=D(n,"weights","huberLoss")),zn(a.shape,o.shape,"Error in huberLoss: ");let l=Ee(s),c=rn(ye(o,a)),u=hd(c,l),d=ye(c,u),p=ie(W(Ee(.5),xt(u)),W(l,d));return Jr(p,i,r)}var TF=V({huberLoss_:CF});function NF(e,t,n,s=1e-7,r=Vn.SUM_BY_NONZERO_WEIGHTS){let a=D(e,"labels","logLoss"),o=D(t,"predictions","logLoss"),i=null;n!=null&&(i=D(n,"weights","logLoss")),zn(a.shape,o.shape,"Error in logLoss: ");let l=Ee(1),c=Ee(s),u=Ot(W(a,Ns(ie(o,c)))),d=W(ye(l,a),Ns(ie(ye(l,o),c))),p=ye(u,d);return Jr(p,i,r)}var EF=V({logLoss_:NF});function RF(e,t,n,s=Vn.SUM_BY_NONZERO_WEIGHTS){let r=D(e,"labels","meanSquaredError"),a=D(t,"predictions","meanSquaredError"),o=null;n!=null&&(o=D(n,"weights","meanSquaredError")),zn(r.shape,a.shape,"Error in meanSquaredError: ");let i=n1(r,a);return Jr(i,o,s)}var $F=V({meanSquaredError_:RF});function DF(e,t){let n=D(e,"labels","sigmoidCrossEntropyWithLogits"),s=D(t,"logits","sigmoidCrossEntropyWithLogits");zn(n.shape,s.shape,"Error in sigmoidCrossEntropyWithLogits: ");let r=Rr(s),a=W(s,n),o=Zh(Ts(Ot(rn(s))));return ie(ye(r,a),o)}function _F(e,t,n,s=0,r=Vn.SUM_BY_NONZERO_WEIGHTS){let a=D(e,"multiClassLabels","sigmoidCrossEntropy"),o=D(t,"logits","sigmoidCrossEntropy"),i=null;if(n!=null&&(i=D(n,"weights","sigmoidCrossEntropy")),zn(a.shape,o.shape,"Error in sigmoidCrossEntropy: "),s>0){let c=Ee(s),u=Ee(1),d=Ee(.5);a=ie(W(a,ye(u,c)),W(d,c))}let l=DF(a,o);return Jr(l,i,r)}var PF=V({sigmoidCrossEntropy_:_F});function FF(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}`);return Er((r,a,o)=>{let l=J3(a,[n],!0),c=ye(de(a,"float32"),l);o([r,c]);let u=Ot(W(c,r));return{value:Ie(u,[n]),gradFunc:(h,f)=>{let[m,g]=f,A=Qi(h.shape,[n]);return[W(G(h,A),ye(de(m,"float32"),Ts(g))),W(G(h,A),ye(Ts(g),de(m,"float32")))]}}})(e,t)}function OF(e,t,n,s=0,r=Vn.SUM_BY_NONZERO_WEIGHTS){let a=D(e,"onehotLabels","softmaxCrossEntropy"),o=D(t,"logits","softmaxCrossEntropy"),i=null;if(n!=null&&(i=D(n,"weights","softmaxCrossEntropy")),zn(a.shape,o.shape,"Error in softmaxCrossEntropy: "),s>0){let c=Ee(s),u=Ee(1),d=Ee(a.shape[1]);a=ie(W(a,ye(u,c)),he(c,d))}let l=FF(a,o);return Jr(l,i,r)}var MF=V({softmaxCrossEntropy_:OF});function zF(e,t,n,s){let r=D(e,"indices","sparseFillEmptyRows"),a=D(t,"values","sparseFillEmptyRows"),o=D(n,"denseShape","sparseFillEmptyRows"),i=D(s,"defaultValue","sparseFillEmptyRows",a.dtype);if(r.rank!==2)throw new Error(`Indices should be Tensor2D but received shape - ${r.shape}`);if(a.rank!==1)throw new Error(`Values should be Tensor1D but received shape ${a.shape}`);if(o.rank!==1)throw new Error(`Dense shape should be Tensor1D but received shape ${o.shape}`);if(i.rank!==0)throw new Error(`Default value should be a scalar but received shape ${i.shape}`);let l={indices:r,values:a,denseShape:o,defaultValue:i},c=B.runKernel(Ih,l);return{outputIndices:c[0],outputValues:c[1],emptyRowIndicator:c[2],reverseIndexMap:c[3]}}var LF=V({sparseFillEmptyRows_:zF});function BF(e,t,n){let s=D(e,"inputIndices","sparseReshape"),r=D(t,"inputShape","sparseReshape"),a=D(n,"newShape","sparseReshape");if(s.rank!==2)throw new Error(`Input indices should be Tensor2D but received shape - ${s.shape}`);if(r.rank!==1)throw new Error(`Input shape should be Tensor1D but received shape ${r.shape}`);if(a.rank!==1)throw new Error(`New shape should be Tensor1D but received shape ${a.shape}`);let o={inputIndices:s,inputShape:r,newShape:a},i=B.runKernel(Sh,o);return{outputIndices:i[0],outputShape:i[1]}}var WF=V({sparseReshape_:BF});function VF(e,t,n){let s=D(e,"data","sparseSegmentMean"),r=D(t,"indices","sparseSegmentMean"),a=D(n,"segmentIds","sparseSegmentMean");if(s.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.rank!==1)throw new Error(`Indices should be Tensor1D but received shape + ${s.shape}`),O(o%(t*t)==0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${o} for depthToSpace with input shape ${s.shape}`);let i={x:s},l={blockSize:t,dataFormat:n};return B.runKernel(ii,i,l)}var L3=V({depthToSpace_:x$});function b$(e,t,n,s,r="NHWC",a=[1,1],o){let i=_(e,"x","depthwiseConv2d","float32"),l=_(t,"filter","depthwiseConv2d","float32"),c=i,u=!1;i.rank===3&&(u=!0,c=G(i,[1,i.shape[0],i.shape[1],i.shape[2]])),O(c.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${c.rank}.`),O(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`),O(c.shape[3]===l.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${c.shape[3]}) must match the inChannels dimension in filter ${l.shape[2]}.`),o!=null&&O(mn(s),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${s}.`);let d={x:c,filter:l},p={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:o},h=B.runKernel(Da,d,p);return u?G(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var cd=V({depthwiseConv2d_:b$});function v$(e){let n={x:_(e,"x","diag")};return B.runKernel(ch,n)}var w$=V({diag_:v$});function k$(e,t,n,s,r=[1,1],a="NHWC"){let o=_(e,"x","dilation2d"),i=_(t,"filter","dilation2d");O(o.rank===3||o.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${o.rank}.`),O(i.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${i.rank}.`),O(a==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${a}`);let l=o,c=!1;o.rank===3&&(l=G(o,[1,o.shape[0],o.shape[1],o.shape[2]]),c=!0);let u={x:l,filter:i},d={strides:n,pad:s,dilations:r},p=B.runKernel(Lc,u,d);return c?G(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var B3=V({dilation2d_:k$});function I$(e,t){let n=e.length,s=[];for(let r=0;r1&&o===1&&s.unshift(a)}return s}function an(e,t){let n=[];for(let s=0;s1)&&n.unshift(a)}return n}function St(e,t){let n=[],s=Math.max(e.length,t.length);for(let r=0;r`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${s.rank}.`);let r=n.rank===1?n.size:n.shape[1],a=s.rank===1?s.size:s.shape[0];if(O(r===a,()=>`Error in dot: inner dimensions of inputs must match, but got ${r} and ${a}.`),n.rank===1&&s.rank===1){let o=G(n,[1,-1]),i=G(s,[-1,1]),l=He(o,i);return G(l,[])}else if(n.rank===1&&s.rank===2){let o=G(n,[1,-1]),i=G(s,[s.shape[0],s.shape[1]]),l=He(o,i);return G(l,[l.size])}else if(n.rank===2&&s.rank===1){let o=G(s,[-1,1]),i=He(n,o);return G(i,[i.size])}else{let o=G(s,[s.shape[0],s.shape[1]]);return He(n,o)}}var R$=V({dot_:E$});function $$(e,...t){let n=t.map((r,a)=>_(r,`tensors${a}`,"einsum")),s={equation:e};return B.runKernel(Bc,n,s)}var V3=V({einsum_:$$});function D$(e){let n={x:_(e,"x","elu","float32")};return B.runKernel(Pa,n)}var dd=V({elu_:D$});function _$(e){let t=_(e,"x","erf");O(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),t.dtype==="int32"&&(t=he(t,"float32"));let n={x:t};return B.runKernel(Jl,n)}var U3=V({erf_:_$});function P$(e){let n={x:_(e,"x","exp")};return B.runKernel(Fa,n)}var Ts=V({exp_:P$});function F$(e,t=0){let n=_(e,"x","expandDims","string_or_numeric");O(t<=n.rank,()=>"Axis must be <= rank of the tensor");let s={input:n},r={dim:t};return B.runKernel(ui,s,r)}var Kt=V({expandDims_:F$});function O$(e){let n={x:_(e,"x","expm1")};return B.runKernel(ci,n)}var G3=V({expm1_:O$});function M$(e,t){let n=_(e,"x","tile","string_or_numeric");O(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`);let s={x:n},r={reps:t};return B.runKernel(qr,s,r)}var js=V({tile_:M$});function z$(e,t,n,s="float32"){t==null&&(t=e);let r=Le([e,t],s),a=e<=t?e:t;for(let i=0;i`Error in localResponseNormalization: x must be rank 3 or 4 but got + rank ${a.rank}.`),O(mn(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let o=a,i=!1;a.rank===3&&(i=!0,o=G(a,[1,a.shape[0],a.shape[1],a.shape[2]]));let l={x:o},c={depthRadius:t,bias:n,alpha:s,beta:r},u=B.runKernel(Uc,l,c);return i?G(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var q3=V({localResponseNormalization_:J$});function Q$(e){let n={x:_(e,"x","log","float32")};return B.runKernel(Wa,n)}var Ns=V({log_:Q$});function eD(e){let n={x:_(e,"x","log1p")};return B.runKernel(su,n)}var Zh=V({log1p_:eD});function tD(e){return O(va(e),()=>"The f passed in grad(f) must be a function"),(t,n)=>{let s=_(t,"x","tf.grad","string_or_numeric"),r=n!=null?_(n,"dy","tf.grad"):null;return B.tidy(()=>{let{value:a,grads:o}=B.gradients(()=>e(s),[s],r);return r!=null&&zn(a.shape,r.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Yh(o),o[0]})}}function nD(e){return O(va(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{O(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");let s=ad(t,"args","tf.grads","string_or_numeric"),r=n!=null?_(n,"dy","tf.grads"):null;return B.tidy(()=>{let{value:a,grads:o}=B.gradients(()=>e(...s),s,r);return r!=null&&zn(a.shape,r.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Yh(o),o})}}function sD(e){return O(va(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{O(t instanceof Ye,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),O(n==null||n instanceof Ye,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:s,value:r}=B.gradients(()=>e(t),[t],n);return Yh(s),{grad:s[0],value:r}}}function rD(e){return O(va(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{O(Array.isArray(t)&&t.every(r=>r instanceof Ye),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),O(n==null||n instanceof Ye,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let s=B.gradients(()=>e(...t),t,n);return n!=null&&zn(s.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Yh(s.grads),s}}function X3(e,t){O(va(e),()=>"The f passed in variableGrads(f) must be a function"),O(t==null||Array.isArray(t)&&t.every(c=>c instanceof sd),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let n=t!=null;if(!n){t=[];for(let c in B.registeredVariables)t.push(B.registeredVariables[c])}let s=n?t.filter(c=>!c.trainable):null,r=t.length;t=t.filter(c=>c.trainable),O(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${r} variables is trainable.`);let a=!0,{value:o,grads:i}=B.gradients(e,t,null,a);O(i.some(c=>c!=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()."),O(o.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${o.rank} tensor`);let l={};return t.forEach((c,u)=>{i[u]!=null&&(l[c.name]=i[u])}),s!=null&&s.forEach(c=>l[c.name]=null),{value:o,grads:l}}function Er(e){return B.customGrad(e)}function Yh(e){if(e.filter(n=>n==null).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.`)}function aD(e){let n={x:_(e,"x","neg")};return B.runKernel(xi,n)}var Ot=V({neg_:aD});function oD(e){let n={x:_(e,"x","softplus")};return B.runKernel(pu,n)}var Cu=V({softplus_:oD});function iD(e){let t=_(e,"x","logSigmoid");return Er(s=>({value:Ot(Cu(Ot(s))),gradFunc:o=>W(o,hs(Ot(s)))}))(t)}var lD=V({logSigmoid_:iD});function uD(e,t=null,n=!1){let r={x:_(e,"x","max")},a={reductionIndices:t,keepDims:n};return B.runKernel(Va,r,a)}var rs=V({max_:uD});function cD(e,t){let n=_(e,"a","sub"),s=_(t,"b","sub");[n,s]=Ft(n,s);let r={a:n,b:s};return B.runKernel(uo,r)}var xe=V({sub_:cD});function dD(e,t=null,n=!1){let s=_(e,"x","sum");s.dtype==="bool"&&(s=he(s,"int32"));let r={x:s},a={axis:t,keepDims:n};return B.runKernel(oo,r,a)}var Ie=V({sum_:dD});function pD(e,t=-1){let n=_(e,"logits","logSoftmax");if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and axis was ${t}`);return Er((r,a)=>{let o=!0,i=rs(r,t,!0),l=xe(r,i),c=xe(he(l,"float32"),Ns(Ie(Ts(l),t,o)));return a([c]),{value:c,gradFunc:(d,p)=>{let[h]=p,f=!0,m=Ts(h);return xe(d,W(Ie(d,t,f),m))}}})(n)}var B2=V({logSoftmax_:pD});function W2(e,t){for(let n=0;ne[a]);return[n,r]}function Qi(e,t){let n=t.map(s=>1);return K3(e,n,t)}function hD(e,t,n){O(W2(t,n),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`)}function Y3(e,t){if(W2(e,t))return null;let n=[];for(let s=0;sn.push(s)),n}function V2(e){return e.map((t,n)=>[n,t]).sort((t,n)=>t[1]-n[1]).map(t=>t[0])}function fD(e,t){let n=[];for(let s=t-e;s`Error in maxPool: input must be rank 4 but got rank ${i.rank}.`),O(Nr(n,o),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`),r!=null&&O(mn(s),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${r} but got pad ${s}.`);let c={x:i},u={filterSize:t,strides:n,pad:s,dimRoundingMode:r},d=B.runKernel(Ga,c,u);return l?G(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Qh=V({maxPool_:vD});function wD(e,t=[1,1,1],n,s,r,a="NDHWC"){let o=_(e,"x","maxPool3d"),i=o,l=!1;o.rank===4&&(l=!0,i=G(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),O(i.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${i.rank}.`),O(a==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`),r!=null&&O(mn(s),()=>`Error in maxPool3d: pad must be an integer when using, dimRoundingMode ${r} but got pad ${s}.`);let c={x:i},u={filterSize:t,strides:n,pad:s,dimRoundingMode:r,dataFormat:a},d=B.runKernel(Gc,c,u);return l?G(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var G2=V({maxPool3d_:wD});function kD(e,t,n,s,r=!1){let o={x:_(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:n,pad:s,includeBatchInIndex:r},l=B.runKernel(bh,o,i);return{result:l[0],indexes:l[1]}}var Q3=V({maxPoolWithArgmax_:kD});function ID(e,t){let n=_(e,"a","maximum"),s=_(t,"b","maximum");[n,s]=Ft(n,s),n.dtype==="bool"&&(n=he(n,"int32"),s=he(s,"int32")),St(n.shape,s.shape);let r={a:n,b:s};return B.runKernel(Ua,r)}var Yr=V({maximum_:ID});function SD(e,t=null,n=!1){let r={x:_(e,"x","mean")},a={axis:t,keepDims:n};return B.runKernel(Ha,r,a)}var Wt=V({mean_:SD});function Ht(e,t="float32"){if(t==="complex64"){let s=Ht(e,"float32"),r=Ht(e,"float32");return yo(s,r)}let n=Qp(Ut(e),t);return B.makeTensor(n,e,t)}function gs(e,t="float32"){if(t==="complex64"){let s=gs(e,"float32"),r=Ht(e,"float32");return yo(s,r)}let n=Lg(Ut(e),t);return B.makeTensor(n,e,t)}function CD(e,t,{indexing:n="xy"}={}){if(n!=="xy"&&n!=="ij")throw new TypeError(`${n} is not a valid third argument to meshgrid`);if(e===void 0)return[];let s=_(e,"x","meshgrid",e instanceof Ye?e.dtype:"float32");if(t===void 0)return[s];let r=_(t,"y","meshgrid",t instanceof Ye?t.dtype:"float32"),a=Ut(s.shape),o=Ut(r.shape);return n==="xy"?(s=G(s,[1,-1]),r=G(r,[-1,1]),[He(gs([o,1],s.dtype),s),He(r,gs([1,a],r.dtype))]):(s=G(s,[-1,1]),r=G(r,[1,-1]),[He(s,gs([1,o],s.dtype)),He(gs([a,1],r.dtype),r)])}function TD(e,t=null,n=!1){let r={x:_(e,"x","min")},a={axis:t,keepDims:n};return B.runKernel(ja,r,a)}var ef=V({min_:TD});function ND(e,t){let n=_(e,"a","minimum"),s=_(t,"b","minimum");[n,s]=Ft(n,s),n.dtype==="bool"&&(n=he(n,"int32"),s=he(s,"int32")),St(n.shape,s.shape);let r={a:n,b:s};return B.runKernel(qa,r)}var hd=V({minimum_:ND});function ED(e,t,n){O(n==="reflect"||n==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`);let s=_(e,"x","mirrorPad");if(s.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");O(t.length===s.rank,()=>`Padding doesn't match input. Must be ${s.rank}. Got ${t.length}.`);let r=n==="reflect"?1:0;for(let i=0;i"Invalid number of paddings. Must be length of 2 each."),O(t[i][0]>=0&&t[i][0]<=s.shape[i]-r&&t[i][1]>=0&&t[i][1]<=s.shape[i]-r,()=>`Padding in dimension ${i} cannot be greater than or equal to ${s.shape[i]-r} or less than 0 for input of shape ${s.shape}`);let a={paddings:t,mode:n},o={x:s};return B.runKernel(Xa,o,a)}var ev=V({mirrorPad_:ED});function RD(e,t){let n=_(e,"a","mod"),s=_(t,"b","mod");[n,s]=Ft(n,s);let r={a:n,b:s};return B.runKernel(au,r)}var tv=V({mod_:RD});function $D(e){let t=_(e,"x","square"),n={};return B.runKernel("Square",{x:t},n)}var xt=V({square_:$D});function DD(e,t=null,n=!1){e=_(e,"x","moments");let s=Us(t,e.shape),r=Wt(e,s,n),a=r.shape;n||(a=Qi(r.shape,s));let o=xt(xe(he(e,"float32"),G(r,a))),i=Wt(o,s,n);return{mean:r,variance:i}}var tf=V({moments_:DD});function _D(e,t,n,s){let r=_(t,"data","multiRNNCell"),a=ad(n,"c","multiRNNCell"),o=ad(s,"h","multiRNNCell"),i=r,l=[];for(let d=0;d2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${o}`);n=n||Math.random();let l={logits:o===1?G(r,[1,-1]):r},c={numSamples:t,seed:n,normalized:s},u=B.runKernel(vh,l,c);return o===1?G(u,[u.size]):u}var nv=V({multinomial_:FD});function OD(e,t){let n=_(e,"a","notEqual","string_or_numeric"),s=_(t,"b","notEqual","string_or_numeric");[n,s]=Ft(n,s),St(n.shape,s.shape);let r={a:n,b:s};return B.runKernel(bi,r)}var Tu=V({notEqual_:OD});function MD(e){let n={x:_(e,"x","onesLike")};return B.runKernel(ki,n)}var Es=V({onesLike_:MD});function zD(e,t){let n=_(e,"v1","outerProduct"),s=_(t,"v2","outerProduct");O(n.rank===1&&s.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${s.rank}.`);let r=G(n,[-1,1]),a=G(s,[1,-1]);return He(r,a)}var LD=V({outerProduct_:zD});function BD(e,t,n=0){let s=_(e,"x","pad");if(s.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");let r={paddings:t,constantValue:n},a={x:s};return B.runKernel(Za,a,r)}var qs=V({pad_:BD});function WD(e,t,n=0){return O(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),qs(e,[t],n)}var VD=V({pad1d_:WD});function UD(e,t,n=0){return O(t.length===2&&t[0].length===2&&t[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),qs(e,t,n)}var GD=V({pad2d_:UD});function HD(e,t,n=0){return O(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."),qs(e,t,n)}var jD=V({pad3d_:HD});function qD(e,t,n=0){return O(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."),qs(e,t,n)}var XD=V({pad4d_:qD});function KD(e,t,n){let s=_(e,"x","spaceToBatchND");O(s.rank>=1+t.length,()=>`input rank ${s.rank} should be > than [blockShape] ${t.length}`),O(n.length===t.length,()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`),O(s.shape.reduce((o,i,l)=>l>0&&l<=t.length?o&&(i+n[l-1][0]+n[l-1][1])%t[l-1]==0:o,!0),()=>`input spatial dimensions ${s.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`);let r={x:s},a={blockShape:t,paddings:n};return B.runKernel(Pi,r,a)}var nf=V({spaceToBatchND_:KD});function ZD(e,t,n,s,r,a){r==null&&(r=[1,1]),a==null&&(a=1),s===0&&(s="valid");let o=_(e,"x","maxPool"),i=o,l=!1;o.rank===3&&(l=!0,i=G(o,[1,o.shape[0],o.shape[1],o.shape[2]])),O(Nr(a,r),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${a} and dilations '${r}'`);let c=S3(i.shape,t,a,r,s),u=[c.dilationHeight,c.dilationWidth],d;s==="same"?d=JD([c.filterHeight,c.filterWidth],u):d=[[0,0],[0,0]];let p=u[0]===1&&u[1]===1,[h,f]=YD([c.inHeight,c.inWidth],u,d),m=p?s:"valid",g=p?i:nf(i,u,h),y=(n==="avg"?()=>Hh(g,t,a,m):()=>Qh(g,t,a,m))(),x=p?y:jh(y,u,f);return l?G(x,[x.shape[1],x.shape[2],x.shape[3]]):x}function YD(e,t,n){let s=n.map(u=>u[0]),r=n.map(u=>u[1]),a=e.concat(s,r),o=t.map((u,d)=>(u-a[d]%u)%u),i=r.map((u,d)=>u+o[d]),l=t.map((u,d)=>[s[d],i[d]]),c=t.map((u,d)=>[0,o[d]]);return[l,c]}function JD(e,t){let s=e.map((o,i)=>o+(o-1)*(t[i]-1)).map(o=>o-1),r=s.map(o=>Math.floor(o/2)),a=s.map((o,i)=>o-r[i]);return s.map((o,i)=>[r[i],a[i]])}var QD=V({pool_:ZD});function e_(e,t){let n=_(e,"base","pow"),s=_(t,"exp","pow");[n,s]=Ft(n,s);let r={a:n,b:s};return B.runKernel(Ya,r)}var Io=V({pow_:e_});function t_(e,t){let n=_(e,"x","prelu"),s=_(t,"alpha","prelu"),r={x:n,alpha:s};return B.runKernel(Ja,r)}var sf=V({prelu_:t_});function n_(e,t=null,n=!1){let s=_(e,"x","prod");s.dtype==="bool"&&(s=he(s,"int32"));let r={x:s},a={axis:t,keepDims:n};return B.runKernel(Ci,r,a)}var H2=V({prod_:n_});function s_(e,t,n){let s=Ut(e),r=null;if(n==null||n==="float32")r=new Float32Array(s);else if(n==="int32")r=new Int32Array(s);else if(n==="bool")r=new Uint8Array(s);else throw new Error(`Unknown data type ${n}`);for(let a=0;a=1||a===0);let o=Math.sqrt(-2*Math.log(a)/a);e=this.mean+this.stdDev*s*o,t=this.mean+this.stdDev*r*o,(!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}},a_=class{constructor(e,t,n,s){this.alpha=e,this.beta=1/t,this.dtype=n;let r=s||Math.random();this.randu=j2.alea(r.toString()),this.randn=new q2(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,s,r,a;for(;;){do s=this.randn.nextValue(),a=1+this.c*s;while(a<=0);if(a*=a*a,e=s*s,t=1-.331*e*e,n=.5*e+this.d*(1-a+Math.log(a)),r=this.randu(),rthis.dtype==null||this.dtype==="float32",this.min=e,this.range=t-e,this.dtype=n,s==null&&(s=Math.random()),typeof s=="number"&&(s=s.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=j2.alea(s)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}};function i_(e,t,n=1,s="float32",r){if(n==null&&(n=1),s==null&&(s="float32"),s!=="float32"&&s!=="int32")throw new Error(`Unsupported data type ${s}`);let a=new a_(t,n,s,r),o=Le(e,s);for(let i=0;i`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),Rs(t,0)}var A_=V({reverse1d_:g_});function y_(e,t){let n=_(e,"x","reverse");return O(n.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`),Rs(n,t)}var x_=V({reverse2d_:y_});function b_(e,t){let n=_(e,"x","reverse");return O(n.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`),Rs(n,t)}var v_=V({reverse3d_:b_});function w_(e,t){let n=_(e,"x","reverse");return O(n.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`),Rs(n,t)}var k_=V({reverse4d_:w_});function I_(e){let n={x:_(e,"x","round")};return B.runKernel(Ei,n)}var K2=V({round_:I_});function S_(e){let n={x:_(e,"x","rsqrt","float32")};return B.runKernel(no,n)}var Z2=V({rsqrt_:S_});function Ee(e,t){if((Dn(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"&&Dn(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return xo(e,[],[],t)}function C_(e){let n={x:_(e,"x","selu")};return B.runKernel(cu,n)}var Y2=V({selu_:C_});function T_(e,t,n,s,r,a=[1,1],o="NHWC"){let i=_(e,"x","separableConv2d"),l=_(t,"depthwiseFilter","separableConv2d"),c=_(n,"pointwiseFilter","separableConv2d"),u=i,d=!1;if(i.rank===3&&(d=!0,u=G(i,[1,i.shape[0],i.shape[1],i.shape[2]])),o==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");O(u.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${u.rank}.`),O(l.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),O(c.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),O(c.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${c.shape[0]}.`),O(c.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${c.shape[1]}.`);let p=l.shape[2],h=l.shape[3];O(c.shape[2]===p*h,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${p*h}, but got ${c.shape[2]}.`);let f=cd(u,l,s,r,o,a),g=ko(f,c,1,"valid",o);return d?G(g,[g.shape[1],g.shape[2],g.shape[3]]):g}var av=V({separableConv2d_:T_});async function N_(e,t){let n=_(e,"x","setdiff1d"),s=_(t,"y","setdiff1d");O(n.dtype===s.dtype,()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${s.dtype}).`),O(n.rank===1,()=>`x should be 1D tensor, but got x (${n.shape}).`),O(s.rank===1,()=>`y should be 1D tensor, but got y (${s.shape}).`);let r=await n.data(),a=await s.data(),o=new Set(a),i=0;for(let u=0;u`slice1d expects a rank-1 tensor, but got a rank-${s.rank} tensor`),_e(s,[t],[n])}var rf=V({slice1d_:D_});function __(e,t,n){let s=_(e,"x","slice2d");return O(s.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${s.rank} tensor`),_e(s,t,n)}var e1=V({slice2d_:__});function P_(e,t,n){let s=_(e,"x","slice3d");return O(s.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${s.rank} tensor`),_e(s,t,n)}var Ru=V({slice3d_:P_});function F_(e,t,n){let s=_(e,"x","slice4d");return O(s.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${s.rank} tensor`),_e(s,t,n)}var md=V({slice4d_:F_});function O_(e,t=-1){let n=_(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}`);let s={logits:n},r={dim:t};return B.runKernel(io,s,r)}var $u=V({softmax_:O_});function M_(e){O(e.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);let t={input:e};return B.runKernel(fh,t)}var af=V({fft_:M_});function z_(e){O(e.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);let t={input:e};return B.runKernel(mh,t)}var gd=V({ifft_:z_});function L_(e){let t=e.shape[e.shape.length-1],n=e.size/t,s;if(t<=2){let r=G(e,[n,t]);s=gd(r)}else{let r=[n,2*(t-1)],a=G(fd(e),[n,t]),o=G(Xh(e),[n,t]),i=Rs(_e(a,[0,1],[n,t-2]),1),l=W(Rs(_e(o,[0,1],[n,t-2]),1),Ee(-1)),c=It([a,i],1),u=It([o,l],1),d=G(yo(c,u),[r[0],r[1]]);s=gd(d)}if(s=fd(s),e.rank===3&&e.shape[0]!==0){let r=s,a=e.shape[0];s=G(s,[a,s.shape[0]/a,s.shape[1]]),r.dispose()}return s}var t1=V({irfft_:L_});function B_(e,t,n=0){let r={x:_(e,"x","split")},a={numOrSizeSplits:t,axis:n};return B.runKernel(Fi,r,a)}var Sn=V({split_:B_});function W_(e,t){O(e.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${e.dtype}`);let n=e.shape[e.shape.length-1],s=e.size/n,r;if(t!=null&&t0),m=e.shape.map(g=>g);m[e.shape.length-1]=t,r=_e(e,f,m),n=t}else if(t!=null&&t>n){let f=e.shape.map(m=>m);f[e.shape.length-1]=t-n,r=It([e,Ht(f)],e.shape.length-1),n=t}else r=e;let a=tt(r),o=G(yo(r,a),[s,n]),i=af(o),l=Math.floor(n/2)+1,c=fd(i),u=Xh(i),d=Sn(c,[l,n-l],c.shape.length-1),p=Sn(u,[l,n-l],u.shape.length-1),h=r.shape.slice();return h[r.shape.length-1]=l,G(yo(d[0],p[0]),h)}var of=V({rfft_:W_});function V_(e){let n={x:_(e,"x","sqrt","float32")};return B.runKernel(ao,n)}var _n=V({sqrt_:V_});function U_(e,t){let n=_(e,"a","squaredDifference"),s=_(t,"b","squaredDifference");[n,s]=Ft(n,s),St(n.shape,s.shape);let r={a:n,b:s},a={};return B.runKernel(lo,r,a)}var n1=V({squaredDifference_:U_});function G_(e,t){let n=_(e,"x","squeeze");return G(n,s5(n.shape,t).newShape)}var pt=V({squeeze_:G_});function H_(e,t=0){let n=ad(e,"tensors","stack","string_or_numeric");O(n.length>=1,()=>"Pass at least one tensor to tf.stack"),n.length>0&&O(t<=n[0].rank,()=>"Axis must be <= rank of the tensor");let s=n,r={axis:t};return B.runKernel(Si,s,r)}var Pn=V({stack_:H_});function j_(e,t=0){let s={x:_(e,"x","step")},r={alpha:t};return B.runKernel(ho,s,r)}var Ad=V({step_:j_});function q_(e,t,n,s,r=0,a=0,o=0,i=0,l=0){let u={x:_(e,"x","stridedSlice","string_or_numeric")},d={begin:t,end:n,strides:s,beginMask:r,endMask:a,ellipsisMask:o,newAxisMask:i,shrinkAxisMask:l};return B.runKernel(Oi,u,d)}var lv=V({stridedSlice_:q_});function X_(e){let n={x:_(e,"x","tan","float32")};return B.runKernel(Mi,n)}var uv=V({tan_:X_});function Zt(e,t){ei(e);let n=Cr(e,t);if(n.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return xo(e,null,n,t)}function ur(e,t,n){if(ei(e),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");let s=Cr(e,n);if(s.length!==2&&s.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return xo(e,t,s,n)}function K_(e,t,n){if(ei(e),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");let s=Cr(e,n);if(s.length!==4&&s.length!==1)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return xo(e,t,s,n)}function Z_(e,t,n){if(ei(e),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");let s=Cr(e,n);if(s.length!==5&&s.length!==1)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return xo(e,t,s,n)}function Y_(e,t,n){if(ei(e),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");let s=Cr(e,n);if(s.length!==6&&s.length!==1)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return t=t||s,xo(e,t,s,n)}function J_(e,t=1,n=!0){let s=_(e,"x","topk");if(s.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");let r=s.shape[s.shape.length-1];if(t<0)throw new Error(`'k' passed to topk() must be >= 0 but got ${t}`);if(t>r)throw new Error(`'k' passed to topk() must be <= the last dimension (${r}) but got ${t}`);let a={x:s},o={k:t,sorted:n},[i,l]=B.runKernel(zi,a,o);return{values:i,indices:l}}var cv=V({topk_:J_});function Q_(e,t=0,n=1,s,r){if(s!=null&&s==="bool")throw new Error("Unsupported data type $ { dtype }");let a=new q2(t,n,s,!0,r),o=Le(e,s);for(let i=0;i0,()=>"The input tensor must be at least 1D");let s={x:n},r={axis:t},[a,o]=B.runKernel(Rh,s,r);return{values:a,indices:o}}var s1=V({unique_:eP});function tP(e,t,n){let s=_(e,"x","unsortedSegmentSum"),r=_(t,"segmentIds","unsortedSegmentSum","int32");O(mn(n),()=>"numSegments must be of dtype int");let a={x:s,segmentIds:r},o={numSegments:n};return B.runKernel(Xc,a,o)}var dv=V({unsortedSegmentSum_:tP});function nP(e,t=0){let n=_(e,"x","unstack","string_or_numeric");O(t>=-n.shape.length&&t`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`);let s={value:n},r={axis:t};return B.runKernel(Bi,s,r)}var as=V({unstack_:nP});function pv(e,t=!0,n,s){return B.makeVariable(e,t,n,s)}function hv(e,t){let n=[];for(let a=0;a0,()=>"mask cannot be scalar"),zn(i.slice(a,a+o),r.shape,"mask's shape must match the first K dimensions of tensor's shape,");let l=1;for(let m=a;m"Shape mismatch in v and x");let l=Ee(1),c=xe(l,i),u=W(xe(o,a),c);if(r){O(s!=null,()=>"When using zeroDebias: true, step is required.");let d=_(s,"step","movingAverage");u=fe(u,xe(l,Io(i,d)))}return ie(a,u)}var lP=V({movingAverage_:iP});function uP(e,t,n){let s=_(e,"indices","scatterND","int32"),r=_(t,"updates","scatterND");b2(r,s,n);let a={indices:s,updates:r},o={shape:n};return B.runKernel(Ri,a,o)}var mv=V({scatterND_:uP});function cP(e,t,n,s){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}.`);let r=e.rank>0?e.shape[0]:1,a=e.rank>1?e.shape[1]:1;if(n.length!==a)throw new Error(`outputShape has incorrect number of elements:, ${n.length}, should be: ${a}.`);let o=t.size;if(!(t.rank===0||t.rank===1&&o===r))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${r}]`);if(t.dtype!==s.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}function dP(e,t,n,s=0){let r=_(e,"sparseIndices","sparseToDense","int32"),a=_(t,"sparseValues","sparseToDense"),o=_(s,"defaultValue","sparseToDense",a.dtype);cP(r,a,n,o);let i={sparseIndices:r,sparseValues:a,defaultValue:o},l={outputShape:n};return B.runKernel(jc,i,l)}var o1=V({sparseToDense_:dP});function pP(e,t){let n=_(t,"indices","gatherND","int32"),r={params:_(e,"x","gatherND","string_or_numeric"),indices:n};return B.runKernel(hi,r)}var gv=V({gatherND_:pP});function hP(e,t){if(t==null)return e.shape.slice();if(Gr(e.shape,t))return t;if(e.shape.length===t.length){let n=[];for(let s=0;s`x has to be a floating point tensor since it's going to be scaled, but got a ${r.dtype} tensor instead.`),O(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),t===0)return e instanceof Ye?r.clone():r;let a=hP(r,n),o=1-t,i=fe(pd(ie(Nu(a,0,1,"float32",s),o)),o);return W(r,i)}var Av=V({dropout_:fP});function yv(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function i1(e,t,n){let s=1-e%2,r=new Float32Array(e);for(let a=0;a1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${s.rank}`),O(s.rank-1===r.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${s.rank} and targets rank ${r.rank}`),zn(s.shape.slice(0,s.shape.length-1),r.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");let a=s.shape[s.shape.length-1];O(n>0&&n<=a,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${a}), but got ${n}`);let o=await s.data(),i=await r.data(),[l,c]=[o.length/a,a],u=r5("bool",l);for(let d=0;dg.value-m.value),u[d]=0;for(let m=0;mxP,depthwiseConv2d:()=>kP,matMul:()=>SP});function AP(e,t,n,s,r,a="NHWC",o){let i=e;e.rank===3&&(i=G(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=G(t,[1,t.shape[0],t.shape[1],t.shape[2]])),O(i.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${i.shape}.`),O(l.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),O(n.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`);let c=a==="NHWC"?i.shape[3]:i.shape[1],u=a==="NHWC"?l.shape[3]:l.shape[1];O(c===n[2],()=>`Error in conv2dDerFilter: depth of input ${c}) must match input depth in filter (${n[2]}.`),O(u===n[3],()=>`Error in conv2dDerFilter: depth of dy (${u}) must match output depth for filter (${n[3]}).`),o!=null&&O(mn(r),()=>`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);let d={x:i,dy:l},p={strides:s,pad:r,dataFormat:a,dimRoundingMode:o,filterShape:n};return B.runKernel(rh,d,p)}var l1=V({conv2DBackpropFilter_:AP});function uf(e,t,n){if(n==null||n==="linear")return e;if(n==="relu")return W(e,Ad(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function cf(e,t){let n=t,s=an(e.shape,t.shape);return s.length>0&&(n=Ie(n,s)),G(n,e.shape)}function df(e,t,n,s){if(t==="linear")return e;if(t==="relu")return Rr(e);if(t==="elu")return dd(e);if(t==="relu6")return X2(e);if(t==="prelu")return sf(e,n);if(t==="leakyrelu")return Kh(e,s);if(t==="sigmoid")return hs(e);throw new Error(`Unknown fused activation ${t}.`)}var pf=(e,t)=>!(e>0)||t==="linear";function yP({x:e,filter:t,strides:n,pad:s,dataFormat:r="NHWC",dilations:a=[1,1],dimRoundingMode:o,bias:i,activation:l="linear",preluActivationWeights:c,leakyreluAlpha:u}){if(l=l||"linear",pf(B.state.gradientDepth,l)===!1){let w=ko(e,t,n,s,r,a,o);return i!=null&&(w=ie(w,i)),df(w,l,c,u)}let d=_(e,"x","conv2d","float32"),p=_(t,"filter","conv2d","float32"),h=d,f=!1;d.rank===3&&(f=!0,h=G(d,[1,d.shape[0],d.shape[1],d.shape[2]])),O(h.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${h.rank}.`),O(p.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${p.rank}.`),o!=null&&O(mn(s),()=>`Error in fused conv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${s}.`),O(h.shape[3]===p.shape[2],()=>`Error in conv2d: depth of input (${h.shape[3]}) must match input depth for filter ${p.shape[2]}.`),O(Nr(n,a),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),O(r==="NHWC",()=>`Error in conv2d: got dataFormat of ${r} but only NHWC is currently supported.`);let m=ld(h.shape,p.shape,n,a,s,o),g;i!=null&&(g=_(i,"bias","fused conv2d"),[g]=Ft(g,d),St(m.outShape,g.shape));let A;c!=null&&(A=_(c,"prelu weights","fused conv2d"));let y=(w,k)=>{let[S,E,$,F]=k,R=uf(w,$,l);O(wo(a),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`);let P=_2(E.shape,R,S,n,s),T=l1(E,R,S.shape,n,s),M=[P,T];if(F!=null){let U=cf(F,R);M.push(U)}return M},x={x:h,filter:p,bias:g,preluActivationWeights:A},b={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:o,activation:l,leakyreluAlpha:u};return i==null?Er((k,S,E)=>{let $=B.runKernel(mo,x,b);return E([S,k,$]),f&&($=G($,[$.shape[1],$.shape[2],$.shape[3]])),{value:$,gradFunc:y}})(h,p):Er((k,S,E,$)=>{let F=B.runKernel(mo,x,b);return $([S,k,F,E]),f&&(F=G(F,[F.shape[1],F.shape[2],F.shape[3]])),{value:F,gradFunc:y}})(h,p,g)}var xP=V({fusedConv2d_:yP});function bP(e,t,n,s,r,a=[1,1],o){let i=e;e.rank===3&&(i=G(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=G(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let c={x:i,dy:l},u={strides:s,pad:r,dimRoundingMode:o,dilations:a,filterShape:n};return B.runKernel(lh,c,u)}var xv=V({depthwiseConv2dNativeBackpropFilter_:bP});function vP(e,t,n,s,r,a=[1,1],o){let i=t,l=!1;t.rank===3&&(l=!0,i=G(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let c={dy:i,filter:n},u={strides:s,pad:r,dimRoundingMode:o,dilations:a,inputShape:e},d=B.runKernel(uh,c,u);return l?G(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var bv=V({depthwiseConv2dNativeBackpropInput_:vP});function wP({x:e,filter:t,strides:n,pad:s,dataFormat:r="NHWC",dilations:a=[1,1],dimRoundingMode:o,bias:i,activation:l="linear",preluActivationWeights:c,leakyreluAlpha:u}){if(pf(B.state.gradientDepth,l)===!1){let w=cd(e,t,n,s,r,a,o);return i!=null&&(w=ie(w,i)),df(w,l,c,u)}let d=_(e,"x","depthwiseConv2d","float32"),p=_(t,"filter","depthwiseConv2d","float32"),h=d,f=!1;d.rank===3&&(f=!0,h=G(d,[1,d.shape[0],d.shape[1],d.shape[2]])),O(h.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${h.rank}.`),O(p.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${p.rank}.`),O(h.shape[3]===p.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${h.shape[3]}) must match the inChannels dimension in filter ${p.shape[2]}.`),a==null&&(a=[1,1]),O(Nr(n,a),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),o!=null&&O(mn(s),()=>`Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode ${o} but got pad ${s}.`);let m=ld(h.shape,p.shape,n,a,s,o,!0),g;i!=null&&(g=_(i,"bias","fused conv2d"),[g]=Ft(g,d),St(m.outShape,g.shape));let A;c!=null&&(A=_(c,"prelu weights","fused depthwiseConv2d"));let y=(w,k)=>{O(wo(a),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${a}'`);let[S,E,$,F]=k,R=uf(w,$,l),P=bv(E.shape,R,S,n,s,a,o),T=xv(E,R,S.shape,n,s,a,o);if(F!=null){let M=cf(g,R);return[P,T,M]}return[P,T]},x={x:h,filter:p,bias:g,preluActivationWeights:A},b={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:o,activation:l,leakyreluAlpha:u};return i==null?Er((k,S,E)=>{let $=B.runKernel(go,x,b);return E([S,k,$]),f&&($=G($,[$.shape[1],$.shape[2],$.shape[3]])),{value:$,gradFunc:y}})(h,p):Er((k,S,E,$)=>{let F=B.runKernel(go,x,b);return $([S,k,F,E]),f&&(F=G(F,[F.shape[1],F.shape[2],F.shape[3]])),{value:F,gradFunc:y}})(h,p,g)}var kP=V({fusedDepthwiseConv2d_:wP});function IP({a:e,b:t,transposeA:n=!1,transposeB:s=!1,bias:r,activation:a="linear",preluActivationWeights:o,leakyreluAlpha:i}){if(pf(B.state.gradientDepth,a)===!1){let F=He(e,t,n,s);return r!=null&&(F=ie(F,r)),df(F,a,o,i)}let l=_(e,"a","fused matMul"),c=_(t,"b","fused matMul");[l,c]=Ft(l,c);let u=n?l.shape[l.rank-2]:l.shape[l.rank-1],d=s?c.shape[c.rank-1]:c.shape[c.rank-2],p=n?l.shape[l.rank-1]:l.shape[l.rank-2],h=s?c.shape[c.rank-2]:c.shape[c.rank-1],f=l.shape.slice(0,-2),m=c.shape.slice(0,-2),g=Ut(f),A=Ut(m);O(l.rank>=2&&c.rank>=2&&l.rank===c.rank,()=>`Error in fused matMul: inputs must have the same rank of at least 2, got ranks ${l.rank} and ${c.rank}.`),O(Gr(f,m),()=>`Error in fused matMul: outer dimensions (${f}) and (${m}) of Tensors with shapes ${l.shape} and ${c.shape} must match.`),O(u===d,()=>`Error in fused matMul: inner shapes (${u}) and (${d}) of Tensors with shapes ${l.shape} and ${c.shape} and transposeA=${n} and transposeB=${s} must match.`);let y=l.shape.slice(0,-2).concat([p,h]),x=n?G(l,[g,u,p]):G(l,[g,p,u]),b=s?G(c,[A,h,d]):G(c,[A,d,h]),w;r!=null&&(w=_(r,"bias","fused matMul"),[w]=Ft(w,l),St(y,w.shape));let k;o!=null&&(k=_(o,"prelu weights","fused matMul"));let S=(F,R)=>{let[P,T,M,U]=R,H=uf(G(F,M.shape),M,a),z,X;if(!n&&!s?(z=He(H,T,!1,!0),X=He(P,H,!0,!1)):!n&&s?(z=He(H,T,!1,!1),X=He(H,P,!0,!1)):n&&!s?(z=He(T,H,!1,!0),X=He(P,H,!1,!1)):(z=He(T,H,!0,!0),X=He(H,P,!0,!0)),r!=null){let ee=cf(U,H);return[z,X,ee]}else return[z,X]},E={a:x,b,bias:w,preluActivationWeights:k},$={transposeA:n,transposeB:s,activation:a,leakyreluAlpha:i};return r==null?Er((R,P,T)=>{let M=B.runKernel(fo,E,$);return T([R,P,M]),{value:G(M,y),gradFunc:S}})(x,b):Er((R,P,T,M)=>{let U=B.runKernel(fo,E,$);return M([R,P,U,T]),{value:G(U,y),gradFunc:S}})(x,b,w)}var SP=V({fusedMatMul_:IP});function CP(e){return i1(e,.54,.46)}var TP=V({hammingWindow_:CP});function NP(e){return i1(e,.5,.5)}var vv=V({hannWindow_:NP});function EP(e,t,n,s=!1,r=0){let a=0,o=[];for(;a+t<=e.size;)o.push(_e(e,a,t)),a+=n;if(s)for(;a`Error in cropAndResize: image must be rank 4,but got rank ${o.rank}.`),O(i.rank===2&&i.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${c},4] but had shape ${i.shape}.`),O(l.rank===1&&l.shape[0]===c,()=>`Error in cropAndResize: boxInd must be have size [${c}] but had shape ${i.shape}.`),O(s.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${s.length}.`),O(s[0]>=1&&s[1]>=1,()=>`cropSize must be atleast [1,1], but was ${s}`),O(r==="bilinear"||r==="nearest",()=>`method must be bilinear or nearest, but was ${r}`);let u={image:o,boxes:i,boxInd:l},d={method:r,extrapolationValue:a,cropSize:s};return B.runKernel(oi,u,d)}var _P=V({cropAndResize_:DP});function PP(e){let t=_(e,"image","flipLeftRight","float32");O(t.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);let n={image:t};return B.runKernel(di,n,{})}var FP=V({flipLeftRight_:PP});function OP(e){let t=_(e,"image","grayscaleToRGB"),n=t.rank-1,s=t.shape[n];O(t.rank>=2,()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`),O(s===1,()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${s}.`);let r=new Array(t.rank);return r.fill(1,0,n),r[n]=3,js(t,r)}var MP=V({grayscaleToRGB_:OP});function zP(e,t,n=0,s=.5){let r=_(e,"image","rotateWithOffset","float32");O(r.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${r.rank}.`);let a={image:r},o={radians:t,fillValue:n,center:s};return B.runKernel(Vi,a,o)}var LP=V({rotateWithOffset_:zP});function Du(e,t,n,s,r,a){s==null&&(s=.5),r==null&&(r=Number.NEGATIVE_INFINITY),a==null&&(a=0);let o=e.shape[0];return n=Math.min(n,o),O(0<=s&&s<=1,()=>`iouThreshold must be in [0, 1], but was '${s}'`),O(e.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`),O(e.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`),O(t.rank===1,()=>"scores must be a 1D tensor"),O(t.shape[0]===o,()=>`scores has incompatible shape with boxes. Expected ${o}, but was ${t.shape[0]}`),O(0<=a&&a<=1,()=>`softNmsSigma must be in [0, 1], but was '${a}'`),{maxOutputSize:n,iouThreshold:s,scoreThreshold:r,softNmsSigma:a}}function BP(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY){let a=_(e,"boxes","nonMaxSuppression","float32"),o=_(t,"scores","nonMaxSuppression","float32"),i=Du(a,o,n,s,r);n=i.maxOutputSize,s=i.iouThreshold,r=i.scoreThreshold;let l={maxOutputSize:n,iouThreshold:s,scoreThreshold:r};return B.runKernel(vi,{boxes:a,scores:o},l)}var WP=V({nonMaxSuppression_:BP});function VP(e,t,n){let s=UP(e,t,n),r=s<0?-(s+1):s;e.splice(r,0,t)}function UP(e,t,n){return HP(e,t,n||GP)}function GP(e,t){return e>t?1:e>>1);let i=n(t,e[a]);i>0?s=a+1:(r=a,o=!i)}return o?s:-s-1}function kv(e,t,n,s,r){return u1(e,t,n,s,r,0)}function Iv(e,t,n,s,r,a){return u1(e,t,n,s,r,0,!1,a,!0)}function Sv(e,t,n,s,r,a){return u1(e,t,n,s,r,a,!0)}function u1(e,t,n,s,r,a,o=!1,i=!1,l=!1){let c=[];for(let g=0;gr&&c.push({score:t[g],boxIndex:g,suppressBeginIndex:0});c.sort(Cv);let u=a>0?-.5/a:0,d=[],p=[];for(;d.length0;){let g=c.pop(),{score:A,boxIndex:y,suppressBeginIndex:x}=g;if(A=x;--w){let k=jP(e,y,d[w]);if(k>=s){b=!0;break}if(g.score=g.score*qP(s,u,k),g.score<=r)break}g.suppressBeginIndex=d.length,b||(g.score===A?(d.push(y),p.push(g.score)):g.score>r&&VP(c,g,Cv))}let h=d.length,f=n-h;i&&f>0&&(d.push(...new Array(f).fill(0)),p.push(...new Array(f).fill(0)));let m={selectedIndices:d};return o&&(m.selectedScores=p),l&&(m.validOutputs=h),m}function jP(e,t,n){let s=e.subarray(t*4,t*4+4),r=e.subarray(n*4,n*4+4),a=Math.min(s[0],s[2]),o=Math.min(s[1],s[3]),i=Math.max(s[0],s[2]),l=Math.max(s[1],s[3]),c=Math.min(r[0],r[2]),u=Math.min(r[1],r[3]),d=Math.max(r[0],r[2]),p=Math.max(r[1],r[3]),h=(i-a)*(l-o),f=(d-c)*(p-u);if(h<=0||f<=0)return 0;let m=Math.max(a,c),g=Math.max(o,u),A=Math.min(i,d),y=Math.min(l,p),x=Math.max(A-m,0)*Math.max(y-g,0);return x/(h+f-x)}function qP(e,t,n){let s=Math.exp(t*n*n);return n<=e?s:0}function Cv(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function XP(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY){let a=_(e,"boxes","nonMaxSuppressionAsync"),o=_(t,"scores","nonMaxSuppressionAsync"),i=Du(a,o,n,s,r);n=i.maxOutputSize,s=i.iouThreshold,r=i.scoreThreshold;let l=await Promise.all([a.data(),o.data()]),c=l[0],u=l[1],{selectedIndices:d}=kv(c,u,n,s,r);return a!==e&&a.dispose(),o!==t&&o.dispose(),Zt(d,"int32")}var KP=XP;function ZP(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=0){let o=_(e,"boxes","nonMaxSuppression"),i=_(t,"scores","nonMaxSuppression"),l=Du(o,i,n,s,r,a);n=l.maxOutputSize,s=l.iouThreshold,r=l.scoreThreshold,a=l.softNmsSigma;let c={boxes:o,scores:i},u={maxOutputSize:n,iouThreshold:s,scoreThreshold:r,softNmsSigma:a},d=B.runKernel(wi,c,u);return{selectedIndices:d[0],selectedScores:d[1]}}var YP=V({nonMaxSuppressionWithScore_:ZP});async function JP(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=0){let o=_(e,"boxes","nonMaxSuppressionAsync"),i=_(t,"scores","nonMaxSuppressionAsync"),l=Du(o,i,n,s,r,a);n=l.maxOutputSize,s=l.iouThreshold,r=l.scoreThreshold,a=l.softNmsSigma;let c=await Promise.all([o.data(),i.data()]),u=c[0],d=c[1],{selectedIndices:p,selectedScores:h}=Sv(u,d,n,s,r,a);return o!==e&&o.dispose(),i!==t&&i.dispose(),{selectedIndices:Zt(p,"int32"),selectedScores:Zt(h)}}var QP=JP;function eF(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=!1){let o=_(e,"boxes","nonMaxSuppression"),i=_(t,"scores","nonMaxSuppression"),l=Du(o,i,n,s,r,null),c=l.maxOutputSize,u=l.iouThreshold,d=l.scoreThreshold,p={boxes:o,scores:i},h={maxOutputSize:c,iouThreshold:u,scoreThreshold:d,padToMaxOutputSize:a},f=B.runKernel(ou,p,h);return{selectedIndices:f[0],validOutputs:f[1]}}var tF=V({nonMaxSuppressionPadded_:eF});async function nF(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=!1){let o=_(e,"boxes","nonMaxSuppressionAsync"),i=_(t,"scores","nonMaxSuppressionAsync"),l=Du(o,i,n,s,r,null),c=l.maxOutputSize,u=l.iouThreshold,d=l.scoreThreshold,[p,h]=await Promise.all([o.data(),i.data()]),{selectedIndices:f,validOutputs:m}=Iv(p,h,c,u,d,a);return o!==e&&o.dispose(),i!==t&&i.dispose(),{selectedIndices:Zt(f,"int32"),validOutputs:Ee(m,"int32")}}var sF=nF;function rF(e,t,n=!1,s=!1){let r=_(e,"images","resizeBilinear");O(r.rank===3||r.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${r.rank}.`),O(t.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`),O(s===!1||n===!1,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let a=r,o=!1;r.rank===3&&(o=!0,a=G(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,i={images:a},l={alignCorners:n,halfPixelCenters:s,size:t},c=B.runKernel(eo,i,l);return o?G(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var aF=V({resizeBilinear_:rF});function oF(e,t,n=!1,s=!1){let r=_(e,"images","resizeNearestNeighbor");O(r.rank===3||r.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${r.rank}.`),O(t.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),O(r.dtype==="float32"||r.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype"),O(s===!1||n===!1,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let a=r,o=!1;r.rank===3&&(o=!0,a=G(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,i={images:a},l={alignCorners:n,halfPixelCenters:s,size:t},c=B.runKernel(uu,i,l);return o?G(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var iF=V({resizeNearestNeighbor_:oF});function lF(e,t="binary",n=!1,s=.5){let r=_(e,"image","threshold"),a=.2989,o=.587,i=.114,l=r.shape[0]*r.shape[1],c=W(Zt([s]),255),u,d,p,h;if(O(r.rank===3,()=>`Error in threshold: image must be rank 3,but got rank ${r.rank}.`),O(r.shape[2]===3||r.shape[2]===1,()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${r.shape[2]}.`),O(r.dtype==="int32"||r.dtype==="float32",()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${r.dtype}.`),O(t==="otsu"||t==="binary",()=>`Method must be binary or otsu, but was ${t}`),r.shape[2]===3){[u,d,p]=Sn(r,[1,1,1],-1);let g=W(u,a),A=W(d,o),y=W(p,i);h=ie(ie(g,A),y)}else h=e;if(t==="otsu"){let g=$2(he(K2(h),"int32"),Gt([]),256);c=uF(g,l)}let f=n?Ji(h,c):ms(h,c);return he(W(f,255),"int32")}function uF(e,t){let n=Zt([-1]),s=Zt([0]),r=Zt([0]),a,o,i,l,c,u;for(let d=0;d`Error in transform: image must be rank 4,but got rank ${o.rank}.`),O(i.rank===2&&(i.shape[0]===o.shape[0]||i.shape[0]===1)&&i.shape[1]===8,()=>"Error in transform: Input transform should be batch x 8 or 1 x 8"),O(a==null||a.length===2,()=>`Error in transform: outputShape must be [height, width] or null, but got ${a}.`);let l={image:o,transforms:i},c={interpolation:n,fillMode:s,fillValue:r,outputShape:a};return B.runKernel(Li,l,c)}var pF=V({transform_:dF});function hF(e,t,n){O(t%1==0,()=>`bandPart(): numLower must be an integer, got ${t}.`),O(n%1==0,()=>`bandPart(): numUpper must be an integer, got ${n}.`);let s=_(e,"a","bandPart");O(s.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${s.rank}.`);let r=s.shape,[a,o]=s.shape.slice(-2);if(!(t<=a))throw new Error(`bandPart(): numLower (${t}) must not be greater than the number of rows (${a}).`);if(!(n<=o))throw new Error(`bandPart(): numUpper (${n}) must not be greater than the number of columns (${o}).`);t<0&&(t=a),n<0&&(n=o);let i=G(Eu(0,a,1,"int32"),[-1,1]),l=Eu(0,o,1,"int32"),c=xe(i,l),u=lr(Ji(c,Ee(+t,"int32")),Yi(c,Ee(-n,"int32"))),d=Ht([a,o],s.dtype);return G(Pn(as(G(s,[-1,a,o])).map(p=>Wn(u,p,d))),r)}var fF=V({bandPart_:hF});function mF(e){let t;if(Array.isArray(e)){t=!1,O(e!=null&&e.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");let r=e[0].shape[0];for(let a=1;a`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[a].shape[0]} vs. ${r})`)}else t=!0,e=Sn(e,e.shape[0],0).map(r=>pt(r,[0]));O(e.length<=e[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`);let n=[],s=e;for(let r=0;r{let a=s[r];if(r>0)for(let o=0;o=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`),e.rank===2)return Tv(e,t);{let n=e.shape.slice(0,e.shape.length-2).reduce((l,c)=>l*c),s=as(G(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),r=[],a=[];s.forEach(l=>{let[c,u]=Tv(l,t);r.push(c),a.push(u)});let o=G(Pn(r,0),e.shape),i=G(Pn(a,0),e.shape);return[o,i]}}function Tv(e,t=!1){return B.tidy(()=>{O(e.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`);let n=e.shape[0],s=e.shape[1],r=z2(n),a=or(e),o=ur([[1]],[1,1]),i=or(o),l=n>=s?s:n;for(let c=0;c{let h=_e(a,[c,c],[n-c,1]),f=a1(h),m=_e(a,[c,c],[1,1]),g=Wn(ms(m,0),ur([[-1]]),ur([[1]])),A=xe(m,W(g,f)),y=fe(h,A);y.shape[0]===1?i=or(o):i=It([o,_e(y,[1,0],[y.shape[0]-1,y.shape[1]])],0);let x=Ot(fe(He(g,A),f)),b=_e(a,[c,0],[n-c,s]),w=W(x,i),k=et(i);if(c===0)a=xe(b,He(w,He(k,b)));else{let $=xe(b,He(w,He(k,b)));a=It([_e(a,[0,0],[c,s]),$],0)}let S=et(w),E=_e(r,[0,c],[n,r.shape[1]-c]);if(c===0)r=xe(E,He(He(E,i),S));else{let $=xe(E,He(He(E,i),S));r=It([_e(r,[0,0],[n,c]),$],1)}return[i,a,r]}),Q([u,d,p])}return!t&&n>s&&(r=_e(r,[0,0],[n,s]),a=_e(a,[0,0],[s,s])),[r,a]})}var yF=V({qr_:AF}),Vn;(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"})(Vn||(Vn={}));function xF(e,t,n=Vn.SUM_BY_NONZERO_WEIGHTS){let s=_(e,"losses","computeWeightedLoss"),r=null;t!=null&&(r=_(t,"weights","computeWeightedLoss"));let a=r==null?s:W(s,r);if(n===Vn.NONE)return a;if(n===Vn.SUM)return Ie(a);if(n===Vn.MEAN){if(r==null)return Wt(a);{let o=s.size/r.size,i=fe(Ie(a),Ie(r));return o>1?fe(i,Ee(o)):i}}if(n===Vn.SUM_BY_NONZERO_WEIGHTS){if(r==null)return fe(Ie(a),Ee(s.size));{let o=W(r,gs(s.shape)),i=he(Ie(Tu(o,Ee(0))),"float32");return fe(Ie(a),i)}}throw Error(`Unknown reduction: ${n}`)}var Jr=V({computeWeightedLoss_:xF});function bF(e,t,n,s=Vn.SUM_BY_NONZERO_WEIGHTS){let r=_(e,"labels","absoluteDifference"),a=_(t,"predictions","absoluteDifference"),o=null;n!=null&&(o=_(n,"weights","absoluteDifference")),zn(r.shape,a.shape,"Error in absoluteDifference: ");let i=rn(xe(r,a));return Jr(i,o,s)}var vF=V({absoluteDifference_:bF});function wF(e,t,n,s,r=Vn.SUM_BY_NONZERO_WEIGHTS){let a=_(e,"labels","cosineDistance"),o=_(t,"predictions","cosineDistance"),i=null;s!=null&&(i=_(s,"weights","cosineDistance")),zn(a.shape,o.shape,"Error in cosineDistance: ");let l=Ee(1),c=xe(l,Ie(W(a,o),n,!0));return Jr(c,i,r)}var kF=V({cosineDistance_:wF});function IF(e,t,n,s=Vn.SUM_BY_NONZERO_WEIGHTS){let r=_(e,"labels","hingeLoss"),a=_(t,"predictions","hingeLoss"),o=null;n!=null&&(o=_(n,"weights","hingeLoss")),zn(r.shape,a.shape,"Error in hingeLoss: ");let i=Ee(1);r=xe(W(Ee(2),r),i);let l=Rr(xe(i,W(r,a)));return Jr(l,o,s)}var SF=V({hingeLoss_:IF});function CF(e,t,n,s=1,r=Vn.SUM_BY_NONZERO_WEIGHTS){let a=_(e,"labels","huberLoss"),o=_(t,"predictions","huberLoss"),i=null;n!=null&&(i=_(n,"weights","huberLoss")),zn(a.shape,o.shape,"Error in huberLoss: ");let l=Ee(s),c=rn(xe(o,a)),u=hd(c,l),d=xe(c,u),p=ie(W(Ee(.5),xt(u)),W(l,d));return Jr(p,i,r)}var TF=V({huberLoss_:CF});function NF(e,t,n,s=1e-7,r=Vn.SUM_BY_NONZERO_WEIGHTS){let a=_(e,"labels","logLoss"),o=_(t,"predictions","logLoss"),i=null;n!=null&&(i=_(n,"weights","logLoss")),zn(a.shape,o.shape,"Error in logLoss: ");let l=Ee(1),c=Ee(s),u=Ot(W(a,Ns(ie(o,c)))),d=W(xe(l,a),Ns(ie(xe(l,o),c))),p=xe(u,d);return Jr(p,i,r)}var EF=V({logLoss_:NF});function RF(e,t,n,s=Vn.SUM_BY_NONZERO_WEIGHTS){let r=_(e,"labels","meanSquaredError"),a=_(t,"predictions","meanSquaredError"),o=null;n!=null&&(o=_(n,"weights","meanSquaredError")),zn(r.shape,a.shape,"Error in meanSquaredError: ");let i=n1(r,a);return Jr(i,o,s)}var $F=V({meanSquaredError_:RF});function DF(e,t){let n=_(e,"labels","sigmoidCrossEntropyWithLogits"),s=_(t,"logits","sigmoidCrossEntropyWithLogits");zn(n.shape,s.shape,"Error in sigmoidCrossEntropyWithLogits: ");let r=Rr(s),a=W(s,n),o=Zh(Ts(Ot(rn(s))));return ie(xe(r,a),o)}function _F(e,t,n,s=0,r=Vn.SUM_BY_NONZERO_WEIGHTS){let a=_(e,"multiClassLabels","sigmoidCrossEntropy"),o=_(t,"logits","sigmoidCrossEntropy"),i=null;if(n!=null&&(i=_(n,"weights","sigmoidCrossEntropy")),zn(a.shape,o.shape,"Error in sigmoidCrossEntropy: "),s>0){let c=Ee(s),u=Ee(1),d=Ee(.5);a=ie(W(a,xe(u,c)),W(d,c))}let l=DF(a,o);return Jr(l,i,r)}var PF=V({sigmoidCrossEntropy_:_F});function FF(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}`);return Er((r,a,o)=>{let l=J3(a,[n],!0),c=xe(he(a,"float32"),l);o([r,c]);let u=Ot(W(c,r));return{value:Ie(u,[n]),gradFunc:(h,f)=>{let[m,g]=f,A=Qi(h.shape,[n]);return[W(G(h,A),xe(he(m,"float32"),Ts(g))),W(G(h,A),xe(Ts(g),he(m,"float32")))]}}})(e,t)}function OF(e,t,n,s=0,r=Vn.SUM_BY_NONZERO_WEIGHTS){let a=_(e,"onehotLabels","softmaxCrossEntropy"),o=_(t,"logits","softmaxCrossEntropy"),i=null;if(n!=null&&(i=_(n,"weights","softmaxCrossEntropy")),zn(a.shape,o.shape,"Error in softmaxCrossEntropy: "),s>0){let c=Ee(s),u=Ee(1),d=Ee(a.shape[1]);a=ie(W(a,xe(u,c)),fe(c,d))}let l=FF(a,o);return Jr(l,i,r)}var MF=V({softmaxCrossEntropy_:OF});function zF(e,t,n,s){let r=_(e,"indices","sparseFillEmptyRows"),a=_(t,"values","sparseFillEmptyRows"),o=_(n,"denseShape","sparseFillEmptyRows"),i=_(s,"defaultValue","sparseFillEmptyRows",a.dtype);if(r.rank!==2)throw new Error(`Indices should be Tensor2D but received shape + ${r.shape}`);if(a.rank!==1)throw new Error(`Values should be Tensor1D but received shape ${a.shape}`);if(o.rank!==1)throw new Error(`Dense shape should be Tensor1D but received shape ${o.shape}`);if(i.rank!==0)throw new Error(`Default value should be a scalar but received shape ${i.shape}`);let l={indices:r,values:a,denseShape:o,defaultValue:i},c=B.runKernel(Ih,l);return{outputIndices:c[0],outputValues:c[1],emptyRowIndicator:c[2],reverseIndexMap:c[3]}}var LF=V({sparseFillEmptyRows_:zF});function BF(e,t,n){let s=_(e,"inputIndices","sparseReshape"),r=_(t,"inputShape","sparseReshape"),a=_(n,"newShape","sparseReshape");if(s.rank!==2)throw new Error(`Input indices should be Tensor2D but received shape + ${s.shape}`);if(r.rank!==1)throw new Error(`Input shape should be Tensor1D but received shape ${r.shape}`);if(a.rank!==1)throw new Error(`New shape should be Tensor1D but received shape ${a.shape}`);let o={inputIndices:s,inputShape:r,newShape:a},i=B.runKernel(Sh,o);return{outputIndices:i[0],outputShape:i[1]}}var WF=V({sparseReshape_:BF});function VF(e,t,n){let s=_(e,"data","sparseSegmentMean"),r=_(t,"indices","sparseSegmentMean"),a=_(n,"segmentIds","sparseSegmentMean");if(s.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.rank!==1)throw new Error(`Indices should be Tensor1D but received shape ${r.shape}`);if(a.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape - ${a.shape}`);let o={data:s,indices:r,segmentIds:a};return B.runKernel(Ch,o)}var UF=V({sparseSegmentMean_:VF});function GF(e,t,n){let s=D(e,"data","sparseSegmentSum"),r=D(t,"indices","sparseSegmentSum"),a=D(n,"segmentIds","sparseSegmentSum");if(s.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.rank!==1)throw new Error(`Indices should be Tensor1D but received shape + ${a.shape}`);let o={data:s,indices:r,segmentIds:a};return B.runKernel(Ch,o)}var UF=V({sparseSegmentMean_:VF});function GF(e,t,n){let s=_(e,"data","sparseSegmentSum"),r=_(t,"indices","sparseSegmentSum"),a=_(n,"segmentIds","sparseSegmentSum");if(s.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.rank!==1)throw new Error(`Indices should be Tensor1D but received shape ${r.shape}`);if(a.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape - ${a.shape}`);let o={data:s,indices:r,segmentIds:a};return B.runKernel(Th,o)}var HF=V({sparseSegmentSum_:GF});function jF(e,t,n,s,r,a,o,i){let l=D(e,"data","stringNGrams","string");if(l.dtype!=="string")throw new Error("Data must be of datatype string");if(l.shape.length!==1)throw new Error(`Data must be a vector, saw: ${l.shape}`);let c=D(t,"dataSplits","stringNGrams");if(c.dtype!=="int32")throw new Error("Data splits must be of datatype int32");let u={separator:n,nGramWidths:s,leftPad:r,rightPad:a,padWidth:o,preserveShortSequences:i},d={data:l,dataSplits:c},p=B.runKernel(qc,d,u);return{nGrams:p[0],nGramsSplits:p[1]}}var qF=V({stringNGrams_:jF});function XF(e,t,n=!0){let s=D(e,"input","stringSplit","string"),r=D(t,"delimiter","stringSplit","string");if(s.rank!==1)throw new Error(`Input should be Tensor1D but received shape ${s.shape}`);if(r.rank!==0)throw new Error(`Delimiter should be a scalar but received shape ${r.shape}`);let a={skipEmpty:n},o={input:s,delimiter:r},i=B.runKernel(Nh,o,a);return{indices:i[0],values:i[1],shape:i[2]}}var KF=V({stringSplit_:XF});function ZF(e,t){let n=D(e,"input","stringToHashBucketFast","string"),s={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");let r={input:n};return B.runKernel(Eh,r,s)}var YF=V({stringToHashBucketFast_:ZF}),JF={fft:af,ifft:gd,rfft:of,irfft:t1},QF={hammingWindow:TP,hannWindow:vv,frame:wv,stft:$P},$e={flipLeftRight:FP,grayscaleToRGB:MP,resizeNearestNeighbor:iF,resizeBilinear:aF,rotateWithOffset:LP,cropAndResize:_P,nonMaxSuppression:WP,nonMaxSuppressionAsync:KP,nonMaxSuppressionWithScore:YP,nonMaxSuppressionWithScoreAsync:QP,nonMaxSuppressionPadded:tF,nonMaxSuppressionPaddedAsync:sF,threshold:cF,transform:pF},Nv={bandPart:fF,gramSchmidt:gF,qr:yF},eO={absoluteDifference:vF,computeWeightedLoss:Jr,cosineDistance:kF,hingeLoss:SF,huberLoss:TF,logLoss:EF,meanSquaredError:$F,sigmoidCrossEntropy:PF,softmaxCrossEntropy:MF},yd={sparseFillEmptyRows:LF,sparseReshape:WF,sparseSegmentMean:UF,sparseSegmentSum:HF},hf={stringNGrams:qF,stringSplit:KF,stringToHashBucketFast:YF},Qr=class extends d3{minimize(e,t=!1,n){let{value:s,grads:r}=this.computeGradients(e,n);if(n!=null){let a=n.map(o=>({name:o.name,tensor:r[o.name]}));this.applyGradients(a)}else this.applyGradients(r);return Q(r),t?s:(s.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return X3(e,t)}dispose(){this.iterations_!=null&&Q(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:Ee(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(Qr,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});var ff=class extends Qr{constructor(e,t,n=null){super();this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],n==null&&(this.epsilon=B.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,s)=>{let r=B.registeredVariables[n],a=!1;this.accumulatedGrads[s]==null&&(this.accumulatedGrads[s]={originalName:`${n}/accum_grad`,variable:j(()=>tt(r).variable(a))}),this.accumulatedUpdates[s]==null&&(this.accumulatedUpdates[s]={originalName:`${n}/accum_var`,variable:j(()=>tt(r).variable(a))});let o=Array.isArray(e)?e[s].tensor:e[n];if(o==null)return;let i=this.accumulatedGrads[s].variable,l=this.accumulatedUpdates[s].variable;j(()=>{let c=ie(W(i,this.rho),W(xt(o),1-this.rho)),u=W(he(_n(ie(l,this.epsilon)),_n(ie(i,this.epsilon))),o),d=ie(W(l,this.rho),W(xt(u),1-this.rho));i.assign(c),l.assign(d);let p=ie(W(u,-this.learningRate),r);r.assign(p)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(Q(this.accumulatedGrads.map(e=>e.variable)),Q(this.accumulatedUpdates.map(e=>e.variable)))}async getWeights(){let 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);let t=e.length/2,n=!1;this.accumulatedGrads=e.slice(0,t).map(s=>({originalName:s.name,variable:s.tensor.variable(n)})),this.accumulatedUpdates=e.slice(t,t*2).map(s=>({originalName:s.name,variable:s.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)}};ff.className="Adadelta";vo(ff);var mf=class extends Qr{constructor(e,t=.1){super();this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,s)=>{let r=B.registeredVariables[n];if(this.accumulatedGrads[s]==null){let i=!1;this.accumulatedGrads[s]={originalName:`${n}/accumulator`,variable:j(()=>Iu(r.shape,this.initialAccumulatorValue).variable(i))}}let a=Array.isArray(e)?e[s].tensor:e[n];if(a==null)return;let o=this.accumulatedGrads[s].variable;j(()=>{let i=ie(o,xt(a));o.assign(i);let l=ie(W(he(a,_n(ie(i,B.backend.epsilon()))),-this.learningRate),r);r.assign(l)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&Q(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);let 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)}};mf.className="Adagrad";vo(mf);var gf=class extends Qr{constructor(e,t,n,s=null){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=s,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],j(()=>{this.accBeta1=Ee(t).variable(),this.accBeta2=Ee(n).variable()}),s==null&&(this.epsilon=B.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);j(()=>{let n=ye(1,this.accBeta1),s=ye(1,this.accBeta2);t.forEach((r,a)=>{let o=B.registeredVariables[r],i=!1;this.accumulatedFirstMoment[a]==null&&(this.accumulatedFirstMoment[a]={originalName:`${r}/m`,variable:j(()=>tt(o).variable(i))}),this.accumulatedSecondMoment[a]==null&&(this.accumulatedSecondMoment[a]={originalName:`${r}/v`,variable:j(()=>tt(o).variable(i))});let l=Array.isArray(e)?e[a].tensor:e[r];if(l==null)return;let c=this.accumulatedFirstMoment[a].variable,u=this.accumulatedSecondMoment[a].variable,d=ie(W(c,this.beta1),W(l,1-this.beta1)),p=ie(W(u,this.beta2),W(xt(l),1-this.beta2)),h=he(d,n),f=he(p,s);c.assign(d),u.assign(p);let m=ie(W(he(h,ie(_n(f),this.epsilon)),-this.learningRate),o);o.assign(m)}),this.accBeta1.assign(W(this.accBeta1,this.beta1)),this.accBeta2.assign(W(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&Q(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&Q(this.accumulatedSecondMoment.map(e=>e.variable))}async getWeights(){let 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),j(()=>{this.accBeta1.assign(Io(this.beta1,this.iterations_+1)),this.accBeta2.assign(Io(this.beta2,this.iterations_+1))});let t=e.length/2,n=!1;this.accumulatedFirstMoment=e.slice(0,t).map(s=>({originalName:s.name,variable:s.tensor.variable(n)})),this.accumulatedSecondMoment=e.slice(t,t*2).map(s=>({originalName:s.name,variable:s.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)}};gf.className="Adam";vo(gf);var Af=class extends Qr{constructor(e,t,n,s=null,r=0){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=s,this.decay=r,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],j(()=>{this.iteration=Ee(0).variable(),this.accBeta1=Ee(t).variable()}),s==null&&(this.epsilon=B.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);j(()=>{let n=ye(1,this.accBeta1),s=he(-this.learningRate,ie(W(this.iteration,this.decay),1));t.forEach((r,a)=>{let o=B.registeredVariables[r],i=!1;this.accumulatedFirstMoment[a]==null&&(this.accumulatedFirstMoment[a]={originalName:`${r}/m`,variable:tt(o).variable(i)}),this.accumulatedWeightedInfNorm[a]==null&&(this.accumulatedWeightedInfNorm[a]={originalName:`${r}/v`,variable:tt(o).variable(i)});let l=Array.isArray(e)?e[a].tensor:e[r];if(l==null)return;let c=this.accumulatedFirstMoment[a].variable,u=this.accumulatedWeightedInfNorm[a].variable,d=ie(W(c,this.beta1),W(l,1-this.beta1)),p=W(u,this.beta2),h=rn(l),f=Yr(p,h);c.assign(d),u.assign(f);let m=ie(W(he(s,n),he(d,ie(f,this.epsilon))),o);o.assign(m)}),this.iteration.assign(ie(this.iteration,1)),this.accBeta1.assign(W(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&Q(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&Q(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)}};Af.className="Adamax";vo(Af);var xd=class extends Qr{constructor(e){super();this.learningRate=e,this.setLearningRate(e)}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,s)=>{let r=Array.isArray(e)?e[s].tensor:e[n];if(r==null)return;let a=B.registeredVariables[n];j(()=>{let o=ie(W(this.c,r),a);a.assign(o)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=yn(Ee(-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)}};xd.className="SGD";vo(xd);var yf=class extends xd{constructor(e,t,n=!1){super(e);this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=Ee(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,s)=>{let r=B.registeredVariables[n];if(this.accumulations[s]==null){let i=!1;this.accumulations[s]={originalName:`${n}/momentum`,variable:j(()=>tt(r).variable(i))}}let a=this.accumulations[s].variable,o=Array.isArray(e)?e[s].tensor:e[n];o!=null&&j(()=>{let i,l=ie(W(this.m,a),o);this.useNesterov?i=ie(W(this.c,ie(o,W(l,this.m))),r):i=ie(W(this.c,l),r),a.assign(l),r.assign(i)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&Q(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);let 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)}};yf.className="Momentum";vo(yf);var xf=class extends Qr{constructor(e,t=.9,n=0,s=null,r=!1){super();if(this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=s,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=r,s==null&&(this.epsilon=B.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,s)=>{let r=B.registeredVariables[n],a=!1;this.accumulatedMeanSquares[s]==null&&(this.accumulatedMeanSquares[s]={originalName:`${n}/rms`,variable:j(()=>tt(r).variable(a))}),this.accumulatedMoments[s]==null&&(this.accumulatedMoments[s]={originalName:`${n}/momentum`,variable:j(()=>tt(r).variable(a))}),this.accumulatedMeanGrads[s]==null&&this.centered&&(this.accumulatedMeanGrads[s]={originalName:`${n}/mg`,variable:j(()=>tt(r).variable(a))});let o=Array.isArray(e)?e[s].tensor:e[n];if(o==null)return;let i=this.accumulatedMeanSquares[s].variable,l=this.accumulatedMoments[s].variable;j(()=>{let c=ie(W(i,this.decay),W(xt(o),1-this.decay));if(this.centered){let u=this.accumulatedMeanGrads[s].variable,d=ie(W(u,this.decay),W(o,1-this.decay)),p=he(W(o,this.learningRate),_n(ye(c,ie(xt(d),this.epsilon)))),h=ie(W(l,this.momentum),p);i.assign(c),u.assign(d),l.assign(h);let f=ye(r,h);r.assign(f)}else{let u=ie(W(i,this.decay),W(xt(o),1-this.decay)),d=ie(W(l,this.momentum),he(W(o,this.learningRate),_n(ie(u,this.epsilon))));i.assign(u),l.assign(d);let p=ye(r,d);r.assign(p)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&Q(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&Q(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&Q(this.accumulatedMoments.map(e=>e.variable))}async getWeights(){let 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);let t=this.centered?e.length/3:e.length/2,n=!1;this.accumulatedMeanSquares=e.slice(0,t).map(s=>({originalName:s.name,variable:s.tensor.variable(n)})),this.accumulatedMoments=e.slice(t,t*2).map(s=>({originalName:s.name,variable:s.tensor.variable(n)})),this.centered&&(this.accumulatedMeanGrads=e.slice(t*2,t*3).map(s=>({originalName:s.name,variable:s.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)}};xf.className="RMSProp";vo(xf);var el=class{static sgd(e){return new xd(e)}static momentum(e,t,n=!1){return new yf(e,t,n)}static rmsprop(e,t=.9,n=0,s=null,r=!1){return new xf(e,t,n,s,r)}static adam(e=.001,t=.9,n=.999,s=null){return new gf(e,t,n,s)}static adadelta(e=.001,t=.95,n=null){return new ff(e,t,n)}static adamax(e=.002,t=.9,n=.999,s=null,r=0){return new Af(e,t,n,s,r)}static adagrad(e,t=.1){return new mf(e,t)}},tl={sgd:el.sgd,momentum:el.momentum,adadelta:el.adadelta,adagrad:el.adagrad,rmsprop:el.rmsprop,adamax:el.adamax,adam:el.adam},tO=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:e=>e())();function Ev(){return new Promise(e=>tO(()=>e()))}var N={};ze(N,{ERF_A1:()=>pO,ERF_A2:()=>hO,ERF_A3:()=>fO,ERF_A4:()=>mO,ERF_A5:()=>gO,ERF_P:()=>dO,PARALLELIZE_THRESHOLD:()=>c1,SELU_SCALE:()=>$v,SELU_SCALEALPHA:()=>Rv,applyActivation:()=>df,assertAndGetBroadcastShape:()=>St,assertAxesAreInnerMostDims:()=>hD,assertParamsConsistent:()=>nO,assignToTypedArray:()=>wO,axesAreInnerMostDims:()=>W2,calculateShapes:()=>Q5,checkEinsumDimSizes:()=>NO,combineLocations:()=>K3,complexWithEvenIndex:()=>xO,complexWithOddIndex:()=>bO,computeConv2DInfo:()=>ld,computeConv3DInfo:()=>C3,computeDefaultPad:()=>N2,computeDilation2DInfo:()=>DR,computeOptimalWindowSize:()=>rO,computeOutAndReduceShapes:()=>Z3,computeOutShape:()=>sO,computePool2DInfo:()=>S3,computePool3DInfo:()=>_R,convertConv2DDataFormat:()=>T3,decodeEinsumEquation:()=>CO,eitherStridesOrDilationsAreOne:()=>Nr,expandShapeToKeepDim:()=>Qi,exponent:()=>IO,exponents:()=>kO,fromStringArrayToUint8:()=>MO,fromUint8ToStringArray:()=>OO,getAxesPermutation:()=>Y3,getBroadcastDims:()=>I$,getComplexWithIndex:()=>vO,getEinsumComputePath:()=>EO,getEinsumPermutation:()=>TO,getFusedBiasGradient:()=>cf,getFusedDyActivation:()=>uf,getImageCenter:()=>aO,getInnerMostAxes:()=>fD,getPermuted:()=>iO,getReductionAxes:()=>an,getReshaped:()=>oO,getReshapedPermuted:()=>lO,getSliceBeginCoords:()=>uO,getSliceSize:()=>cO,getUndoAxesPermutation:()=>V2,isIdentityPermutation:()=>RO,log:()=>aE,mergeRealAndImagArrays:()=>AO,prepareAndValidate:()=>J5,prepareSplitSize:()=>DO,segment_util:()=>Pv,shouldFuse:()=>pf,slice_util:()=>An,splitRealAndImagArrays:()=>yO,tupleValuesAreOne:()=>wo,upcastType:()=>Bn,validateInput:()=>b2,validateUpdateShape:()=>x2,warn:()=>kr});function nO(e,t){let n=e[0].length;e.forEach((r,a)=>{O(r.length===n,()=>`Error in concat${n}D: rank of tensors[${a}] must be the same as the rank of the rest (${n})`)}),O(t>=0&&t`Error in concat${n}D: axis must be between 0 and ${n-1}.`);let s=e[0];e.forEach((r,a)=>{for(let o=0;o`Error in concat${n}D: Shape of tensors[${a}] (${r}) does not match the shape of the rest (${s}) along the non-concatenated axis ${a}.`)})}function sO(e,t){let n=e[0].slice();for(let s=1;s=t*2+1||o%2==1?a.push(o):r.push(o);s.push(...r),s.push(0),s.push(...a)}return s}function lO(e,t,n,s=!0){let r=[];s?r.push(e[0]/n):r.push(e[0]*n);for(let a=1;a/g,Dv=",",_v="...";function CO(e,t){e=e.replace(/\s/g,"");let n=(e.length-e.replace(SO,"").length)/d1.length;if(n<1)throw new Error("Equations without an arrow are not supported.");if(n>1)throw new Error(`Equation must contain exactly one arrow ("${d1}").`);let[s,r]=e.split(d1);O(s.indexOf(_v)===-1,()=>`The ellipsis notation ("${_v}") is not supported yet.`);let a=s.split(Dv),o=a.length;if(t!==o)throw new Error(`Expected ${o} input tensors, received ${t}`);if(o>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");let i=[];for(let p=0;pf.indexOf(h)!==-1))throw new Error(`Output subscripts contain the label ${h} not present in the input subscripts.`);i.indexOf(h)===-1&&i.push(h)}for(let p=0;pr!==-1),{permutationIndices:n,expandDims:s}}function NO(e,t,n){let s=new Array(e);for(let r=0;r`Expected dimension ${s[t[r][o]]} at axis ${o} of input shaped ${JSON.stringify(a)}, but got dimension ${a[o]}`)}}function EO(e,t){let n=e,s=[],r=0;e.length===0&&n.push(-1),r=e.length+1;for(let o=0;ot===n)}function $O(e,t){let n=[];for(let s=0;s"Number of splits must evenly divide the axis."),s=new Array(t).fill(e.shape[n]/t);else{let r=t.reduce((o,i)=>(i===-1&&(o+=1),o),0);O(r<=1,()=>"There should be only one negative value in split array.");let a=t.indexOf(-1);if(a!==-1){let o=t.reduce((i,l)=>l>0?i+l:i);t[a]=e.shape[n]-o}O(e.shape[n]===t.reduce((o,i)=>o+i),()=>"The sum of sizes must match the size of the axis dimension."),s=t}return s}var Pv={};ze(Pv,{collectGatherOpShapeInfo:()=>FO,computeOutShape:()=>PO,segOpComputeOptimalWindowSize:()=>_O});function _O(e,t){let n=!1,s;for(e<=c1?(s=e,n=!0):s=Jp(e,Math.floor(Math.sqrt(e)));!n;)s>t||s===e?n=!0:s=Jp(e,s+1);return s}function PO(e,t,n){let s=[],r=e.length;for(let a=0;ar))throw new Error(`Expect batchDims in the range of [-${r}, ${r}], but got ${s}`);if(s<0&&(s+=r),s>a)throw new Error(`batchDims (${s}) must be less than rank(x) ( - ${a}).`);if(nPh(t))}catch(t){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${t}`)}}function MO(e){return e.map(t=>Qc(t))}var Xs={};ze(Xs,{nonMaxSuppressionV3Impl:()=>kv,nonMaxSuppressionV4Impl:()=>Iv,nonMaxSuppressionV5Impl:()=>Sv,whereImpl:()=>hv});var Fv={kernelName:ni,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(e,Ad(de(n,"float32"),-1))}}},zO={kernelName:Vl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let s=xt(de(n,"float32")),r=_n(ye(Ee(1),s));return Ot(he(e,r))}}}},LO={kernelName:Ul,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let s=_n(ye(xt(de(n,"float32")),1));return he(e,s)}}}},BO={kernelName:Hr,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=St(n.shape,s.shape);return{a:()=>{let i=e,l=an(n.shape,r);return l.length>0&&(i=Ie(i,l)),G(i,n.shape)},b:()=>{let i=e,l=an(s.shape,r);return l.length>0&&(i=Ie(i,l)),G(i,s.shape)}}}},WO={kernelName:wa,saveAllInputs:!0,gradFunc:(e,t)=>{let n={};return t.forEach((s,r)=>{n[r]=()=>e.clone()}),n}},VO={kernelName:ka,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>tt(n)}}},UO={kernelName:jl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>tt(n)}}},GO={kernelName:ql,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,_n(ye(Ee(1),xt(de(n,"float32")))))}}},HO={kernelName:Xl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let s=_n(ie(Ee(1),xt(de(n,"float32"))));return he(e,s)}}}},jO={kernelName:Yl,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=St(n.shape,s.shape);return{a:()=>{let i=ie(xt(n),xt(s)),l=W(e,he(s,i)),c=an(n.shape,r);return c.length>0&&(l=Ie(l,c)),G(l,n.shape)},b:()=>{let i=ie(xt(n),xt(s)),l=Ot(W(e,he(n,i))),c=an(s.shape,r);return c.length>0&&(l=Ie(l,c)),G(l,s.shape)}}}},qO={kernelName:Kl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,ie(xt(de(n,"float32")),1))}}},XO={kernelName:Zl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,ye(Ee(1),xt(de(n,"float32"))))}}};function KO(e,t,n,s,r,a){let o=D(e,"dy","avgPool3dGrad"),i=D(t,"input","avgPool3dGrad"),l=o,c=i,u=!1;i.rank===4&&(u=!0,l=G(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),c=G(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),O(l.rank===5,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${l.rank}.`),O(c.rank===5,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${c.rank}.`),a!=null&&O(mn(r),()=>`Error in avgPool3dGrad: pad must be an integer when using, dimRoundingMode ${a} but got pad ${r}.`);let d={dy:l,input:c},p={filterSize:n,strides:s,pad:r,dimRoundingMode:a},h=B.runKernel(th,d,p);return u?G(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}var ZO=V({avgPool3dGrad_:KO}),YO={kernelName:Fc,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{filterSize:r,strides:a,pad:o,dimRoundingMode:i}=n;return{x:()=>ZO(e,s,r,a,o,i)}}};function JO(e,t,n,s,r){let a=D(e,"dy","avgPoolGrad"),o=D(t,"input","avgPoolGrad");O(o.rank===a.rank,()=>`Rank of input (${o.rank}) does not match rank of dy (${a.rank})`);let i=o,l=a,c=!1;o.rank===3&&(c=!0,i=G(o,[1,o.shape[0],o.shape[1],o.shape[2]]),l=G(a,[1,a.shape[0],a.shape[1],a.shape[2]])),O(l.rank===4,()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${l.rank}.`),O(i.rank===4,()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${i.rank}.`);let u={dy:l,input:i},d={filterSize:n,strides:s,pad:r},p=B.runKernel(eh,u,d);return c?G(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var QO=V({avgPoolGrad_:JO}),eM={kernelName:Ia,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{filterSize:r,strides:a,pad:o}=n;return{x:()=>QO(e,s,r,a,o)}}},tM={kernelName:Sa,inputsToSave:["a","b"],gradFunc:(e,t,n)=>{let[s,r]=t,{transposeA:a,transposeB:o}=n;return!a&&!o?{a:()=>He(e,r,!1,!0),b:()=>He(s,e,!0,!1)}:!a&&o?{a:()=>He(e,r,!1,!1),b:()=>He(e,s,!0,!1)}:a&&!o?{a:()=>He(r,e,!1,!0),b:()=>He(s,e,!1,!1)}:{a:()=>He(r,e,!0,!0),b:()=>He(e,s,!0,!0)}}},nM={kernelName:si,gradFunc:(e,t,n)=>{let{blockShape:s,crops:r}=n;return{x:()=>nf(e,s,r)}}},sM={kernelName:m5,gradFunc:(e,t,n)=>{let s=n,r=s.inputShape,a=s.shape,o=Array.from(a);for(let l=r.length-1;l>=0;l--)if(r[l]===a[l])o[l]=1;else if(r[l]!==1)throw new Error(`broadcastTo(): [${r}] cannot be broadcast to [${a}].`);let i=[];for(let l=0;l1&&i.push(l);return{x:()=>Ie(e,i,!0)}}},rM={kernelName:Ca,gradFunc:e=>({x:()=>e.clone()})},aM={kernelName:Ta,gradFunc:e=>({x:()=>tt(e)})},oM={kernelName:jr,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{clipValueMin:r,clipValueMax:a}=n;return{x:()=>Wn(lr(Yi(s,r),Ji(s,a)),e,tt(e))}}},iM={kernelName:Mc,inputsToSave:["x"],gradFunc:Fv.gradFunc},lM={kernelName:ri,saveAllInputs:!0,gradFunc:(e,t,n)=>{let s=t.map(l=>l.shape),{axis:r}=n,a=Us(r,t[0].shape)[0],o=s.map(l=>l[a]);return Sn(e,o,a).map(l=>()=>l)}},uM={kernelName:Na,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let[s,r]=t,{dilations:a,strides:o,pad:i,dataFormat:l}=n;return O(wo(a),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`),{x:()=>_2(s.shape,e,r,o,i,l),filter:()=>l1(s,e,r.shape,o,i,l)}}},cM={kernelName:Ea,inputsToSave:["dy","filter"],gradFunc:(e,t,n)=>{let[s,r]=t,{strides:a,pad:o,dataFormat:i,dimRoundingMode:l}=n;return{dy:()=>ko(e,r,a,o,i,1,l),filter:()=>l1(e,s,r.shape,a,o,i,l)}}};function dM(e,t,n,s,r){let a=e;e.rank===4&&(a=G(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let o=t;o.rank===4&&(o=G(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),O(a.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${a.shape}.`),O(o.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${o.shape}.`),O(n.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${n}.`),O(a.shape[4]===n[3],()=>`Error in conv3dDerFilter: depth of input ${a.shape[4]}) must match input depth in filter (${n[3]}.`),O(o.shape[4]===n[4],()=>`Error in conv3dDerFilter: depth of dy (${o.shape[4]}) must match output depth for filter (${n[4]}).`);let i={x:a,dy:o},l={strides:s,pad:r,filterShape:n};return B.runKernel(ah,i,l)}var pM=V({conv3DBackpropFilter_:dM}),hM={kernelName:zc,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let{dilations:s,strides:r,pad:a}=n;O(wo(s),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);let[o,i]=t;return{x:()=>O3(o.shape,e,i,r,a),filter:()=>pM(o,e,i.shape,r,a)}}},fM={kernelName:Ra,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(Ot(J2(de(n,"float32"))),e)}}},mM={kernelName:$a,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(Q2(de(n,"float32")),e)}}},gM={kernelName:ai,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{axis:r,exclusive:a,reverse:o}=n;return{x:()=>{let i=Y3([r],s.rank),l=M2(e,r,a,!o);return i!=null&&(l=et(l,i)),l}}}},AM={kernelName:Da,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let{dilations:s,strides:r,pad:a,dimRoundingMode:o}=n,i=s==null?[1,1]:s;O(wo(i),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${i}'`);let[l,c]=t;return O(l.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`),O(c.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${c.rank}.`),O(l.shape[3]===c.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${l.shape[3]}) must match the inChannels dimension in filter ${c.shape[2]}.`),O(Nr(r,i),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${r} and dilations '${i}'.`),o!=null&&O(mn(a),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${a}.`),{x:()=>bv(l.shape,e,c,r,a,i,o),filter:()=>xv(l,e,c.shape,r,a,i,o)}}},yM={kernelName:Lc,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let[s,r]=t,a={x:s,filter:r,dy:e},o={x:s,filter:r,dy:e};return{x:()=>B.runKernel(dh,a,n),filter:()=>B.runKernel(ph,o,n)}}},xM={kernelName:Pa,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t,s={dy:e,y:n};return{x:()=>B.runKernel(hh,s)}}},bM={kernelName:Jl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t,s=W(Ts(Ot(xt(n))),2/Math.sqrt(Math.PI));return{x:()=>W(e,s)}}},vM={kernelName:Fa,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(e,n)}}},wM={kernelName:ui,inputsToSave:["input"],gradFunc:(e,t)=>{let[n]=t;return{input:()=>G(e,n.shape)}}},kM={kernelName:ci,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(e,Ts(n))}}},IM={kernelName:Oa,gradFunc:e=>({x:()=>tt(e)})},SM={kernelName:Ma,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=St(n.shape,s.shape);return{a:()=>{let i=he(e,de(s,"float32")),l=an(n.shape,r);return l.length>0?G(Ie(i,l),n.shape):i},b:()=>{let i=W(e,de(n,"float32")),l=an(s.shape,r);l.length>0&&(i=G(Ie(i,l),s.shape));let c=xt(s);return Ot(he(i,de(c,"float32")))}}}},CM={kernelName:za,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{let{varianceEpsilon:s}=n,[r,a,o,i]=t,l=i==null?Ee(1):i,c=an(a.shape,r.shape),u=[];if(a.rank===1){for(let b=0;ba.rank===1?G(W(W(e,js(G(h,[1,1,1,a.shape[0]]),u)),l),r.shape):G(W(W(e,h),l),r.shape),mean:()=>{let b=W(W(h,Ee(-1)),p);return a.rank===1&&(b=Ie(b,c)),G(b,a.shape)},variance:()=>{let b=W(W(f,d),p);return a.rank===1&&(b=Ie(b,c)),G(b,a.shape)},scale:()=>{let b=W(d,h),w=W(e,b);return a.rank===1&&(w=Ie(w,c)),G(w,a.shape)},offset:()=>{let b=e;return a.rank===1&&(b=Ie(b,c)),G(b,a.shape)}}}},TM={kernelName:pi,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{let[s,r]=t,{axis:a}=n,o=Us(a,s.shape)[0];return{x:()=>{let l=s.shape,c=r.size,u=l.slice(0,o),d=u.length,p=l.slice(a,l.length).slice(1),h=p.length,f=Ov(0,d),m=Ov(d+1,d+1+h),g=Mv([u,[c],p]),A=G(e,g),y=G(r,[c]),x=Mv([[d],f,m]),b=et(A,x),w=dv(b,y,s.shape[o]),k=V2(x);return w=et(w,k),w},indices:()=>r}}};function Ov(e,t){let n=[];for(let s=e;s{let[n,s]=t;return{a:()=>tt(n),b:()=>tt(s)}}},EM={kernelName:Ba,gradFunc:e=>({x:()=>de(e,"float32")})},RM={kernelName:eu,gradFunc:e=>({x:()=>tt(e)})},$M={kernelName:tu,gradFunc:e=>({x:()=>tt(e)})},DM={kernelName:nu,gradFunc:e=>({x:()=>tt(e)})},_M={kernelName:mi,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{alpha:r}=n,a=ms(s,0);return{x:()=>Wn(a,e,W(e,r))}}},PM={kernelName:su,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,ie(n,1))}}},FM={kernelName:Wa,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,de(n,"float32"))}}},OM={kernelName:g5,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[s]=t,{axis:r}=n;return{logits:()=>{let a=!0,o=Ts(s);return ye(e,W(Ie(e,r,a),o))}}}};function MM(e,t,n,s=5,r=1,a=1,o=.5){let i={x:e,y:t,dy:n},l={depthRadius:s,bias:r,alpha:a,beta:o};return B.runKernel(Ah,i,l)}var zM=V({localResponseNormalizationBackprop_:MM}),LM={kernelName:Uc,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[s,r]=t,{depthRadius:a,bias:o,alpha:i,beta:l}=n;return{x:()=>zM(s,r,e,a,o,i,l)}}};function zv(e,t,n,s){return t.rankW(e,de(Cs(n,t),e.dtype))}}var Lv={kernelName:Va,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let s=n,{reductionIndices:r}=s,a=t[0],o=t[1],i=Us(r,a.shape),l=zv(e,o,a,i);return{x:()=>l.x()}}},BM={kernelName:Ua,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t;return{a:()=>W(e,de(Yi(n,s),"float32")),b:()=>W(e,de(L2(n,s),"float32"))}}};function WM(e,t,n,s,r,a,o){let i=D(e,"dy","maxPool3dGrad"),l=D(t,"input","maxPool3dGrad"),c=D(n,"output","maxPool3dGrad"),u=i,d=l,p=c,h=!1;l.rank===4&&(h=!0,u=G(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),d=G(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),p=G(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]])),O(u.rank===5,()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${u.rank}.`),O(d.rank===5,()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${d.rank}.`),O(p.rank===5,()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${p.rank}.`),o!=null&&O(mn(a),()=>`Error in maxPool3dGrad: pad must be an integer when using, dimRoundingMode ${o} but got pad ${a}.`);let f={dy:u,input:d,output:p},m={filterSize:s,strides:r,pad:a,dimRoundingMode:o},g=B.runKernel(xh,f,m);return h?G(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}var VM=V({maxPool3dGrad_:WM}),UM={kernelName:Gc,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[s,r]=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:l}=n;return{x:()=>VM(e,s,r,a,o,i,l)}}};function GM(e,t,n,s,r,a,o){let i=D(e,"dy","maxPoolGrad"),l=D(t,"input","maxPoolGrad"),c=D(n,"output","maxPoolGrad");O(l.rank===i.rank,()=>`Rank of input (${l.rank}) does not match rank of dy (${i.rank})`),O(i.rank===4,()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${i.rank}.`),O(l.rank===4,()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`),o!=null&&O(mn(a),()=>`Error in maxPoolGrad: pad must be an integer when using, dimRoundingMode ${o} but got pad ${a}.`);let u={dy:i,input:l,output:c},d={filterSize:s,strides:r,pad:a,dimRoundingMode:o};return B.runKernel(yh,u,d)}var HM=V({maxPoolGrad_:GM}),jM={kernelName:Ga,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[s,r]=t,{filterSize:a,strides:o,pad:i}=n;return{x:()=>HM(e,s,r,a,o,i)}}},qM={kernelName:Ha,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{axis:r}=n,a=Us(r,s.shape),i=Z3(s.shape,a)[1],l=Ut(i);return{x:()=>{let u=s.shape.slice();a.forEach(h=>{u[h]=1});let d=G(e,u);return he(W(d,gs(s.shape,"float32")),l)}}}},XM={kernelName:ja,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let s=n,{axis:r}=s,[a,o]=t,i=Us(r,a.shape),l=zv(e,o,a,i);return{x:()=>l.x()}}},KM={kernelName:qa,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t;return{a:()=>W(e,de(Ji(n,s),"float32")),b:()=>W(e,de(ms(n,s),"float32"))}}},ZM={kernelName:Xa,inputsToSave:["x"],gradFunc:(e,t,n)=>{let s=t[0],{paddings:r}=n,a=r.map(o=>o[0]);return{x:()=>_e(e,a,s.shape)}}},YM={kernelName:au,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=St(n.shape,s.shape);return{a:()=>{let i=an(n.shape,r);return i.length>0?G(Ie(e,i),n.shape):e},b:()=>{let i=W(e,Ot(pd(he(n,s)))),l=an(s.shape,r);return l.length>0?G(Ie(i,l),s.shape):i}}}},JM={kernelName:Ka,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=St(n.shape,s.shape);return{a:()=>{let i=W(e,de(s,"float32")),l=an(n.shape,r);return l.length>0?G(Ie(i,l),n.shape):i},b:()=>{let i=W(e,de(n,"float32")),l=an(s.shape,r);return l.length>0?G(Ie(i,l),s.shape):i}}}},QM={kernelName:xi,gradFunc:e=>({x:()=>Ot(e)})},ez={kernelName:Ii,inputsToSave:["indices"],gradFunc:(e,t)=>{let n=t[0];return{indices:()=>Ht(n.shape,"float32")}}},tz={kernelName:ki,gradFunc:e=>({x:()=>tt(e)})},nz={kernelName:Si,saveAllInputs:!0,gradFunc:(e,t,n)=>{let{axis:s}=n;return as(e,s).map(a=>()=>a)}},Bv={kernelName:Za,inputsToSave:["x"],gradFunc:(e,t,n)=>{let s=t[0],{paddings:r}=n,a=r.map(o=>o[0]);return{x:()=>_e(e,a,s.shape)}}},sz={kernelName:Ya,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{let[n,s,r]=t,a=n,o=s,i=St(a.shape,o.shape);return{a:()=>{let u=de(o,"float32"),d=W(e,W(u,Io(a,ye(u,Ee(1))))),p=an(a.shape,i);return p.length>0&&(d=Ie(d,p)),G(d,a.shape)},b:()=>{let u=ms(a,0),d=Wn(u,Ns(a),tt(a)),p=W(e,W(r,d)),h=an(o.shape,i);return h.length>0&&(p=Ie(p,h)),G(p,o.shape)}}}},rz={kernelName:Ja,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{let[n,s]=t,r=ms(n,0);return{x:()=>Wn(r,e,W(e,s)),alpha:()=>{let a=Wn(r,tt(e),W(e,n)),o=an(s.shape,e.shape);return o.length>0&&(a=Ie(a,o)),G(a,s.shape)}}}},az={kernelName:_a,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=St(n.shape,s.shape);return{a:()=>{let i=he(e,de(s,"float32")),l=an(n.shape,r);return l.length>0?G(Ie(i,l),n.shape):i},b:()=>{let i=W(e,de(n,"float32")),l=an(s.shape,r);l.length>0&&(i=G(Ie(i,l),s.shape));let c=xt(s);return Ot(he(i,de(c,"float32")))}}}},oz={kernelName:lu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,Ot(xt(n)))}}},iz={kernelName:to,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t,s=W(Ji(n,6),Ad(n));return{x:()=>W(e,de(s,"float32"))}}},lz={kernelName:Qa,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(e,de(Ad(n),"float32"))}}},uz={kernelName:Ti,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>G(e,n.shape)}}},cz={kernelName:eo,inputsToSave:["images"],gradFunc:(e,t,n)=>{let[s]=t,r={dy:e,images:s};return{images:()=>B.runKernel(kh,r,n)}}},dz={kernelName:uu,inputsToSave:["images"],gradFunc:(e,t,n)=>{let[s]=t,r={dy:e,images:s};return{images:()=>B.runKernel(wh,r,n)}}},pz={kernelName:Ni,gradFunc:(e,t,n)=>{let{dims:s}=n,r=Us(s,e.shape);return{x:()=>Rs(e,r)}}},hz={kernelName:Ei,gradFunc:e=>({x:()=>tt(e)})},fz={kernelName:no,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>Ot(he(e,W(Io(n,1.5),2)))}}},mz={kernelName:$i,inputsToSave:["condition"],gradFunc:(e,t)=>{let[n]=t;return{condition:()=>de(tt(n),"float32"),t:()=>W(e,de(n,e.dtype)),e:()=>W(e,de(Jh(n),e.dtype))}}},gz={kernelName:cu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let s=ms(n,Ee(0)),r=Ee(Rv),a=Ee($v),o=W(e,a),i=W(W(e,r),Ts(de(n,"float32")));return Wn(s,o,i)}}}},Az={kernelName:ro,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(e,W(n,ye(Ee(1),n)))}}},yz={kernelName:du,gradFunc:e=>({x:()=>tt(e)})},xz={kernelName:so,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(qh(de(n,"float32")),e)}}},bz={kernelName:_i,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(O2(de(n,"float32")),e)}}},vz={kernelName:Di,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{begin:r,size:a}=n,o=s.shape,[i,l]=c3(s,r,a),c=[];for(let u=0;uqs(e,c)}}},wz={kernelName:io,outputsToSave:[!0],gradFunc:(e,t,n)=>{let[s]=t,{dim:r}=n,a=!0,o=W(e,s);return{logits:()=>ye(o,W(Ie(o,[r],a),s))}}},kz={kernelName:pu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(e,hs(n))}}},Wv={kernelName:Pi,gradFunc:(e,t,n)=>{let{blockShape:s,paddings:r}=n;return{x:()=>jh(e,s,r)}}},Vv={kernelName:Fi,gradFunc:(e,t,n)=>{let{axis:s}=n;return{x:()=>It(e,s)}}},Iz={kernelName:ao,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,W(_n(de(n,"float32")),2))}}},Sz={kernelName:hu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(e,W(de(n,"float32"),2))}}},Cz={kernelName:lo,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=Ee(2);return{a:()=>W(e,W(r,ye(n,s))),b:()=>W(e,W(r,ye(s,n)))}}},Tz={kernelName:ho,gradFunc:e=>({x:()=>tt(e)})},Nz={kernelName:uo,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=St(n.shape,s.shape);return{a:()=>{let i=e,l=an(n.shape,r);return l.length>0&&(i=Ie(i,l)),G(i,n.shape)},b:()=>{let i=e,l=an(s.shape,r);return l.length>0&&(i=Ie(i,l)),G(Ot(i),s.shape)}}}},Ez={kernelName:oo,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,r=s.shape.slice(),{axis:a}=n;Us(a,s.shape).forEach(c=>{r[c]=1});let i=G(e,r),l=W(i,gs(s.shape,"float32"));return{x:()=>l}}},Rz={kernelName:Mi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,xt(qh(n)))}}},$z={kernelName:co,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(ye(Ee(1),xt(n)),e)}}},Dz={kernelName:qr,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{reps:r}=n;return{x:()=>{let o=tt(s);if(s.rank===1)for(let i=0;i{let s=n,{perm:r}=s,a=V2(r);return{x:()=>et(e,a)}}},Pz={kernelName:Bi,gradFunc:(e,t,n)=>{let s=n,{axis:r}=s;return{value:()=>Pn(e,r)}}},Fz={kernelName:Xc,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>Oz(e,n)}}};function Oz(e,t){let n=Yr(t,tt(t)),s=Su(e,n),r=Yi(t,Ee(0,"int32")),a=s.rank-r.rank;for(let i=0;i({x:()=>tt(e)})},zz=[Fv,zO,LO,BO,WO,VO,UO,GO,HO,jO,qO,XO,YO,eM,tM,nM,sM,rM,aM,oM,iM,lM,cM,uM,hM,fM,mM,gM,AM,yM,az,xM,bM,vM,wM,kM,SM,IM,CM,TM,NM,EM,RM,$M,DM,_M,PM,FM,OM,LM,Lv,Lv,BM,UM,jM,qM,XM,KM,ZM,YM,JM,QM,ez,tz,nz,Bv,Bv,sz,rz,oz,iz,lz,uz,cz,dz,pz,hz,fz,mz,gz,Az,yz,xz,bz,vz,wz,kz,Wv,Wv,Vv,Vv,Iz,Cz,Sz,Tz,Nz,Ez,Rz,$z,Dz,_z,Pz,Fz,Mz];for(let e of zz)A5(e);var Uv={};ze(Uv,{maxNorm:()=>Vz,minMaxNorm:()=>Hz,nonNeg:()=>Gz,unitNorm:()=>Uz});var p1;function on(){return p1==null&&(p1=Tr().epsilon()),p1}function cr(){return"channelsLast"}var ea=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,ea.prototype)}},dr=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,dr.prototype)}},q=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,q.prototype)}},Be=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Be.prototype)}},Gv=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Gv.prototype)}};function nl(e,t){if(Array.isArray(e)){let n=[];for(let s=0;sn.toUpperCase())}var Ks={};function h1(e){if(e==null)return null;let t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function f1(e){if(!(e==null||typeof e!="object"))if(Array.isArray(e))e.forEach(t=>f1(t));else{let t=Object.keys(e);for(let n of t){let s=e[n];s!=null&&typeof s=="object"&&(!Array.isArray(s)&&s.type==="ndarray"&&typeof s.value=="number"?e[n]=s.value:f1(s))}}}function bd(e,t={},n={},s="object",r=!1){if(typeof e=="string"){let a=e,o;if(a in n)o=n[a];else if(a in Ks)o=Ks[a];else if(o=t[a],o==null)throw new q(`Unknown ${s}: ${e}. This may be due to one of the following reasons: + ${a.shape}`);let o={data:s,indices:r,segmentIds:a};return B.runKernel(Th,o)}var HF=V({sparseSegmentSum_:GF});function jF(e,t,n,s,r,a,o,i){let l=_(e,"data","stringNGrams","string");if(l.dtype!=="string")throw new Error("Data must be of datatype string");if(l.shape.length!==1)throw new Error(`Data must be a vector, saw: ${l.shape}`);let c=_(t,"dataSplits","stringNGrams");if(c.dtype!=="int32")throw new Error("Data splits must be of datatype int32");let u={separator:n,nGramWidths:s,leftPad:r,rightPad:a,padWidth:o,preserveShortSequences:i},d={data:l,dataSplits:c},p=B.runKernel(qc,d,u);return{nGrams:p[0],nGramsSplits:p[1]}}var qF=V({stringNGrams_:jF});function XF(e,t,n=!0){let s=_(e,"input","stringSplit","string"),r=_(t,"delimiter","stringSplit","string");if(s.rank!==1)throw new Error(`Input should be Tensor1D but received shape ${s.shape}`);if(r.rank!==0)throw new Error(`Delimiter should be a scalar but received shape ${r.shape}`);let a={skipEmpty:n},o={input:s,delimiter:r},i=B.runKernel(Nh,o,a);return{indices:i[0],values:i[1],shape:i[2]}}var KF=V({stringSplit_:XF});function ZF(e,t){let n=_(e,"input","stringToHashBucketFast","string"),s={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");let r={input:n};return B.runKernel(Eh,r,s)}var YF=V({stringToHashBucketFast_:ZF}),JF={fft:af,ifft:gd,rfft:of,irfft:t1},QF={hammingWindow:TP,hannWindow:vv,frame:wv,stft:$P},$e={flipLeftRight:FP,grayscaleToRGB:MP,resizeNearestNeighbor:iF,resizeBilinear:aF,rotateWithOffset:LP,cropAndResize:_P,nonMaxSuppression:WP,nonMaxSuppressionAsync:KP,nonMaxSuppressionWithScore:YP,nonMaxSuppressionWithScoreAsync:QP,nonMaxSuppressionPadded:tF,nonMaxSuppressionPaddedAsync:sF,threshold:cF,transform:pF},Nv={bandPart:fF,gramSchmidt:gF,qr:yF},eO={absoluteDifference:vF,computeWeightedLoss:Jr,cosineDistance:kF,hingeLoss:SF,huberLoss:TF,logLoss:EF,meanSquaredError:$F,sigmoidCrossEntropy:PF,softmaxCrossEntropy:MF},yd={sparseFillEmptyRows:LF,sparseReshape:WF,sparseSegmentMean:UF,sparseSegmentSum:HF},hf={stringNGrams:qF,stringSplit:KF,stringToHashBucketFast:YF},Qr=class extends d3{minimize(e,t=!1,n){let{value:s,grads:r}=this.computeGradients(e,n);if(n!=null){let a=n.map(o=>({name:o.name,tensor:r[o.name]}));this.applyGradients(a)}else this.applyGradients(r);return Q(r),t?s:(s.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return X3(e,t)}dispose(){this.iterations_!=null&&Q(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:Ee(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(Qr,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});var ff=class extends Qr{constructor(e,t,n=null){super();this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],n==null&&(this.epsilon=B.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,s)=>{let r=B.registeredVariables[n],a=!1;this.accumulatedGrads[s]==null&&(this.accumulatedGrads[s]={originalName:`${n}/accum_grad`,variable:j(()=>tt(r).variable(a))}),this.accumulatedUpdates[s]==null&&(this.accumulatedUpdates[s]={originalName:`${n}/accum_var`,variable:j(()=>tt(r).variable(a))});let o=Array.isArray(e)?e[s].tensor:e[n];if(o==null)return;let i=this.accumulatedGrads[s].variable,l=this.accumulatedUpdates[s].variable;j(()=>{let c=ie(W(i,this.rho),W(xt(o),1-this.rho)),u=W(fe(_n(ie(l,this.epsilon)),_n(ie(i,this.epsilon))),o),d=ie(W(l,this.rho),W(xt(u),1-this.rho));i.assign(c),l.assign(d);let p=ie(W(u,-this.learningRate),r);r.assign(p)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(Q(this.accumulatedGrads.map(e=>e.variable)),Q(this.accumulatedUpdates.map(e=>e.variable)))}async getWeights(){let 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);let t=e.length/2,n=!1;this.accumulatedGrads=e.slice(0,t).map(s=>({originalName:s.name,variable:s.tensor.variable(n)})),this.accumulatedUpdates=e.slice(t,t*2).map(s=>({originalName:s.name,variable:s.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)}};ff.className="Adadelta";vo(ff);var mf=class extends Qr{constructor(e,t=.1){super();this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,s)=>{let r=B.registeredVariables[n];if(this.accumulatedGrads[s]==null){let i=!1;this.accumulatedGrads[s]={originalName:`${n}/accumulator`,variable:j(()=>Iu(r.shape,this.initialAccumulatorValue).variable(i))}}let a=Array.isArray(e)?e[s].tensor:e[n];if(a==null)return;let o=this.accumulatedGrads[s].variable;j(()=>{let i=ie(o,xt(a));o.assign(i);let l=ie(W(fe(a,_n(ie(i,B.backend.epsilon()))),-this.learningRate),r);r.assign(l)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&Q(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);let 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)}};mf.className="Adagrad";vo(mf);var gf=class extends Qr{constructor(e,t,n,s=null){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=s,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],j(()=>{this.accBeta1=Ee(t).variable(),this.accBeta2=Ee(n).variable()}),s==null&&(this.epsilon=B.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);j(()=>{let n=xe(1,this.accBeta1),s=xe(1,this.accBeta2);t.forEach((r,a)=>{let o=B.registeredVariables[r],i=!1;this.accumulatedFirstMoment[a]==null&&(this.accumulatedFirstMoment[a]={originalName:`${r}/m`,variable:j(()=>tt(o).variable(i))}),this.accumulatedSecondMoment[a]==null&&(this.accumulatedSecondMoment[a]={originalName:`${r}/v`,variable:j(()=>tt(o).variable(i))});let l=Array.isArray(e)?e[a].tensor:e[r];if(l==null)return;let c=this.accumulatedFirstMoment[a].variable,u=this.accumulatedSecondMoment[a].variable,d=ie(W(c,this.beta1),W(l,1-this.beta1)),p=ie(W(u,this.beta2),W(xt(l),1-this.beta2)),h=fe(d,n),f=fe(p,s);c.assign(d),u.assign(p);let m=ie(W(fe(h,ie(_n(f),this.epsilon)),-this.learningRate),o);o.assign(m)}),this.accBeta1.assign(W(this.accBeta1,this.beta1)),this.accBeta2.assign(W(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&Q(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&Q(this.accumulatedSecondMoment.map(e=>e.variable))}async getWeights(){let 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),j(()=>{this.accBeta1.assign(Io(this.beta1,this.iterations_+1)),this.accBeta2.assign(Io(this.beta2,this.iterations_+1))});let t=e.length/2,n=!1;this.accumulatedFirstMoment=e.slice(0,t).map(s=>({originalName:s.name,variable:s.tensor.variable(n)})),this.accumulatedSecondMoment=e.slice(t,t*2).map(s=>({originalName:s.name,variable:s.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)}};gf.className="Adam";vo(gf);var Af=class extends Qr{constructor(e,t,n,s=null,r=0){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=s,this.decay=r,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],j(()=>{this.iteration=Ee(0).variable(),this.accBeta1=Ee(t).variable()}),s==null&&(this.epsilon=B.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);j(()=>{let n=xe(1,this.accBeta1),s=fe(-this.learningRate,ie(W(this.iteration,this.decay),1));t.forEach((r,a)=>{let o=B.registeredVariables[r],i=!1;this.accumulatedFirstMoment[a]==null&&(this.accumulatedFirstMoment[a]={originalName:`${r}/m`,variable:tt(o).variable(i)}),this.accumulatedWeightedInfNorm[a]==null&&(this.accumulatedWeightedInfNorm[a]={originalName:`${r}/v`,variable:tt(o).variable(i)});let l=Array.isArray(e)?e[a].tensor:e[r];if(l==null)return;let c=this.accumulatedFirstMoment[a].variable,u=this.accumulatedWeightedInfNorm[a].variable,d=ie(W(c,this.beta1),W(l,1-this.beta1)),p=W(u,this.beta2),h=rn(l),f=Yr(p,h);c.assign(d),u.assign(f);let m=ie(W(fe(s,n),fe(d,ie(f,this.epsilon))),o);o.assign(m)}),this.iteration.assign(ie(this.iteration,1)),this.accBeta1.assign(W(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&Q(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&Q(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)}};Af.className="Adamax";vo(Af);var xd=class extends Qr{constructor(e){super();this.learningRate=e,this.setLearningRate(e)}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,s)=>{let r=Array.isArray(e)?e[s].tensor:e[n];if(r==null)return;let a=B.registeredVariables[n];j(()=>{let o=ie(W(this.c,r),a);a.assign(o)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=yn(Ee(-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)}};xd.className="SGD";vo(xd);var yf=class extends xd{constructor(e,t,n=!1){super(e);this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=Ee(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,s)=>{let r=B.registeredVariables[n];if(this.accumulations[s]==null){let i=!1;this.accumulations[s]={originalName:`${n}/momentum`,variable:j(()=>tt(r).variable(i))}}let a=this.accumulations[s].variable,o=Array.isArray(e)?e[s].tensor:e[n];o!=null&&j(()=>{let i,l=ie(W(this.m,a),o);this.useNesterov?i=ie(W(this.c,ie(o,W(l,this.m))),r):i=ie(W(this.c,l),r),a.assign(l),r.assign(i)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&Q(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);let 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)}};yf.className="Momentum";vo(yf);var xf=class extends Qr{constructor(e,t=.9,n=0,s=null,r=!1){super();if(this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=s,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=r,s==null&&(this.epsilon=B.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,s)=>{let r=B.registeredVariables[n],a=!1;this.accumulatedMeanSquares[s]==null&&(this.accumulatedMeanSquares[s]={originalName:`${n}/rms`,variable:j(()=>tt(r).variable(a))}),this.accumulatedMoments[s]==null&&(this.accumulatedMoments[s]={originalName:`${n}/momentum`,variable:j(()=>tt(r).variable(a))}),this.accumulatedMeanGrads[s]==null&&this.centered&&(this.accumulatedMeanGrads[s]={originalName:`${n}/mg`,variable:j(()=>tt(r).variable(a))});let o=Array.isArray(e)?e[s].tensor:e[n];if(o==null)return;let i=this.accumulatedMeanSquares[s].variable,l=this.accumulatedMoments[s].variable;j(()=>{let c=ie(W(i,this.decay),W(xt(o),1-this.decay));if(this.centered){let u=this.accumulatedMeanGrads[s].variable,d=ie(W(u,this.decay),W(o,1-this.decay)),p=fe(W(o,this.learningRate),_n(xe(c,ie(xt(d),this.epsilon)))),h=ie(W(l,this.momentum),p);i.assign(c),u.assign(d),l.assign(h);let f=xe(r,h);r.assign(f)}else{let u=ie(W(i,this.decay),W(xt(o),1-this.decay)),d=ie(W(l,this.momentum),fe(W(o,this.learningRate),_n(ie(u,this.epsilon))));i.assign(u),l.assign(d);let p=xe(r,d);r.assign(p)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&Q(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&Q(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&Q(this.accumulatedMoments.map(e=>e.variable))}async getWeights(){let 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);let t=this.centered?e.length/3:e.length/2,n=!1;this.accumulatedMeanSquares=e.slice(0,t).map(s=>({originalName:s.name,variable:s.tensor.variable(n)})),this.accumulatedMoments=e.slice(t,t*2).map(s=>({originalName:s.name,variable:s.tensor.variable(n)})),this.centered&&(this.accumulatedMeanGrads=e.slice(t*2,t*3).map(s=>({originalName:s.name,variable:s.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)}};xf.className="RMSProp";vo(xf);var el=class{static sgd(e){return new xd(e)}static momentum(e,t,n=!1){return new yf(e,t,n)}static rmsprop(e,t=.9,n=0,s=null,r=!1){return new xf(e,t,n,s,r)}static adam(e=.001,t=.9,n=.999,s=null){return new gf(e,t,n,s)}static adadelta(e=.001,t=.95,n=null){return new ff(e,t,n)}static adamax(e=.002,t=.9,n=.999,s=null,r=0){return new Af(e,t,n,s,r)}static adagrad(e,t=.1){return new mf(e,t)}},tl={sgd:el.sgd,momentum:el.momentum,adadelta:el.adadelta,adagrad:el.adagrad,rmsprop:el.rmsprop,adamax:el.adamax,adam:el.adam},tO=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:e=>e())();function Ev(){return new Promise(e=>tO(()=>e()))}var N={};ze(N,{ERF_A1:()=>pO,ERF_A2:()=>hO,ERF_A3:()=>fO,ERF_A4:()=>mO,ERF_A5:()=>gO,ERF_P:()=>dO,PARALLELIZE_THRESHOLD:()=>c1,SELU_SCALE:()=>$v,SELU_SCALEALPHA:()=>Rv,applyActivation:()=>df,assertAndGetBroadcastShape:()=>St,assertAxesAreInnerMostDims:()=>hD,assertParamsConsistent:()=>nO,assignToTypedArray:()=>wO,axesAreInnerMostDims:()=>W2,calculateShapes:()=>Q5,checkEinsumDimSizes:()=>NO,combineLocations:()=>K3,complexWithEvenIndex:()=>xO,complexWithOddIndex:()=>bO,computeConv2DInfo:()=>ld,computeConv3DInfo:()=>C3,computeDefaultPad:()=>N2,computeDilation2DInfo:()=>DR,computeOptimalWindowSize:()=>rO,computeOutAndReduceShapes:()=>Z3,computeOutShape:()=>sO,computePool2DInfo:()=>S3,computePool3DInfo:()=>_R,convertConv2DDataFormat:()=>T3,decodeEinsumEquation:()=>CO,eitherStridesOrDilationsAreOne:()=>Nr,expandShapeToKeepDim:()=>Qi,exponent:()=>IO,exponents:()=>kO,fromStringArrayToUint8:()=>MO,fromUint8ToStringArray:()=>OO,getAxesPermutation:()=>Y3,getBroadcastDims:()=>I$,getComplexWithIndex:()=>vO,getEinsumComputePath:()=>EO,getEinsumPermutation:()=>TO,getFusedBiasGradient:()=>cf,getFusedDyActivation:()=>uf,getImageCenter:()=>aO,getInnerMostAxes:()=>fD,getPermuted:()=>iO,getReductionAxes:()=>an,getReshaped:()=>oO,getReshapedPermuted:()=>lO,getSliceBeginCoords:()=>uO,getSliceSize:()=>cO,getUndoAxesPermutation:()=>V2,isIdentityPermutation:()=>RO,log:()=>aE,mergeRealAndImagArrays:()=>AO,prepareAndValidate:()=>J5,prepareSplitSize:()=>DO,segment_util:()=>Pv,shouldFuse:()=>pf,slice_util:()=>An,splitRealAndImagArrays:()=>yO,tupleValuesAreOne:()=>wo,upcastType:()=>Bn,validateInput:()=>b2,validateUpdateShape:()=>x2,warn:()=>kr});function nO(e,t){let n=e[0].length;e.forEach((r,a)=>{O(r.length===n,()=>`Error in concat${n}D: rank of tensors[${a}] must be the same as the rank of the rest (${n})`)}),O(t>=0&&t`Error in concat${n}D: axis must be between 0 and ${n-1}.`);let s=e[0];e.forEach((r,a)=>{for(let o=0;o`Error in concat${n}D: Shape of tensors[${a}] (${r}) does not match the shape of the rest (${s}) along the non-concatenated axis ${a}.`)})}function sO(e,t){let n=e[0].slice();for(let s=1;s=t*2+1||o%2==1?a.push(o):r.push(o);s.push(...r),s.push(0),s.push(...a)}return s}function lO(e,t,n,s=!0){let r=[];s?r.push(e[0]/n):r.push(e[0]*n);for(let a=1;a/g,Dv=",",_v="...";function CO(e,t){e=e.replace(/\s/g,"");let n=(e.length-e.replace(SO,"").length)/d1.length;if(n<1)throw new Error("Equations without an arrow are not supported.");if(n>1)throw new Error(`Equation must contain exactly one arrow ("${d1}").`);let[s,r]=e.split(d1);O(s.indexOf(_v)===-1,()=>`The ellipsis notation ("${_v}") is not supported yet.`);let a=s.split(Dv),o=a.length;if(t!==o)throw new Error(`Expected ${o} input tensors, received ${t}`);if(o>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");let i=[];for(let p=0;pf.indexOf(h)!==-1))throw new Error(`Output subscripts contain the label ${h} not present in the input subscripts.`);i.indexOf(h)===-1&&i.push(h)}for(let p=0;pr!==-1),{permutationIndices:n,expandDims:s}}function NO(e,t,n){let s=new Array(e);for(let r=0;r`Expected dimension ${s[t[r][o]]} at axis ${o} of input shaped ${JSON.stringify(a)}, but got dimension ${a[o]}`)}}function EO(e,t){let n=e,s=[],r=0;e.length===0&&n.push(-1),r=e.length+1;for(let o=0;ot===n)}function $O(e,t){let n=[];for(let s=0;s"Number of splits must evenly divide the axis."),s=new Array(t).fill(e.shape[n]/t);else{let r=t.reduce((o,i)=>(i===-1&&(o+=1),o),0);O(r<=1,()=>"There should be only one negative value in split array.");let a=t.indexOf(-1);if(a!==-1){let o=t.reduce((i,l)=>l>0?i+l:i);t[a]=e.shape[n]-o}O(e.shape[n]===t.reduce((o,i)=>o+i),()=>"The sum of sizes must match the size of the axis dimension."),s=t}return s}var Pv={};ze(Pv,{collectGatherOpShapeInfo:()=>FO,computeOutShape:()=>PO,segOpComputeOptimalWindowSize:()=>_O});function _O(e,t){let n=!1,s;for(e<=c1?(s=e,n=!0):s=Jp(e,Math.floor(Math.sqrt(e)));!n;)s>t||s===e?n=!0:s=Jp(e,s+1);return s}function PO(e,t,n){let s=[],r=e.length;for(let a=0;ar))throw new Error(`Expect batchDims in the range of [-${r}, ${r}], but got ${s}`);if(s<0&&(s+=r),s>a)throw new Error(`batchDims (${s}) must be less than rank(x) ( + ${a}).`);if(nPh(t))}catch(t){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${t}`)}}function MO(e){return e.map(t=>Qc(t))}var Xs={};ze(Xs,{nonMaxSuppressionV3Impl:()=>kv,nonMaxSuppressionV4Impl:()=>Iv,nonMaxSuppressionV5Impl:()=>Sv,whereImpl:()=>hv});var Fv={kernelName:ni,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(e,Ad(he(n,"float32"),-1))}}},zO={kernelName:Vl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let s=xt(he(n,"float32")),r=_n(xe(Ee(1),s));return Ot(fe(e,r))}}}},LO={kernelName:Ul,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let s=_n(xe(xt(he(n,"float32")),1));return fe(e,s)}}}},BO={kernelName:Hr,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=St(n.shape,s.shape);return{a:()=>{let i=e,l=an(n.shape,r);return l.length>0&&(i=Ie(i,l)),G(i,n.shape)},b:()=>{let i=e,l=an(s.shape,r);return l.length>0&&(i=Ie(i,l)),G(i,s.shape)}}}},WO={kernelName:wa,saveAllInputs:!0,gradFunc:(e,t)=>{let n={};return t.forEach((s,r)=>{n[r]=()=>e.clone()}),n}},VO={kernelName:ka,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>tt(n)}}},UO={kernelName:jl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>tt(n)}}},GO={kernelName:ql,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>fe(e,_n(xe(Ee(1),xt(he(n,"float32")))))}}},HO={kernelName:Xl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let s=_n(ie(Ee(1),xt(he(n,"float32"))));return fe(e,s)}}}},jO={kernelName:Yl,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=St(n.shape,s.shape);return{a:()=>{let i=ie(xt(n),xt(s)),l=W(e,fe(s,i)),c=an(n.shape,r);return c.length>0&&(l=Ie(l,c)),G(l,n.shape)},b:()=>{let i=ie(xt(n),xt(s)),l=Ot(W(e,fe(n,i))),c=an(s.shape,r);return c.length>0&&(l=Ie(l,c)),G(l,s.shape)}}}},qO={kernelName:Kl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>fe(e,ie(xt(he(n,"float32")),1))}}},XO={kernelName:Zl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>fe(e,xe(Ee(1),xt(he(n,"float32"))))}}};function KO(e,t,n,s,r,a){let o=_(e,"dy","avgPool3dGrad"),i=_(t,"input","avgPool3dGrad"),l=o,c=i,u=!1;i.rank===4&&(u=!0,l=G(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),c=G(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),O(l.rank===5,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${l.rank}.`),O(c.rank===5,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${c.rank}.`),a!=null&&O(mn(r),()=>`Error in avgPool3dGrad: pad must be an integer when using, dimRoundingMode ${a} but got pad ${r}.`);let d={dy:l,input:c},p={filterSize:n,strides:s,pad:r,dimRoundingMode:a},h=B.runKernel(th,d,p);return u?G(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}var ZO=V({avgPool3dGrad_:KO}),YO={kernelName:Fc,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{filterSize:r,strides:a,pad:o,dimRoundingMode:i}=n;return{x:()=>ZO(e,s,r,a,o,i)}}};function JO(e,t,n,s,r){let a=_(e,"dy","avgPoolGrad"),o=_(t,"input","avgPoolGrad");O(o.rank===a.rank,()=>`Rank of input (${o.rank}) does not match rank of dy (${a.rank})`);let i=o,l=a,c=!1;o.rank===3&&(c=!0,i=G(o,[1,o.shape[0],o.shape[1],o.shape[2]]),l=G(a,[1,a.shape[0],a.shape[1],a.shape[2]])),O(l.rank===4,()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${l.rank}.`),O(i.rank===4,()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${i.rank}.`);let u={dy:l,input:i},d={filterSize:n,strides:s,pad:r},p=B.runKernel(eh,u,d);return c?G(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var QO=V({avgPoolGrad_:JO}),eM={kernelName:Ia,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{filterSize:r,strides:a,pad:o}=n;return{x:()=>QO(e,s,r,a,o)}}},tM={kernelName:Sa,inputsToSave:["a","b"],gradFunc:(e,t,n)=>{let[s,r]=t,{transposeA:a,transposeB:o}=n;return!a&&!o?{a:()=>He(e,r,!1,!0),b:()=>He(s,e,!0,!1)}:!a&&o?{a:()=>He(e,r,!1,!1),b:()=>He(e,s,!0,!1)}:a&&!o?{a:()=>He(r,e,!1,!0),b:()=>He(s,e,!1,!1)}:{a:()=>He(r,e,!0,!0),b:()=>He(e,s,!0,!0)}}},nM={kernelName:si,gradFunc:(e,t,n)=>{let{blockShape:s,crops:r}=n;return{x:()=>nf(e,s,r)}}},sM={kernelName:m5,gradFunc:(e,t,n)=>{let s=n,r=s.inputShape,a=s.shape,o=Array.from(a);for(let l=r.length-1;l>=0;l--)if(r[l]===a[l])o[l]=1;else if(r[l]!==1)throw new Error(`broadcastTo(): [${r}] cannot be broadcast to [${a}].`);let i=[];for(let l=0;l1&&i.push(l);return{x:()=>Ie(e,i,!0)}}},rM={kernelName:Ca,gradFunc:e=>({x:()=>e.clone()})},aM={kernelName:Ta,gradFunc:e=>({x:()=>tt(e)})},oM={kernelName:jr,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{clipValueMin:r,clipValueMax:a}=n;return{x:()=>Wn(lr(Yi(s,r),Ji(s,a)),e,tt(e))}}},iM={kernelName:Mc,inputsToSave:["x"],gradFunc:Fv.gradFunc},lM={kernelName:ri,saveAllInputs:!0,gradFunc:(e,t,n)=>{let s=t.map(l=>l.shape),{axis:r}=n,a=Us(r,t[0].shape)[0],o=s.map(l=>l[a]);return Sn(e,o,a).map(l=>()=>l)}},uM={kernelName:Na,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let[s,r]=t,{dilations:a,strides:o,pad:i,dataFormat:l}=n;return O(wo(a),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`),{x:()=>_2(s.shape,e,r,o,i,l),filter:()=>l1(s,e,r.shape,o,i,l)}}},cM={kernelName:Ea,inputsToSave:["dy","filter"],gradFunc:(e,t,n)=>{let[s,r]=t,{strides:a,pad:o,dataFormat:i,dimRoundingMode:l}=n;return{dy:()=>ko(e,r,a,o,i,1,l),filter:()=>l1(e,s,r.shape,a,o,i,l)}}};function dM(e,t,n,s,r){let a=e;e.rank===4&&(a=G(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let o=t;o.rank===4&&(o=G(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),O(a.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${a.shape}.`),O(o.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${o.shape}.`),O(n.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${n}.`),O(a.shape[4]===n[3],()=>`Error in conv3dDerFilter: depth of input ${a.shape[4]}) must match input depth in filter (${n[3]}.`),O(o.shape[4]===n[4],()=>`Error in conv3dDerFilter: depth of dy (${o.shape[4]}) must match output depth for filter (${n[4]}).`);let i={x:a,dy:o},l={strides:s,pad:r,filterShape:n};return B.runKernel(ah,i,l)}var pM=V({conv3DBackpropFilter_:dM}),hM={kernelName:zc,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let{dilations:s,strides:r,pad:a}=n;O(wo(s),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);let[o,i]=t;return{x:()=>O3(o.shape,e,i,r,a),filter:()=>pM(o,e,i.shape,r,a)}}},fM={kernelName:Ra,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(Ot(J2(he(n,"float32"))),e)}}},mM={kernelName:$a,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(Q2(he(n,"float32")),e)}}},gM={kernelName:ai,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{axis:r,exclusive:a,reverse:o}=n;return{x:()=>{let i=Y3([r],s.rank),l=M2(e,r,a,!o);return i!=null&&(l=et(l,i)),l}}}},AM={kernelName:Da,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let{dilations:s,strides:r,pad:a,dimRoundingMode:o}=n,i=s==null?[1,1]:s;O(wo(i),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${i}'`);let[l,c]=t;return O(l.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`),O(c.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${c.rank}.`),O(l.shape[3]===c.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${l.shape[3]}) must match the inChannels dimension in filter ${c.shape[2]}.`),O(Nr(r,i),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${r} and dilations '${i}'.`),o!=null&&O(mn(a),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${a}.`),{x:()=>bv(l.shape,e,c,r,a,i,o),filter:()=>xv(l,e,c.shape,r,a,i,o)}}},yM={kernelName:Lc,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let[s,r]=t,a={x:s,filter:r,dy:e},o={x:s,filter:r,dy:e};return{x:()=>B.runKernel(dh,a,n),filter:()=>B.runKernel(ph,o,n)}}},xM={kernelName:Pa,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t,s={dy:e,y:n};return{x:()=>B.runKernel(hh,s)}}},bM={kernelName:Jl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t,s=W(Ts(Ot(xt(n))),2/Math.sqrt(Math.PI));return{x:()=>W(e,s)}}},vM={kernelName:Fa,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(e,n)}}},wM={kernelName:ui,inputsToSave:["input"],gradFunc:(e,t)=>{let[n]=t;return{input:()=>G(e,n.shape)}}},kM={kernelName:ci,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(e,Ts(n))}}},IM={kernelName:Oa,gradFunc:e=>({x:()=>tt(e)})},SM={kernelName:Ma,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=St(n.shape,s.shape);return{a:()=>{let i=fe(e,he(s,"float32")),l=an(n.shape,r);return l.length>0?G(Ie(i,l),n.shape):i},b:()=>{let i=W(e,he(n,"float32")),l=an(s.shape,r);l.length>0&&(i=G(Ie(i,l),s.shape));let c=xt(s);return Ot(fe(i,he(c,"float32")))}}}},CM={kernelName:za,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{let{varianceEpsilon:s}=n,[r,a,o,i]=t,l=i==null?Ee(1):i,c=an(a.shape,r.shape),u=[];if(a.rank===1){for(let b=0;ba.rank===1?G(W(W(e,js(G(h,[1,1,1,a.shape[0]]),u)),l),r.shape):G(W(W(e,h),l),r.shape),mean:()=>{let b=W(W(h,Ee(-1)),p);return a.rank===1&&(b=Ie(b,c)),G(b,a.shape)},variance:()=>{let b=W(W(f,d),p);return a.rank===1&&(b=Ie(b,c)),G(b,a.shape)},scale:()=>{let b=W(d,h),w=W(e,b);return a.rank===1&&(w=Ie(w,c)),G(w,a.shape)},offset:()=>{let b=e;return a.rank===1&&(b=Ie(b,c)),G(b,a.shape)}}}},TM={kernelName:pi,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{let[s,r]=t,{axis:a}=n,o=Us(a,s.shape)[0];return{x:()=>{let l=s.shape,c=r.size,u=l.slice(0,o),d=u.length,p=l.slice(a,l.length).slice(1),h=p.length,f=Ov(0,d),m=Ov(d+1,d+1+h),g=Mv([u,[c],p]),A=G(e,g),y=G(r,[c]),x=Mv([[d],f,m]),b=et(A,x),w=dv(b,y,s.shape[o]),k=V2(x);return w=et(w,k),w},indices:()=>r}}};function Ov(e,t){let n=[];for(let s=e;s{let[n,s]=t;return{a:()=>tt(n),b:()=>tt(s)}}},EM={kernelName:Ba,gradFunc:e=>({x:()=>he(e,"float32")})},RM={kernelName:eu,gradFunc:e=>({x:()=>tt(e)})},$M={kernelName:tu,gradFunc:e=>({x:()=>tt(e)})},DM={kernelName:nu,gradFunc:e=>({x:()=>tt(e)})},_M={kernelName:mi,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{alpha:r}=n,a=ms(s,0);return{x:()=>Wn(a,e,W(e,r))}}},PM={kernelName:su,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>fe(e,ie(n,1))}}},FM={kernelName:Wa,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>fe(e,he(n,"float32"))}}},OM={kernelName:g5,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[s]=t,{axis:r}=n;return{logits:()=>{let a=!0,o=Ts(s);return xe(e,W(Ie(e,r,a),o))}}}};function MM(e,t,n,s=5,r=1,a=1,o=.5){let i={x:e,y:t,dy:n},l={depthRadius:s,bias:r,alpha:a,beta:o};return B.runKernel(Ah,i,l)}var zM=V({localResponseNormalizationBackprop_:MM}),LM={kernelName:Uc,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[s,r]=t,{depthRadius:a,bias:o,alpha:i,beta:l}=n;return{x:()=>zM(s,r,e,a,o,i,l)}}};function zv(e,t,n,s){return t.rankW(e,he(Cs(n,t),e.dtype))}}var Lv={kernelName:Va,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let s=n,{reductionIndices:r}=s,a=t[0],o=t[1],i=Us(r,a.shape),l=zv(e,o,a,i);return{x:()=>l.x()}}},BM={kernelName:Ua,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t;return{a:()=>W(e,he(Yi(n,s),"float32")),b:()=>W(e,he(L2(n,s),"float32"))}}};function WM(e,t,n,s,r,a,o){let i=_(e,"dy","maxPool3dGrad"),l=_(t,"input","maxPool3dGrad"),c=_(n,"output","maxPool3dGrad"),u=i,d=l,p=c,h=!1;l.rank===4&&(h=!0,u=G(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),d=G(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),p=G(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]])),O(u.rank===5,()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${u.rank}.`),O(d.rank===5,()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${d.rank}.`),O(p.rank===5,()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${p.rank}.`),o!=null&&O(mn(a),()=>`Error in maxPool3dGrad: pad must be an integer when using, dimRoundingMode ${o} but got pad ${a}.`);let f={dy:u,input:d,output:p},m={filterSize:s,strides:r,pad:a,dimRoundingMode:o},g=B.runKernel(xh,f,m);return h?G(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}var VM=V({maxPool3dGrad_:WM}),UM={kernelName:Gc,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[s,r]=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:l}=n;return{x:()=>VM(e,s,r,a,o,i,l)}}};function GM(e,t,n,s,r,a,o){let i=_(e,"dy","maxPoolGrad"),l=_(t,"input","maxPoolGrad"),c=_(n,"output","maxPoolGrad");O(l.rank===i.rank,()=>`Rank of input (${l.rank}) does not match rank of dy (${i.rank})`),O(i.rank===4,()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${i.rank}.`),O(l.rank===4,()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`),o!=null&&O(mn(a),()=>`Error in maxPoolGrad: pad must be an integer when using, dimRoundingMode ${o} but got pad ${a}.`);let u={dy:i,input:l,output:c},d={filterSize:s,strides:r,pad:a,dimRoundingMode:o};return B.runKernel(yh,u,d)}var HM=V({maxPoolGrad_:GM}),jM={kernelName:Ga,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[s,r]=t,{filterSize:a,strides:o,pad:i}=n;return{x:()=>HM(e,s,r,a,o,i)}}},qM={kernelName:Ha,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{axis:r}=n,a=Us(r,s.shape),i=Z3(s.shape,a)[1],l=Ut(i);return{x:()=>{let u=s.shape.slice();a.forEach(h=>{u[h]=1});let d=G(e,u);return fe(W(d,gs(s.shape,"float32")),l)}}}},XM={kernelName:ja,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let s=n,{axis:r}=s,[a,o]=t,i=Us(r,a.shape),l=zv(e,o,a,i);return{x:()=>l.x()}}},KM={kernelName:qa,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t;return{a:()=>W(e,he(Ji(n,s),"float32")),b:()=>W(e,he(ms(n,s),"float32"))}}},ZM={kernelName:Xa,inputsToSave:["x"],gradFunc:(e,t,n)=>{let s=t[0],{paddings:r}=n,a=r.map(o=>o[0]);return{x:()=>_e(e,a,s.shape)}}},YM={kernelName:au,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=St(n.shape,s.shape);return{a:()=>{let i=an(n.shape,r);return i.length>0?G(Ie(e,i),n.shape):e},b:()=>{let i=W(e,Ot(pd(fe(n,s)))),l=an(s.shape,r);return l.length>0?G(Ie(i,l),s.shape):i}}}},JM={kernelName:Ka,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=St(n.shape,s.shape);return{a:()=>{let i=W(e,he(s,"float32")),l=an(n.shape,r);return l.length>0?G(Ie(i,l),n.shape):i},b:()=>{let i=W(e,he(n,"float32")),l=an(s.shape,r);return l.length>0?G(Ie(i,l),s.shape):i}}}},QM={kernelName:xi,gradFunc:e=>({x:()=>Ot(e)})},ez={kernelName:Ii,inputsToSave:["indices"],gradFunc:(e,t)=>{let n=t[0];return{indices:()=>Ht(n.shape,"float32")}}},tz={kernelName:ki,gradFunc:e=>({x:()=>tt(e)})},nz={kernelName:Si,saveAllInputs:!0,gradFunc:(e,t,n)=>{let{axis:s}=n;return as(e,s).map(a=>()=>a)}},Bv={kernelName:Za,inputsToSave:["x"],gradFunc:(e,t,n)=>{let s=t[0],{paddings:r}=n,a=r.map(o=>o[0]);return{x:()=>_e(e,a,s.shape)}}},sz={kernelName:Ya,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{let[n,s,r]=t,a=n,o=s,i=St(a.shape,o.shape);return{a:()=>{let u=he(o,"float32"),d=W(e,W(u,Io(a,xe(u,Ee(1))))),p=an(a.shape,i);return p.length>0&&(d=Ie(d,p)),G(d,a.shape)},b:()=>{let u=ms(a,0),d=Wn(u,Ns(a),tt(a)),p=W(e,W(r,d)),h=an(o.shape,i);return h.length>0&&(p=Ie(p,h)),G(p,o.shape)}}}},rz={kernelName:Ja,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{let[n,s]=t,r=ms(n,0);return{x:()=>Wn(r,e,W(e,s)),alpha:()=>{let a=Wn(r,tt(e),W(e,n)),o=an(s.shape,e.shape);return o.length>0&&(a=Ie(a,o)),G(a,s.shape)}}}},az={kernelName:_a,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=St(n.shape,s.shape);return{a:()=>{let i=fe(e,he(s,"float32")),l=an(n.shape,r);return l.length>0?G(Ie(i,l),n.shape):i},b:()=>{let i=W(e,he(n,"float32")),l=an(s.shape,r);l.length>0&&(i=G(Ie(i,l),s.shape));let c=xt(s);return Ot(fe(i,he(c,"float32")))}}}},oz={kernelName:lu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>fe(e,Ot(xt(n)))}}},iz={kernelName:to,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t,s=W(Ji(n,6),Ad(n));return{x:()=>W(e,he(s,"float32"))}}},lz={kernelName:Qa,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(e,he(Ad(n),"float32"))}}},uz={kernelName:Ti,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>G(e,n.shape)}}},cz={kernelName:eo,inputsToSave:["images"],gradFunc:(e,t,n)=>{let[s]=t,r={dy:e,images:s};return{images:()=>B.runKernel(kh,r,n)}}},dz={kernelName:uu,inputsToSave:["images"],gradFunc:(e,t,n)=>{let[s]=t,r={dy:e,images:s};return{images:()=>B.runKernel(wh,r,n)}}},pz={kernelName:Ni,gradFunc:(e,t,n)=>{let{dims:s}=n,r=Us(s,e.shape);return{x:()=>Rs(e,r)}}},hz={kernelName:Ei,gradFunc:e=>({x:()=>tt(e)})},fz={kernelName:no,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>Ot(fe(e,W(Io(n,1.5),2)))}}},mz={kernelName:$i,inputsToSave:["condition"],gradFunc:(e,t)=>{let[n]=t;return{condition:()=>he(tt(n),"float32"),t:()=>W(e,he(n,e.dtype)),e:()=>W(e,he(Jh(n),e.dtype))}}},gz={kernelName:cu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let s=ms(n,Ee(0)),r=Ee(Rv),a=Ee($v),o=W(e,a),i=W(W(e,r),Ts(he(n,"float32")));return Wn(s,o,i)}}}},Az={kernelName:ro,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(e,W(n,xe(Ee(1),n)))}}},yz={kernelName:du,gradFunc:e=>({x:()=>tt(e)})},xz={kernelName:so,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(qh(he(n,"float32")),e)}}},bz={kernelName:_i,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(O2(he(n,"float32")),e)}}},vz={kernelName:Di,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{begin:r,size:a}=n,o=s.shape,[i,l]=c3(s,r,a),c=[];for(let u=0;uqs(e,c)}}},wz={kernelName:io,outputsToSave:[!0],gradFunc:(e,t,n)=>{let[s]=t,{dim:r}=n,a=!0,o=W(e,s);return{logits:()=>xe(o,W(Ie(o,[r],a),s))}}},kz={kernelName:pu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(e,hs(n))}}},Wv={kernelName:Pi,gradFunc:(e,t,n)=>{let{blockShape:s,paddings:r}=n;return{x:()=>jh(e,s,r)}}},Vv={kernelName:Fi,gradFunc:(e,t,n)=>{let{axis:s}=n;return{x:()=>It(e,s)}}},Iz={kernelName:ao,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>fe(e,W(_n(he(n,"float32")),2))}}},Sz={kernelName:hu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(e,W(he(n,"float32"),2))}}},Cz={kernelName:lo,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=Ee(2);return{a:()=>W(e,W(r,xe(n,s))),b:()=>W(e,W(r,xe(s,n)))}}},Tz={kernelName:ho,gradFunc:e=>({x:()=>tt(e)})},Nz={kernelName:uo,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=St(n.shape,s.shape);return{a:()=>{let i=e,l=an(n.shape,r);return l.length>0&&(i=Ie(i,l)),G(i,n.shape)},b:()=>{let i=e,l=an(s.shape,r);return l.length>0&&(i=Ie(i,l)),G(Ot(i),s.shape)}}}},Ez={kernelName:oo,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,r=s.shape.slice(),{axis:a}=n;Us(a,s.shape).forEach(c=>{r[c]=1});let i=G(e,r),l=W(i,gs(s.shape,"float32"));return{x:()=>l}}},Rz={kernelName:Mi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>fe(e,xt(qh(n)))}}},$z={kernelName:co,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(xe(Ee(1),xt(n)),e)}}},Dz={kernelName:qr,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{reps:r}=n;return{x:()=>{let o=tt(s);if(s.rank===1)for(let i=0;i{let s=n,{perm:r}=s,a=V2(r);return{x:()=>et(e,a)}}},Pz={kernelName:Bi,gradFunc:(e,t,n)=>{let s=n,{axis:r}=s;return{value:()=>Pn(e,r)}}},Fz={kernelName:Xc,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>Oz(e,n)}}};function Oz(e,t){let n=Yr(t,tt(t)),s=Su(e,n),r=Yi(t,Ee(0,"int32")),a=s.rank-r.rank;for(let i=0;i({x:()=>tt(e)})},zz=[Fv,zO,LO,BO,WO,VO,UO,GO,HO,jO,qO,XO,YO,eM,tM,nM,sM,rM,aM,oM,iM,lM,cM,uM,hM,fM,mM,gM,AM,yM,az,xM,bM,vM,wM,kM,SM,IM,CM,TM,NM,EM,RM,$M,DM,_M,PM,FM,OM,LM,Lv,Lv,BM,UM,jM,qM,XM,KM,ZM,YM,JM,QM,ez,tz,nz,Bv,Bv,sz,rz,oz,iz,lz,uz,cz,dz,pz,hz,fz,mz,gz,Az,yz,xz,bz,vz,wz,kz,Wv,Wv,Vv,Vv,Iz,Cz,Sz,Tz,Nz,Ez,Rz,$z,Dz,_z,Pz,Fz,Mz];for(let e of zz)A5(e);var Uv={};ze(Uv,{maxNorm:()=>Vz,minMaxNorm:()=>Hz,nonNeg:()=>Gz,unitNorm:()=>Uz});var p1;function on(){return p1==null&&(p1=Tr().epsilon()),p1}function cr(){return"channelsLast"}var ea=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,ea.prototype)}},dr=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,dr.prototype)}},q=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,q.prototype)}},Be=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Be.prototype)}},Gv=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Gv.prototype)}};function nl(e,t){if(Array.isArray(e)){let n=[];for(let s=0;sn.toUpperCase())}var Ks={};function h1(e){if(e==null)return null;let t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function f1(e){if(!(e==null||typeof e!="object"))if(Array.isArray(e))e.forEach(t=>f1(t));else{let t=Object.keys(e);for(let n of t){let s=e[n];s!=null&&typeof s=="object"&&(!Array.isArray(s)&&s.type==="ndarray"&&typeof s.value=="number"?e[n]=s.value:f1(s))}}}function bd(e,t={},n={},s="object",r=!1){if(typeof e=="string"){let a=e,o;if(a in n)o=n[a];else if(a in Ks)o=Ks[a];else if(o=t[a],o==null)throw new q(`Unknown ${s}: ${e}. This may be due to one of the following reasons: 1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code. 2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return o}else{let a=e;if(a.className==null||a.config==null)throw new q(`${s}: Improper config format: ${JSON.stringify(a)}. 'className' and 'config' must set.`);let o=a.className,i,l;if(o in n?[i,l]=n[o]:o in Ks?[i,l]=Ks.className:o in t&&([i,l]=t[o]),i==null)throw new q(`Unknown ${s}: ${o}. This may be due to one of the following reasons: 1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code. -2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(l!=null){let c={};for(let h of Object.keys(Ks))c[h]=Ks[h];for(let h of Object.keys(n))c[h]=n[h];let u=a.config;u.customObjects=c;let d={...Ks};for(let h of Object.keys(n))Ks[h]=n[h];f1(a.config);let p=l(i,a.config,n,r);return Ks={...d},p}else{let c={...Ks};for(let d of Object.keys(n))Ks[d]=n[d];let u=new i(a.config);return Ks={...c},u}}}function Lz(e,t){return et?1:0}function bf(e,t){return-1*Lz(e,t)}function Co(e){if(e==null)return e;let t=[];for(let n of e)t.indexOf(n)===-1&&t.push(n);return t}function Bz(e){if(e==null)throw new q(`Invalid value in obj: ${JSON.stringify(e)}`);for(let t in e)if(e.hasOwnProperty(t))return!1;return!0}function rl(e,t,n){if(n!=null&&e.indexOf(n)<0)throw new q(`${n} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function m1(e,t,n=0,s=1/0){return $r(n>=0),$r(s>=n),Array.isArray(e)&&e.length>=n&&e.length<=s&&e.every(r=>typeof r===t)}function xn(e,t){Array.isArray(e)?(v.assert(e.length>0,()=>`${t} is unexpectedly an empty array.`),e.forEach((n,s)=>xn(n,`element ${s+1} of ${t}`))):v.assert(Number.isInteger(e)&&e>0,()=>`Expected ${t} to be a positive integer, but got ${jv(e)}.`)}function jv(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>jv(t)).join(",")+"]":typeof e=="string"?`"${e}"`:`${e}`}function Wz(e,t,n){let s=n!=null?n():v.now(),r;return(...o)=>{let i=n!=null?n():v.now();return i-s_n(Ie(W(e,e),t,!0)))}var vd=class extends le.Serializable{getConfig(){return{}}},A1=class extends vd{constructor(e){super();this.defaultMaxValue=2,this.defaultAxis=0,this.maxValue=e.maxValue!=null?e.maxValue:this.defaultMaxValue,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return j(()=>{let t=g1(e,this.axis),n=fs(t,0,this.maxValue);return W(e,he(n,ie(on(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}};A1.className="MaxNorm";le.registerClass(A1);var y1=class extends vd{constructor(e){super();this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return j(()=>he(e,ie(on(),g1(e,this.axis))))}getConfig(){return{axis:this.axis}}};y1.className="UnitNorm";le.registerClass(y1);var x1=class extends vd{apply(e){return Rr(e)}};x1.className="NonNeg";le.registerClass(x1);var b1=class extends vd{constructor(e){super();this.defaultMinValue=0,this.defaultMaxValue=1,this.defaultRate=1,this.defaultAxis=0,this.minValue=e.minValue!=null?e.minValue:this.defaultMinValue,this.maxValue=e.maxValue!=null?e.maxValue:this.defaultMaxValue,this.rate=e.rate!=null?e.rate:this.defaultRate,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return j(()=>{let t=g1(e,this.axis),n=ie(W(this.rate,fs(t,this.minValue,this.maxValue)),W(1-this.rate,t));return W(e,he(n,ie(on(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}};b1.className="MinMaxNorm";le.registerClass(b1);var Xv={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function ln(e){return h1(e)}function Kv(e,t={}){return bd(e,le.SerializationMap.getMap().classNameMap,t,"constraint")}function un(e){if(e==null)return null;if(typeof e=="string"){let n={className:e in Xv?Xv[e]:e,config:{}};return Kv(n)}else return e instanceof vd?e:Kv(e)}function Vz(e){return new A1(e)}function Uz(e){return new y1(e)}function Gz(){return new x1}function Hz(e){return new b1(e)}var Zv={};ze(Zv,{constant:()=>fL,glorotNormal:()=>vL,glorotUniform:()=>bL,heNormal:()=>wL,heUniform:()=>kL,identity:()=>yL,leCunNormal:()=>IL,leCunUniform:()=>SL,ones:()=>hL,orthogonal:()=>CL,randomNormal:()=>gL,randomUniform:()=>mL,truncatedNormal:()=>AL,varianceScaling:()=>xL,zeros:()=>pL});var jz=["channelsFirst","channelsLast"],qz=["nearest","bilinear"],Xz=["valid","same","causal"],Kz=["max","avg"],Zz=["sum","mul","concat","ave"],_u=new Map;function jt(e){rl(jz,"DataFormat",e)}function Yz(e){rl(qz,"InterpolationFormat",e)}function $s(e){rl(Xz,"PaddingMode",e)}function Yv(e){rl(Kz,"PoolMode",e)}var wd=[],Jv="/";function al(e,t){wd.push(e);try{let n=t();return wd.pop(),n}catch(n){throw wd.pop(),n}}function Jz(){return wd.length===0?"":wd.join(Jv)+Jv}function Qv(e){if(!tw(e))throw new Error("Not a valid tensor name: '"+e+"'");return Jz()+e}function ew(e){if(!tw(e))throw new Error("Not a valid tensor name: '"+e+"'");_u.has(e)||_u.set(e,0);let t=_u.get(e);if(_u.set(e,_u.get(e)+1),t>0){let n=`${e}_${t}`;return _u.set(n,1),n}else return e}var Qz=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function tw(e){return!!e.match(Qz)}function eL(e){return e===parseInt(e.toString(),10)}function To(e,t,n){t==null&&(t=0),n==null&&(n=e.length);let s=1;for(let r=t;rt&&(t=s)}return t}function pr(e,t){if(t{if(e.shape.length!==2)throw new q(`repeat() expects a rank-2 tensor, but received a rank-${e.shape.length} tensor.`);let n=kd(e,1);return k1(n,[1,t,1])})}function nL(e){let t=[To(e.shape)];return G(e,t)}function sL(e){if(e.rank<=1)throw new q(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);let t=[e.shape[0],To(e.shape,1)];return G(e,t)}function ol(e,t,n){return j(()=>{switch(e.rank){case 1:return rf(e,t,n);case 2:return e1(e,[t,0],[n,e.shape[1]]);case 3:return Ru(e,[t,0,0],[n,e.shape[1],e.shape[2]]);case 4:return md(e,[t,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3]]);case 5:return _e(e,[t,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return _e(e,[t,0,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4],e.shape[5]]);default:throw new q(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}})}function v1(e,t,n){return j(()=>{switch(e.rank){case 1:return rf(e,t,n);case 2:return e1(e,[0,t],[e.shape[0],n]);case 3:return Ru(e,[0,0,t],[e.shape[0],e.shape[1],n]);case 4:return md(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],n]);default:throw new q(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function wf(e,t,n,s){return j(()=>{switch(e.rank){case 1:return rf(e,t,n);case 2:switch(s){case 1:return ol(e,t,n);case 2:return v1(e,t,n);default:throw new q(`The axis is not within the rank of the tensor ${s}`)}case 3:switch(s){case 1:return ol(e,t,n);case 2:return Ru(e,[0,t,0],[e.shape[0],n,e.shape[2]]);case 3:return v1(e,t,n);default:throw new q(`The axis is not within the rank of the tensor ${s}`)}case 4:switch(s){case 1:return ol(e,t,n);case 2:return md(e,[0,t,0,0],[e.shape[0],n,e.shape[2],e.shape[3]]);case 3:return md(e,[0,0,t,0],[e.shape[0],e.shape[1],n,e.shape[3]]);case 4:return v1(e,t,n);default:throw new q(`The axis is not within the rank of the tensor ${s}`)}default:throw new q(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function w1(e,t=-1){let n;return t<0&&(n=e[0].rank,n!==0?t=n:t=0),t===e[0].rank&&(t=-1),It(e,t)}function nw(e,t){switch(e.rank){case 1:return _3([e,t]);case 2:return ku([e,t],0);case 3:return P3([e,t],0);case 4:return F3([e,t],0);default:throw new q(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function k1(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new q(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return js(e,t)}function kf(e,t=0,n=1,s,r){return sv(e,t,n,s,r)}function Dr(e,t,n,s){if(e.rank<2||t.rank<2)throw new Be(`dot requires both inputs to be rank >= 2 but got x shape = ${e.shape} and y shape = ${t.shape}`);if(t.rank>=3){let r=e.shape.slice(-1)[0],a=t.shape.slice(-2)[0];if(r!==a)throw new Be(`If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = ${e.shape} and y shape = ${t.shape}`)}if(e.rank===2&&t.rank===2){let r=!1,a=!1;return So.matMul({a:e,b:t,transposeA:r,transposeB:a,bias:s?I1(e.rank,s,cr()):null,activation:n})}else{let r=e.shape.slice(),a=r.pop();e=G(e,[-1,a]);let o=t.shape.slice(),i=o.pop(),l=o.pop(),c=[...o,i],u=Array.from({length:t.rank},(f,m)=>m===0?t.rank-2:m<=t.rank-2?m-1:m);t=G(et(t,u),[l,-1]);let d=[...r,...c],p=!1,h=!1;return G(So.matMul({a:e,b:t,transposeA:p,transposeB:h,bias:s?I1(e.rank,s,cr()):null,activation:n}),d)}}function sw(e,t,n){return j(()=>(Array.isArray(t)?t=Zt(t,"int32"):t=de(t,"int32"),Su(e,t,n)))}function Id(e){return W(e,e)}function I1(e,t,n){let s=t.shape;if(t.rank!==1&&t.rank!==e)throw new q(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${e}`);if(e===5){if(n==="channelsFirst")return s.length===1?G(t,[1,s[0],1,1,1]):G(t,[1,s[3],s[0],s[1],s[2]]);if(n==="channelsLast")return s.length===1?G(t,[1,1,1,1,s[0]]):G(t,[1].concat(s))}else if(e===4){if(n==="channelsFirst")return s.length===1?G(t,[1,s[0],1,1]):G(t,[1,s[2],s[0],s[1]]);if(n==="channelsLast")return s.length===1?G(t,[1,1,1,s[0]]):G(t,[1].concat(s))}else if(e===3){if(n==="channelsFirst")return s.length===1?G(t,[1,s[0],1]):G(t,[1,s[1],s[0]]);if(n==="channelsLast")return s.length===1?G(t,[1,1,s[0]]):G(t,[1].concat(s))}else if(e<3)return t;throw new q(`Unsupported input rank by biasAdd: ${t.rank}`)}function hr(e,t,n){return j(()=>(n==null&&(n=cr()),jt(n),ie(e,I1(e.rank,t,n))))}function rL(e,t=1){if(t!==1)throw new Be(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return dd(e)}function aL(e){return j(()=>he(e,ie(rn(e),1)))}function rw(e,t,n,s){return j(()=>Av(e,t,n,s))}function oL(e){return j(()=>{let t=ie(.5,W(.2,e));return fs(t,0,1)})}function Sd(e,t,n=!1){return n?e():t()}var iL=["fanIn","fanOut","fanAvg"],lL=["normal","uniform","truncatedNormal"];function uL(e){rl(iL,"FanMode",e)}function cL(e){rl(lL,"Distribution",e)}var Zs=class extends le.Serializable{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}},S1=class extends Zs{apply(e,t){return Ht(e,t)}};S1.className="Zeros";le.registerClass(S1);var If=class extends Zs{apply(e,t){return gs(e,t)}};If.className="Ones";le.registerClass(If);var C1=class extends Zs{constructor(e){super();if(typeof e!="object")throw new q(`Expected argument of type ConstantConfig but got ${e}`);if(e.value===void 0)throw new q(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return j(()=>W(Ee(this.value),gs(e,t)))}getConfig(){return{value:this.value}}};C1.className="Constant";le.registerClass(C1);var T1=class extends Zs{constructor(e){super();this.DEFAULT_MINVAL=-.05,this.DEFAULT_MAXVAL=.05,this.minval=e.minval||this.DEFAULT_MINVAL,this.maxval=e.maxval||this.DEFAULT_MAXVAL,this.seed=e.seed}apply(e,t){return Nu(e,this.minval,this.maxval,t)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}};T1.className="RandomUniform";le.registerClass(T1);var N1=class extends Zs{constructor(e){super();this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if(t=t||"float32",t!=="float32"&&t!=="int32")throw new Be(`randomNormal does not support dType ${t}.`);return kf(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};N1.className="RandomNormal";le.registerClass(N1);var E1=class extends Zs{constructor(e){super();this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if(t=t||"float32",t!=="float32"&&t!=="int32")throw new Be(`truncatedNormal does not support dType ${t}.`);return lf(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};E1.className="TruncatedNormal";le.registerClass(E1);var R1=class extends Zs{constructor(e){super();this.gain=e.gain!=null?e.gain:1}apply(e,t){return j(()=>{if(e.length!==2||e[0]!==e[1])throw new q("Identity matrix initializer can only be used for 2D square matrices.");return W(this.gain,z2(e[0]))})}getConfig(){return{gain:this.gain}}};R1.className="Identity";le.registerClass(R1);function dL(e,t="channelsLast"){let n,s;if(jt(t),e.length===2)n=e[0],s=e[1];else if([3,4,5].indexOf(e.length)!==-1){if(t==="channelsFirst"){let r=To(e,2);n=e[1]*r,s=e[0]*r}else if(t==="channelsLast"){let r=To(e,0,e.length-2);n=e[e.length-2]*r,s=e[e.length-1]*r}}else{let r=To(e);n=Math.sqrt(r),s=Math.sqrt(r)}return[n,s]}var is=class extends Zs{constructor(e){super();if(e.scale<0)throw new q(`scale must be a positive float. Got: ${e.scale}`);this.scale=e.scale==null?1:e.scale,this.mode=e.mode==null?"fanIn":e.mode,uL(this.mode),this.distribution=e.distribution==null?"normal":e.distribution,cL(this.distribution),this.seed=e.seed}apply(e,t){let n=dL(e),s=n[0],r=n[1],a=this.scale;if(this.mode==="fanIn"?a/=Math.max(1,s):this.mode==="fanOut"?a/=Math.max(1,r):a/=Math.max(1,(s+r)/2),this.distribution==="normal"){let o=Math.sqrt(a);if(t=t||"float32",t!=="float32"&&t!=="int32")throw new Be(`${this.getClassName()} does not support dType ${t}.`);return lf(e,0,o,t,this.seed)}else{let o=Math.sqrt(3*a);return Nu(e,-o,o,t)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}};is.className="VarianceScaling";le.registerClass(is);var Sf=class extends is{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return is.className}};Sf.className="GlorotUniform";le.registerClass(Sf);var Cf=class extends is{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return is.className}};Cf.className="GlorotNormal";le.registerClass(Cf);var Tf=class extends is{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return is.className}};Tf.className="HeNormal";le.registerClass(Tf);var Nf=class extends is{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return is.className}};Nf.className="HeUniform";le.registerClass(Nf);var Ef=class extends is{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return is.className}};Ef.className="LeCunNormal";le.registerClass(Ef);var Rf=class extends is{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return is.className}};Rf.className="LeCunNormal";le.registerClass(Rf);var $1=class extends Zs{constructor(e){super();if(this.DEFAULT_GAIN=1,this.gain=e.gain==null?this.DEFAULT_GAIN:e.gain,this.seed=e.seed,this.seed!=null)throw new Be("Random seed is not implemented for Orthogonal Initializer yet.")}apply(e,t){return j(()=>{if(e.length<2)throw new Be("Shape must be at least 2D.");e[0]*e[1]>2e3&&console.warn(`Orthogonal initializer is being called on a matrix with more than 2000 (${e[0]*e[1]}) elements: Slowness may result.`);let n=e[0]>e[1]?[e[1],e[0]]:e,s=kf(n,0,1,"float32"),r=Nv.gramSchmidt(s);return e[0]>e[1]&&(r=et(r)),W(this.gain,r)})}getConfig(){return{gain:this.gain,seed:this.seed}}};$1.className="Orthogonal";le.registerClass($1);var aw={constant:"Constant",glorotNormal:"GlorotNormal",glorotUniform:"GlorotUniform",heNormal:"HeNormal",heUniform:"HeUniform",identity:"Identity",leCunNormal:"LeCunNormal",leCunUniform:"LeCunUniform",ones:"Ones",orthogonal:"Orthogonal",randomNormal:"RandomNormal",randomUniform:"RandomUniform",truncatedNormal:"TruncatedNormal",varianceScaling:"VarianceScaling",zeros:"Zeros"};function ow(e,t={}){return bd(e,le.SerializationMap.getMap().classNameMap,t,"initializer")}function Mt(e){return h1(e)}function $t(e){if(typeof e=="string"){let t=e in aw?aw[e]:e;if(t==="GlorotNormal")return new Cf;if(t==="GlorotUniform")return new Sf;if(t==="HeNormal")return new Tf;if(t==="HeUniform")return new Nf;if(t==="LeCunNormal")return new Ef;if(t==="LeCunUniform")return new Rf;{let n={};return n.className=t,n.config={},ow(n)}}else return e instanceof Zs?e:ow(e)}function pL(){return new S1}function hL(){return new If}function fL(e){return new C1(e)}function mL(e){return new T1(e)}function gL(e){return new N1(e)}function AL(e){return new E1(e)}function yL(e){return new R1(e)}function xL(e){return new is(e)}function bL(e){return new Sf(e)}function vL(e){return new Cf(e)}function wL(e){return new Tf(e)}function kL(e){return new Nf(e)}function IL(e){return new Ef(e)}function SL(e){return new Rf(e)}function CL(e){return new $1(e)}var iw={};ze(iw,{Layer:()=>nt,RNN:()=>sa,RNNCell:()=>Dd,activation:()=>iW,add:()=>gW,alphaDropout:()=>QW,average:()=>AW,averagePooling1d:()=>JA,averagePooling2d:()=>QA,averagePooling3d:()=>ey,avgPool1d:()=>CW,avgPool2d:()=>NW,avgPool3d:()=>RW,avgPooling1d:()=>TW,avgPooling2d:()=>EW,avgPooling3d:()=>$W,batchNormalization:()=>kW,bidirectional:()=>HW,concatenate:()=>yW,conv1d:()=>JB,conv2d:()=>QB,conv2dTranspose:()=>eW,conv3d:()=>tW,conv3dTranspose:()=>nW,convLstm2d:()=>WW,convLstm2dCell:()=>VW,cropping2D:()=>rW,dense:()=>lW,depthwiseConv2d:()=>oW,dot:()=>wW,dropout:()=>uW,elu:()=>jB,embedding:()=>mW,flatten:()=>dW,gaussianDropout:()=>JW,gaussianNoise:()=>YW,globalAveragePooling1d:()=>DW,globalAveragePooling2d:()=>_W,globalMaxPool1d:()=>qW,globalMaxPool2d:()=>XW,globalMaxPooling1d:()=>bk,globalMaxPooling2d:()=>vk,gru:()=>FW,gruCell:()=>OW,input:()=>Bw,inputLayer:()=>HB,layerNormalization:()=>IW,leakyReLU:()=>XB,lstm:()=>MW,lstmCell:()=>zW,masking:()=>eV,maxPool1d:()=>KW,maxPool2d:()=>ZW,maxPooling1d:()=>wk,maxPooling2d:()=>kk,maxPooling3d:()=>PW,maximum:()=>xW,minimum:()=>bW,multiply:()=>vW,permute:()=>fW,prelu:()=>KB,reLU:()=>qB,repeatVector:()=>pW,reshape:()=>hW,rnn:()=>UW,separableConv2d:()=>sW,simpleRNN:()=>LW,simpleRNNCell:()=>BW,softmax:()=>ZB,spatialDropout1d:()=>cW,stackedRNNCells:()=>GW,thresholdedReLU:()=>YB,timeDistributed:()=>jW,upSampling2d:()=>aW,zeroPadding2d:()=>SW});var TL=0;function lw(){return TL++}var $f={};function Df(e=""){return e in $f||($f[e]=0),$f[e]+=1,e+$f[e].toString()}function D1(e){return Array.isArray(e)&&Array.isArray(e[0])}function _f(e){return e.length===0?[]:Array.isArray(e[0])?e:[e]}function Ve(e){let t;if(Array.isArray(e)){if(e.length!==1)throw new q(`Expected Tensor length to be 1; got ${e.length}`);t=e[0]}else t=e;return t}function mt(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(e.length===1)return e=e,e[0];throw new q(`Expected exactly 1 Shape; got ${e.length}`)}else return e}function Pf(e){let t=0;for(let n of e)n.shape.length===0?t+=1:t+=n.shape.reduce((s,r)=>s*r);return t}var uw="Variable",cw=class{constructor(e,t="float32",n=uw,s=!0,r=null){this.dtype=t==null?"float32":t,this.shape=e.shape,this.id=lw(),n=n==null?uw:n,this.originalName=Qv(n),this.name=ew(this.originalName),this.trainable_=s,this.constraint=r,this.val=pv(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),NL(this.val,e),this.val.id!==e.id&&(this.val.assign(e),this.constraint!=null&&this.val.assign(this.constraint.apply(this.val))),this}dispose(){this.assertNotDisposed(),this.val.dispose()}assertNotDisposed(){if(this.val.isDisposed)throw new Error(`LayersVariable ${this.name} is already disposed.`)}get trainable(){return this.trainable_}set trainable(e){this.trainable_=e,this.val.trainable=e}};function NL(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape))}function _1(e){return e.map(t=>t.read())}function P1(e){e.forEach(t=>{t[0].write(t[1])})}var Yt=class{constructor(e){this.dtype=e.dtype,this.shape=e.shape,e.shape!=null?this.ndim=e.shape.length:this.ndim=e.ndim,this.maxNDim=e.maxNDim,this.minNDim=e.minNDim,this.axes=e.axes||{}}},fr=class{constructor(e,t,n,s,r,a,o){this.dtype=e,this.shape=t,this.sourceLayer=n,this.inputs=s,this.callArgs=r,this.outputTensorIndex=o,this.id=lw(),a!=null&&(this.originalName=Qv(a),this.name=ew(this.originalName)),this.rank=t.length}},EL=0,Ff=class{constructor(e,t){this.callArgs=t,this.id=EL++,this.outboundLayer=e.outboundLayer,this.inboundLayers=e.inboundLayers,this.nodeIndices=e.nodeIndices,this.tensorIndices=e.tensorIndices,this.inputTensors=e.inputTensors,this.outputTensors=e.outputTensors,this.inputMasks=e.inputMasks,this.outputMasks=e.outputMasks,this.inputShapes=e.inputShapes,this.outputShapes=e.outputShapes;for(let n of e.inboundLayers)n!=null&&n.outboundNodes.push(this);e.outboundLayer.inboundNodes.push(this)}getConfig(){let e=[];for(let t of this.inboundLayers)t!=null?e.push(t.name):e.push(null);return{outboundLayer:this.outboundLayer?this.outboundLayer.name:null,inboundLayers:e,nodeIndices:this.nodeIndices,tensorIndices:this.tensorIndices}}},RL=0,nt=class extends le.Serializable{constructor(e={}){super();this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=RL++,this.activityRegularizer=null,this.inputSpec=null,this.supportsMasking=!1,this._trainableWeights=[],this._nonTrainableWeights=[],this._losses=[],this._updates=[],this._built=!1,this.inboundNodes=[],this.outboundNodes=[];let t=e.name;if(!t){let n=this.getClassName();t=ta(n)+"_"+Df(n)}if(this.name=t,this.trainable_=e.trainable==null?!0:e.trainable,e.inputShape!=null||e.batchInputShape!=null){let n;if(e.batchInputShape!=null)n=e.batchInputShape;else if(e.inputShape!=null){let r=null;e.batchSize!=null&&(r=e.batchSize),n=[r].concat(e.inputShape)}this.batchInputShape=n;let s=e.dtype;s==null&&(s=e.inputDType),s==null&&(s="float32"),this.dtype=s}e.weights!=null?this.initialWeights=e.weights:this.initialWeights=null,this._refCount=null,this.fastWeightInitDuringBuild=!1}static nodeKey(e,t){return e.name+"_ib-"+t.toString()}getNodeAtIndex(e,t){if(this.inboundNodes.length===0)throw new dr(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new q(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return os(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return os(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new ea(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use \`getInputAt(nodeIndex)\` instead.`);if(this.inboundNodes.length===0)throw new ea(`Layer ${this.name} is not connected, no input to return.`);return os(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(this.inboundNodes.length===0)throw new ea(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new ea(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return os(this.getNodeAtIndex(0,"output").outputTensors)}get losses(){return this._losses}calculateLosses(){return this.losses.map(e=>e())}get updates(){return this._updates}get built(){return this._built}set built(e){this._built=e}get trainable(){return this.trainable_}set trainable(e){this._trainableWeights.forEach(t=>t.trainable=e),this.trainable_=e}get trainableWeights(){return this.trainable_?this._trainableWeights.filter(e=>e.trainable):[]}set trainableWeights(e){this._trainableWeights=e}get nonTrainableWeights(){return this.trainable?this._trainableWeights.filter(e=>!e.trainable).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)}set nonTrainableWeights(e){this._nonTrainableWeights=e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}get stateful(){return this._stateful}resetStates(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")}assertInputCompatibility(e){if(e=Ct(e),this.inputSpec==null||this.inputSpec.length===0)return;let t=Ct(this.inputSpec);if(e.length!==t.length)throw new q(`Layer ${this.name} expects ${t.length} inputs, but it received ${e.length} input tensors. Input received: ${e}`);for(let n=0;nr.maxNDim)throw new q(`Input ${n} is incompatible with layer ${this.name}: expected max_ndim=${r.maxNDim}, found ndim=${a}`);if(r.minNDim!=null&&a=0?o[l]:o[o.length+l];if(c!=null&&[c,null].indexOf(u)===-1)throw new q(`Input ${n} is incompatible with layer ${this.name}: expected axis ${l} of input shape to have value ${c} but got shape ${o}.`)}}if(r.shape!=null)for(let o=0;o{if(!this.built){this.assertInputCompatibility(e);let a=[];for(let o of Ct(e))a.push(o.shape);this.build(os(a)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),this._refCount===null&&r&&(this._refCount=1)}if(this.assertInputCompatibility(e),r){let a=this.call(e,t),o=Ct(a),i=[];for(let l of o)n.indexOf(l)!==-1&&(l=l.clone()),i.push(l);if(a=os(i),this.activityRegularizer!=null)throw new Be("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return a}else{let a=$L(e),o=this.computeOutputShape(a),i,l=DL(e);if(this.warnOnIncompatibleInputShape(Array.isArray(e)?a[0]:a),o!=null&&o.length>0&&Array.isArray(o[0])?i=o.map((c,u)=>new fr(l,c,this,Ct(e),t,this.name,u)):i=new fr(l,o,this,Ct(e),t,this.name),this.addInboundNode(e,i,null,null,a,o,t),this._refCount++,this.activityRegularizer!=null)throw new Be("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return i}})}warnOnIncompatibleInputShape(e){if(this.batchInputShape!=null)if(e.length!==this.batchInputShape.length)console.warn(`The rank of the input tensor provided (shape: ${JSON.stringify(e)}) does not match that of the batchInputShape (${JSON.stringify(this.batchInputShape)}) of the layer ${this.name}`);else{let t=!1;this.batchInputShape.forEach((n,s)=>{n!=null&&e[s]!=null&&e[s]!==n&&(t=!0)}),t&&console.warn(`The shape of the input tensor (${JSON.stringify(e)}) does not match the expectation of layer ${this.name}: ${JSON.stringify(this.batchInputShape)}`)}}get outputShape(){if(this.inboundNodes==null||this.inboundNodes.length===0)throw new ea(`The layer ${this.name} has never been called and thus has no defined output shape.`);let e=[];for(let t of this.inboundNodes){let n=JSON.stringify(t.outputShapes);e.indexOf(n)===-1&&e.push(n)}if(e.length===1){let t=this.inboundNodes[0].outputShapes;return Array.isArray(t)&&Array.isArray(t[0])&&t.length===1?t[0]:t}else throw new ea(`The layer ${this.name} has multiple inbound nodes with different output shapes. Hence the notion of "output shape" is ill-defined for the layer.`)}countParams(){if(!this.built)throw new dr(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return Pf(this.weights)}build(e){this.built=!0}getWeights(e=!1){return _1(e?this.trainableWeights:this.weights)}setWeights(e){j(()=>{let t=this.weights;if(t.length!==e.length)throw new q(`You called setWeights(weights) on layer "${this.name}" with a weight list of length ${e.length}, but the layer was expecting ${t.length} weights. Provided weights: ${e}...`);if(t.length===0)return;let n=[],s=_1(t);for(let r=0;rr.apply(c.read())),a==null&&(a=!0),a?this._trainableWeights.push(c):this._nonTrainableWeights.push(c),c}setFastWeightInitDuringBuild(e){this.fastWeightInitDuringBuild=e}addLoss(e){e==null||Array.isArray(e)&&e.length===0||(e=Ct(e),this._losses!==void 0&&this._losses!==null&&this.losses.push(...e))}computeOutputShape(e){return e}computeMask(e,t){if(!this.supportsMasking){if(t!=null)if(Array.isArray(t))t.forEach(n=>{if(n!=null)throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`)});else throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);return null}return t}addInboundNode(e,t,n,s,r,a,o=null){let i=Ct(e);t=Ct(t),n=Ct(n),s=Ct(s),r=_f(r),a=_f(a);let l=[],c=[],u=[];for(let d of i)l.push(d.sourceLayer),c.push(d.nodeIndex),u.push(d.tensorIndex);new Ff({outboundLayer:this,inboundLayers:l,nodeIndices:c,tensorIndices:u,inputTensors:i,outputTensors:t,inputMasks:n,outputMasks:s,inputShapes:r,outputShapes:a},o);for(let d=0;de.dispose()),this.weights.length}assertNotDisposed(){if(this._refCount===0)throw new Error(`Layer '${this.name}' is already disposed.`)}dispose(){if(!this.built)throw new Error(`Cannot dispose Layer ${this.name} because it has not been built yet.`);if(this._refCount===null)throw new Error(`Cannot dispose Layer ${this.name} because it has not been used yet.`);this.assertNotDisposed();let e=0;return--this._refCount==0&&(e=this.disposeWeights()),{refCountAfterDispose:this._refCount,numDisposedVariables:e}}};function $L(e){e=Ct(e);let t=[];for(let n of e)t.push(n.shape);return os(t)}function DL(e){return"float32"}function dw(e,t,n){if((t==null||n!=null&&n>0)&&(t=e.sourceLayer,n=e.nodeIndex),t.inboundNodes.length===0)return[e];{let s=t.inboundNodes[n];if(s.inboundLayers.length===0)return s.inputTensors;{let r=[];for(let a=0;a0){let r=await Promise.all(t);for(let a=0;aie(this.totals[s],W(r,n)));this.totals[s]=o,a!=null&&a.dispose()}}}async onEpochEnd(e,t){if(t!=null)for(let n of this.params.metrics)this.totals[n]!=null&&(typeof this.totals[n]=="number"?t[n]=this.totals[n]/this.seen:j(()=>{let s=W(he(1,this.seen),this.totals[n]);t[n]=s,this.totals[n].dispose(),yn(t[n])}))}},gw=class extends Ou{async onTrainBegin(e){this.epoch=[],this.history={}}async onEpochEnd(e,t){t==null&&(t={}),this.epoch.push(e);for(let n in t)this.history[n]==null&&(this.history[n]=[]),this.history[n].push(t[n])}async syncData(){let e=[],t=[],n=[];for(let r in this.history){let a=this.history[r];for(let o=0;onew Aw(s,t))}var _r=class{constructor(){}static registerCallbackConstructor(e,t){v.assert(e>=0&&Number.isInteger(e),()=>`Verbosity level is expected to be an integer >= 0, but got ${e}`),_r.checkForDuplicate(t),_r.constructors[e]==null&&(_r.constructors[e]=[]),_r.constructors[e].push(t)}static checkForDuplicate(e){for(let t in _r.constructors)_r.constructors[+t].forEach(s=>{if(s===e)throw new q("Duplicate callback constructor.")})}static clear(){_r.constructors={}}static createCallbacks(e){let t=[];for(let n in _r.constructors){let s=+n;e>=s&&t.push(..._r.constructors[s])}return t.map(n=>new n)}},F1=_r;F1.constructors={};function xw(e,t,n,s,r,a,o,i,l){let c=new gw,u=[new PL,...F1.createCallbacks(t)];e!=null&&u.push(...e),u.push(c);let d=new mw(u);return d.setParams({epochs:n,initialEpoch:s,samples:r,steps:a,batchSize:o,verbose:t,doValidation:i,metrics:l}),{callbackList:d,history:c}}function mr(e,t={},n=!1){return bd(e,le.SerializationMap.getMap().classNameMap,t,"layer",n)}function Of(e,t){return j(()=>{e.dtype!=="float32"&&(e=de(e,"float32"));let n=Ie(Id(e),t,!0),s=Iu(n.shape,on()),r=_n(Yr(n,s));return he(e,r)})}function il(e,t){return j(()=>Wt(Id(ye(t,e)),-1))}function Mf(e,t){return j(()=>Wt(rn(ye(t,e)),-1))}function Mu(e,t){return j(()=>{let n=ye(e,t),s=fs(rn(e),on(),Number.MAX_VALUE),r=rn(he(n,s));return W(100,Wt(r,-1))})}function FL(e,t){return j(()=>{let n=fs(t,on(),Number.MAX_VALUE),s=Ns(ie(1,n)),r=fs(e,on(),Number.MAX_VALUE),a=Ns(ie(1,r));return Wt(Id(ye(s,a)),-1)})}function OL(e,t){return j(()=>{let n=Yr(0,ye(1,W(e,t)));return Wt(Id(n),-1)})}function ML(e,t){return j(()=>{let n=Yr(0,ye(1,W(e,t)));return Wt(n,-1)})}function zL(e,t){return j(()=>{let n=Ie(W(e,t),-1),s=rs(W(ye(1,e),t),-1);return Yr(0,ie(1,ye(s,n)))})}function LL(e,t){return j(()=>{let n=Math.log(2),s=ye(t,e),r=ye(ie(s,Cu(W(-2,s))),n);return Wt(r,-1)})}function Cd(e,t,n=!1){return j(()=>{if(n)t=$u(t);else{let s=Ie(t,t.shape.length-1,!0);t=he(t,s)}return t=fs(t,on(),1-on()),Ot(Ie(W(de(e,"float32"),Ns(t)),t.shape.length-1))})}function zf(e,t,n=!1){return j(()=>{let s=de(pd(nL(e)),"int32");t=fs(t,on(),1-on());let r=t.shape,a=G(id(s,r[r.length-1]),r);return Cd(a,t,n)})}function BL(e,t){if(!v.arraysEqual(e.shape,t.shape))throw new q(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(t.shape)}`);return j(()=>{let n=Rr(t),s=Ot(rn(t));return ie(ye(n,W(t,e)),Zh(Ts(s)))})}function Lf(e,t){return j(()=>{let n;return n=fs(t,on(),1-on()),n=Ns(he(n,ye(1,n))),Wt(BL(e,n),-1)})}function WL(e,t){return j(()=>{let n=fs(e,on(),1),s=fs(t,on(),1);return Ie(W(e,Ns(he(n,s))),-1)})}function VL(e,t){return j(()=>{let n=Ns(ie(on(),t));return Wt(ye(t,W(e,n)),-1)})}function O1(e,t){return j(()=>{let n=Of(e,-1),s=Of(t,-1),r=W(n,s);return Ot(Ie(r,-1))})}var Bf={meanSquaredError:il,meanAbsoluteError:Mf,meanAbsolutePercentageError:Mu,meanSquaredLogarithmicError:FL,squaredHinge:OL,hinge:ML,categoricalHinge:zL,logcosh:LL,categoricalCrossentropy:Cd,sparseCategoricalCrossentropy:zf,binaryCrossentropy:Lf,kullbackLeiblerDivergence:WL,poisson:VL,cosineProximity:O1};function M1(e){if(typeof e=="string"){if(e in Bf)return Bf[e];let t=`Unknown loss ${e}`;throw e.toLowerCase().includes("softmaxcrossentropy")&&(t=`Unknown loss ${e}. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy`),new q(t)}else return e}function z1(e,t){return j(()=>{let n=W(.5,Es(t)),s=vf(ms(t,n),e.dtype);return Wt(Cs(e,s),-1)})}function L1(e,t){return j(()=>vf(Cs(Hs(e,-1),Hs(t,-1)),"float32"))}function bw(e,t){return j(()=>de(Ie(lr(Cs(e,1),Cs(t,1))),"float32"))}function UL(e,t){return j(()=>de(Ie(lr(Cs(e,1),Cs(t,0))),"float32"))}function GL(e,t){return j(()=>de(Ie(lr(Cs(e,0),Cs(t,1))),"float32"))}function vw(e,t){return j(()=>{let n=bw(e,t),s=GL(e,t),r=ie(n,s);return de(Wn(ms(r,0),he(n,r),0),"float32")})}function HL(e,t){return j(()=>{let n=bw(e,t),s=UL(e,t),r=ie(n,s);return de(Wn(ms(r,0),he(n,r),0),"float32")})}function ww(e,t){return Lf(e,t)}function kw(e,t){return e.rank===t.rank&&(e=pt(e,[e.rank-1])),t=Hs(t,-1),t.dtype!==e.dtype&&(t=de(t,e.dtype)),de(Cs(e,t),"float32")}var jL=il,qL=il,XL=Mf,KL=Mf,ZL=Mu,YL=Mu,B1=Cd,JL=O1,Iw=zf,Wf={binaryAccuracy:z1,categoricalAccuracy:L1,precision:vw,categoricalCrossentropy:B1,sparseCategoricalCrossentropy:Iw,mse:jL,MSE:qL,mae:XL,MAE:KL,mape:ZL,MAPE:YL,cosine:JL};function QL(e){if(typeof e=="string"&&e in Wf)return Wf[e];if(typeof e!="string"&&e!=null)return e;throw new q(`Unknown metric ${e}`)}function Vf(e){if($r(e!==null,`Unknown LossOrMetricFn ${e}`),typeof e=="string")return e;{let t;for(let n of Object.keys(Bf))if(Bf[n]===e){t=n;break}if(t!==void 0)return t;for(let n of Object.keys(Wf))if(Wf[n]===e){t=n;break}return t!==void 0?t:e.name}}function eB(e){let t={Adagrad:()=>tl.adagrad(.01),Adadelta:()=>tl.adadelta(1,.95,on()),Adam:()=>tl.adam(.001,.9,.999,on()),Adamax:()=>tl.adamax(.002,.9,.999,on(),0),RMSProp:()=>tl.rmsprop(.001,.9,0,on()),SGD:()=>tl.sgd(.01)};if(t.adagrad=t.Adagrad,t.adadelta=t.Adadelta,t.adam=t.Adam,t.adamax=t.Adamax,t.rmsprop=t.RMSProp,t.sgd=t.SGD,e in t)return t[e]();throw new q(`Unknown Optimizer ${e}`)}var Sw=1*1024*1024;function Cw(e,t,n=!1){if(e==null||typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype||!W1(e))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(n){let s=JSON.stringify(e);s.length>Sw&&console.warn(`User-defined metadata of model "${t}" is too large in size (length=${s.length} when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= ${Sw}.`)}}function W1(e){if(e===null)return!0;if(typeof e=="object")if(Object.getPrototypeOf(e)===Object.prototype){let t=Object.keys(e);for(let n of t)if(typeof n!="string"||!W1(e[n]))return!1;return!0}else if(Array.isArray(e)){for(let t of e)if(!W1(t))return!1;return!0}else return!1;else{let t=typeof e;return t==="string"||t==="number"||t==="boolean"}}function tB(e,t,n,s=console.log){let r=sB(e),a=["Layer (type)","Output shape","Param #"];r?(t=t||65,n=n||[.45,.85,1]):(t=t||98,n=n||[.33,.55,.67,1]),n[n.length-1]<=1&&(n=n.map(u=>Math.floor(t*u)));let o;if(!r){a.push("Receives inputs"),o=[];for(let u in e.nodesByDepth)o.push(...e.nodesByDepth[u])}s("_".repeat(t)),Uf(a,n,s),s("=".repeat(t));let i=e.layers;for(let u=0;u1||r.length===1&&r[0].inboundLayers.length>1){t=!1;break}s.push(...r)}if(t)for(let r of e.layers){let a=!1;for(let o of r.inboundNodes)if(s.indexOf(o)!==-1)if(a){t=!1;break}else a=!0;if(!t)break}return t}function Uf(e,t,n=console.log){let s="";for(let r=0;r0&&(s=s.slice(0,s.length-1)+" "),s+=e[r],s=s.slice(0,t[r]),s+=" ".repeat(t[r]-s.length);n(s)}function rB(e,t,n){let s;try{s=JSON.stringify(e.outputShape)}catch(i){s="multiple"}let r=e.name,a=e.getClassName(),o=[`${r} (${a})`,s,e.countParams().toString()];Uf(o,t,n)}function aB(e,t,n,s){let r;try{r=JSON.stringify(e.outputShape)}catch(u){r="multiple"}let a=[];for(let u of e.inboundNodes)if(!(n!=null&&n.length>0&&n.indexOf(u)===-1))for(let d=0;df.name),l=[],c=t.names();for(let f of i)c.indexOf(f)!==-1?l.push(t.getValue(f)):l.push(null);s!=null&&(s.maxNumTensors=-1/0,s.minNumTensors=1/0);let u=i.join(",")+"|"+t.names().join(","),d,p;if(G1[u]==null){let f=iB(o,t);d=f.sorted,p=f.recipientCounts,G1[u]=d,Nw[u]=p}d=G1[u],p={},r||Object.assign(p,Nw[u]);let h=new ll(t);for(let f=0;fs.maxNumTensors&&(s.maxNumTensors=P),P0,()=>"Expected at least one fetch, got none");let n=[],s={};if(e.length===1){let r=Ew(e[0],t);n=r.sorted,s=r.recipientMap}else{let r=new Set;for(let a of e){let{sorted:o,recipientMap:i}=Ew(a,t);for(let l of o)r.has(l.name)||(n.push(l),r.add(l.name));for(let l in i)s[l]==null&&(s[l]=new Set),i[l].forEach(c=>s[l].add(c))}}return{sorted:n,recipientCounts:lB(s)}}function lB(e){let t={};for(let n in e)t[n]=e[n].size;return t}function Ew(e,t){let n=new Set,s=[],r={};for(let i of t.names())n.add(i);let a=[],o=[];for(a.push(e);a.length>0;){let i=a[a.length-1];if(n.has(i.name)){a.pop();continue}let l=o[o.length-1]===a.length-1;if(i.inputs.length===0||l)a.pop(),s.push(i),n.add(i.name),l&&o.pop();else{o.push(a.length-1);for(let c of i.inputs)r[c.name]==null&&(r[c.name]=new Set),r[c.name].add(i.name),!n.has(c.name)&&a.push(c)}}return{sorted:s,recipientMap:r}}function uB(e){let t;if(e.sourceLayer.inboundNodes.length===1)t=e.sourceLayer.output;else{let n=null;for(let s=0;sA.name)}`);Co(this.outputs).length!==this.outputs.length&&console.warn(`The list of outputs passed to the model is redundant. All outputs should only appear once. Found: ${this.outputs.map(A=>A.name)}`),this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];for(let A of this.outputs){let y=A.sourceLayer,x=A.nodeIndex,b=A.tensorIndex;this.outputLayers.push(y),this.outputLayersNodeIndices.push(x),this.outputLayersTensorIndices.push(b)}for(let A of this.inputs){let y=A.sourceLayer,x=A.nodeIndex,b=A.tensorIndex;$r(x===0,"input layer has >1 nodes"),$r(b===0,"input layer has >1 tensors"),this.inputLayers.push(y),this.inputLayersNodeIndices.push(x),this.inputLayersTensorIndices.push(b)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let A=0;AA.shape),this.internalOutputShapes=this.outputs.map(A=>A.shape);let t={},n={},s={},r={},a={},o=[],i=(A,y,x,b,w,k)=>{(b==null||w==null||k==null)&&(b=A.sourceLayer,w=A.nodeIndex,k=A.tensorIndex);let S=b.inboundNodes[w];if(x.indexOf(S)!==-1)throw new dr(`The tensor ${A.name} at layer "${b.name}" is part of a cycle.`);if(y.indexOf(S)!==-1)return;this.containerNodes.add(Pr.nodeKey(b,w)),b.id in a||(a[b.id]=Object.keys(a).length),x.indexOf(S)===-1&&x.push(S);let E=S.inboundLayers.length;for(let P=0;P=0;)x.splice(x.indexOf(S),1);o.push(S)},l=[],c=[];for(let A of this.outputs)i(A,l,c);let u=o.slice().reverse();for(let A of u){n[A.id]=A,A.id in t||(t[A.id]=0);let y=t[A.id],x=s[A.outboundLayer.id]==null?0:s[A.outboundLayer.id];y=Math.max(y,x),s[A.outboundLayer.id]=y,r[A.outboundLayer.id]=A.outboundLayer,t[A.id]=y;for(let b=0;bparseInt(A,10)).sort(bf);this.layers=[];for(let A of h){let y=p[A];y.sort((x,b)=>{let w=a[x.id],k=a[b.id];return wk?1:0});for(let x of y)x instanceof Pr&&this.internalContainerRefs.push(x),this.layers.push(x)}this.layersByDepth=p,h=Object.keys(d).map(A=>parseInt(A,10)).sort(bf);let f=this.inputs.slice(),m=[];for(let A of h)for(let y of d[A]){let x=y.outboundLayer;if(x!=null){for(let b of y.inputTensors)if(f.indexOf(b)===-1)throw new dr(`Graph disconnected: cannot obtain value for tensor ${b} at layer "${x.name}". The following previous layers were accessed without issue: ${m}`);for(let b of y.outputTensors)f.push(b);m.push(x.name)}}this.nodesByDepth=d;let g=this.layers.map(A=>A.name);for(let A of g){let y=g.filter(x=>x===A).length;if(y!==1)throw new dr(`The name "${A}" is used ${y} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(g))}this.outboundNodes=[],this.inboundNodes=[],new Ff({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:this.inputs.map(A=>null),outputMasks:this.outputs.map(A=>null),inputShapes:this.inputs.map(A=>A.shape),outputShapes:this.outputs.map(A=>A.shape)}),this.built=!0,this._refCount=1}assertNotDisposed(){if(this._refCount===0)throw new Error(`Container '${this.name}' is already disposed.`)}dispose(){this.assertNotDisposed();let e={refCountAfterDispose:null,numDisposedVariables:0};if(--this._refCount==0){for(let t of this.layers)e.numDisposedVariables+=t.dispose().numDisposedVariables;for(let t of this.internalContainerRefs)e.numDisposedVariables+=t.dispose().numDisposedVariables}return e.refCountAfterDispose=this._refCount,e}get trainable(){return this.trainable_}set trainable(e){this.layers.forEach(t=>{t._trainableWeights.forEach(n=>n.trainable=e)}),this.trainable_=e}get trainableWeights(){if(this._trainableWeights.length>0)throw new q("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];let e=[];for(let t of this.layers)e=e.concat(t.trainableWeights);return e}get nonTrainableWeights(){let e=[];for(let t of this.layers)e.push(...t.nonTrainableWeights);if(!this.trainable){let t=[];for(let n of this.layers)t.push(...n.trainableWeights);return t.concat(e)}return e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(e,t=!0){let n={},s=0;for(let a of this.layers)for(let o of a.weights){if(n[o.originalName]!=null)throw new q(`Duplicate weight name: ${o.originalName}`);n[o.originalName]=o,s++}let r=[];for(let a in e){let o=a;if(n[a]==null){let i=a.split("/");o=i.slice(0,-2).concat([i[i.length-1]]).join("/")}if(n[o]!=null)r.push([n[o],e[a]]);else if(t)throw new q(`Provided weight data has no target variable: ${a}`);delete n[o]}if(t){let a=[];for(let o in n)a.push(o);if(a.length>0)throw new q(`${a.length} of ${s} weights are not set: ${a}`)}P1(r)}updatedConfig(){let e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${U1}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){let n=V1(this.updatedConfig());return t?JSON.stringify(n):n}call(e,t){return j(()=>{e=Ct(e);let n=new ll;for(let s=0;s{e=Ct(e);let n;return t==null?n=nl(null,e.length):n=Ct(t),this.runInternalGraph(e,n)[1]})}computeOutputShape(e){let t=_f(e);if(t.length!==this.inputLayers.length)throw new q(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);let n={};for(let o=0;oparseInt(o,10)).sort(bf);if(s.length>1)for(let o of s){let i=this.nodesByDepth[o];for(let l of i){let c=l.outboundLayer;if(this.inputLayers.map(f=>f.id).indexOf(c.id)!==-1)continue;let u=[];for(let f=0;fparseInt(i,10)).sort(bf);for(let i of s){let l=this.nodesByDepth[i];for(let c of l){let u=c.outboundLayer,d=c.inputTensors,p=c.outputTensors,h=new Array;for(let f of d)f.id in n&&h.push(n[f.id]);if(h.length===d.length){let f={},m,g,A,y;if(c.callArgs!=null&&(f=c.callArgs),h.length===1){let[x,b]=h[0];f.mask==null&&(f.mask=b),A=Ct(u.call(x,f)),y=Ct(u.computeMask(x,b)),m=[x],g=[b]}else m=h.map(x=>x[0]),g=h.map(x=>x[1]),f.mask==null&&(f.mask=g),A=Ct(u.call(m,f)),y=Ct(u.computeMask(m,g));if(u.activityRegularizer)throw new Be("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let x=0;x{let e=[];for(let t of this.layers)for(let n=0;n0){let f=[];for(let m=0;m0&&m.apply(os(A),y)}function l(m){let g=m.name,A=mr(m,t.customObjects!=null?t.customObjects:{});A.setFastWeightInitDuringBuild(s),r[g]=A,m.inboundNodes.forEach(x=>{if(!(x instanceof Array))throw new q(`Corrupted configuration, expected array for nodeData: ${x}`);o(A,x)})}let c=t.name,u=t.layers;for(let m of u)l(m);for(;!Bz(a);)for(let m of u){let g=r[m.name];if(g.name in a){let A=a[g.name];delete a[g.name];for(let y of A)i(g,y)}}let d=[],p=[],h=t.inputLayers;for(let m of h){let g=m[0],A=m[1],y=m[2];$r(g in r);let b=r[g].inboundNodes[A].outputTensors;d.push(b[y])}let f=t.outputLayers;for(let m of f){let g=m[0],A=m[1],y=m[2];$r(g in r);let b=r[g].inboundNodes[A].outputTensors;p.push(b[y])}return new e({inputs:d,outputs:p,name:c})}get stateful(){if(this._stateful)throw new q("Container instance unexpectedly has _stateful = true. The statefulness of a Container is determined by the Layers it contains. Its _stateful property must remain the default false.");for(let e of this.layers)if(e.stateful)return!0;return!1}resetStates(){j(()=>{this.layers.forEach(e=>{e.stateful&&e.resetStates()})})}};function cB(e,t,n){let s=t.length;if(e==null||Array.isArray(e)&&e.length===0)return t.map(r=>null);if(s===1)return Array.isArray(e)&&e.length===1?e:typeof e=="object"&&t[0]in e?[e[t[0]]]:[e];if(Array.isArray(e)){if(e.length!==s)throw new Error(`Provided ${n} is an array of ${e.length} element(s), but the model has ${s} outputs. Make sure a set of weights is provided for each model output.`);return e}else if(typeof e=="object"&&Object.keys(e).length>0&&typeof e[Object.keys(e)[0]]=="object"){let r=[];return t.forEach(a=>{a in e?r.push(e[a]):r.push(null)}),r}else throw new Error(`The model has multiple (${s}) outputs, so ${n} must be either an array with ${s} elements or an object with ${t} keys. Provided ${n} not understood: ${JSON.stringify(e)}`)}function Rw(e,t){return cB(e,t,"classWeight")}async function $w(e,t,n,s){if(t!=null||s!=null)throw new Error("Support sampleWeight is not implemented yet");if(n!=null){let r=j(()=>{if(e.shape.length===1)return or(e);if(e.shape.length===2){if(e.shape[1]>1)return Hs(e,1);if(e.shape[1]===1)return G(e,[e.shape[0]]);throw new Error(`Encountered unexpected last-dimension size (${e.shape[1]}) during handling of class weights. The size is expected to be >= 1.`)}else throw new Error(`Unexpected rank of target (y) tensor (${e.rank}) during handling of class weights. The rank is expected to be 1 or 2.`)}),a=Array.from(await r.data());Q(r);let o=[];return a.forEach(i=>{if(n[i]==null)throw new Error(`classWeight must contain all classes in the training data. The class ${i} exists in the data but not in classWeight`);o.push(n[i])}),Zt(o,"float32")}else return null}function dB(e,t){return W(e,t)}var pB=32;function Dw(e,t){let n,s,r=t;n=r.xs,s=r.ys,v.assert(n!=null&&s!=null,()=>`A Dataset iterator for fitDataset() is expected to generate objects of the form \`{xs: xVal, ys: yVal}\`, where the two values may be \`tf.Tensor\`, an array of Tensors, or a map of string to Tensor. The provided Dataset instead generates ${t}`);let a=_w("input",e.inputNames,n),o=_w("output",e.outputNames,s),i=a[0].shape[0];v.assert(a.length===e.inputs.length,()=>`LayersModel has ${e.inputs.length} inputs, but the dataset provides ${a.length} inputs. (Expected input keys: ${JSON.stringify(e.inputNames)})`),v.assert(o.length===e.outputs.length,()=>`LayersModel has ${e.outputs.length} outputs, but the dataset provides ${o.length} outputs. (Expected output keys: ${JSON.stringify(e.outputNames)})`);for(let l=0;l`Batch size mismatch: input ${e.inputNames[l]} has ${a[l].shape[0]}; expected ${i} based on input ${e.inputNames[0]}.`);for(let l=0;l`Batch size mismatch: output ${e.outputNames[l]} has ${o[l].shape[0]}; expected ${i} based on input ${e.inputNames[0]}.`);return{xs:a,ys:o}}function _w(e,t,n){if(n instanceof Ye)return[n];if(Array.isArray(n))return v.assert(n.length===t.length,()=>`Received an array of ${n.length} Tensors, but expected ${t.length} to match the ${e} keys ${t}.`),n;{let s=[];for(let r of t){if(n[r]==null)throw new q(`The feature data generated by the dataset lacks the required ${e} key '${r}'.`);s.push(n[r])}return s}}function hB(e){if(e.length===3)throw new Be("Validation with sample weights is not implemented yet.");return{xs:e[0],ys:e[1]}}async function fB(e,t,n){let s=n.batchesPerEpoch!=null;if(v.assert(e.optimizer!=null,()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."),v.assert(n!=null,()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."),v.assert(n.epochs!=null&&n.epochs>0&&Number.isInteger(n.epochs),()=>`For fitDataset(), config.epochs is expected to be a positive integer, but got ${n.epochs}`),v.assert(!s||n.batchesPerEpoch>0&&Number.isInteger(n.batchesPerEpoch),()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${n.batchesPerEpoch}`),v.assert(n.validationSplit==null,()=>"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."),e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0;try{let r=n.validationData!=null,a,o;if(r)if(Pw(n.validationData))v.assert(n.validationBatches==null||n.validationBatches>0&&Number.isInteger(n.validationBatches),()=>`For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got ${n.validationBatches}`);else{let g=hB(n.validationData);a=g.xs,o=g.ys}let i=e.makeTrainFunction(),l=e.getDedupedMetricsNames(),c;r?c=l.slice().concat(l.map(g=>"val_"+g)):c=l.slice();let u=yw(n.callbacks,n.yieldEvery),d=n.verbose==null?1:n.verbose,{callbackList:p,history:h}=xw(u,d,n.epochs,null,null,mB(t,n),null,r,c);p.setModel(e),e.history=h,await p.onTrainBegin(),e.stopTraining_=!1;let f=n.initialEpoch==null?0:n.initialEpoch,m=await t.iterator();for(;f=n.batchesPerEpoch:x.done){if(r){let b;Pw(n.validationData)?b=Ct(await e.evaluateDataset(n.validationData,{batches:n.validationBatches})):b=Ct(e.evaluate(a,o,{batchSize:n.validationBatchSize==null?pB:n.validationBatchSize,verbose:0}));for(let w=0;w0)throw new Be("Verbose mode is not implemented yet.");v.assert(!s||n.batches>0&&Number.isInteger(n.batches),()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(n.batches)}`);let o=gB(t)?t:await t.iterator(),i=0,l=0;for(;s?l{if(c.value){let{xs:u,ys:d}=Dw(e,c.value),p=u.concat(d),h=j(()=>r(p));if(Q(p),l===0)for(let m=0;mie(a[m],W(f,g))),l>0&&Q(A)}Q(h),i+=f,++l}return a}),c.done){s&&console.warn(`Your dataset iterator ran out of data during evaluateDataset(). Interrupting evalution. Make sure that your dataset can generate at least \`batches\` batches (in this case, ${n.batches} batches). You may need to use the repeat() function when building your dataset.`);break}}for(let c=0;c0&&Number.isInteger(e),()=>`batchSize is required to be a positive integer, but got ${e}`)}function Ed(e,t,n){return e==null?[null]:Array.isArray(e)?e.map(s=>ol(s,t,n-t)):ol(e,t,n-t)}function j1(e,t){return j(()=>e==null?null:Array.isArray(e)?e.map(n=>j1(n,t)):sw(e,t.dtype==="int32"?t:de(t,"int32")))}function q1(e,t){let n=[],s=0,r=null;for(;s=e&&(r=e),n.push([s,r]),s=r;return n}async function yB(e,t,n,s,r,a,o,i,l,c,u,d,p,h,f){r==null&&(r=32),a==null&&(a=1),u==null&&(u=!0),p==null&&(p=0);let m=!1;if(l!=null&&c!=null&&(m=!0),f!=null&&(m=!0,h==null))throw new q("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");let g=e.checkNumSamples(n,r,h,"steps_per_epoch"),A;g!=null&&(A=pr(0,g)),o==null&&(o=1);let{callbackList:y,history:x}=xw(i,o,a,p,g,h,r,m,d);y.setModel(e),e.history=x,await y.onTrainBegin(),e.stopTraining_=!1;for(let b=p;b{let F=S[E][0],R=S[E][1],_=ol(k,F,R-F);P.batch=E,P.size=R-F;let T=j1(n,_),M=t(T);for(let U=0;U0){if(f=!0,s.validationData.length===2)o=s.validationData[0],i=s.validationData[1];else throw s.validationData.length===3?new Be("validationData including sample weights is not supported yet."):new q(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${s.validationData} is invalid.`);let S=!0,E=await e.standardizeUserData(o,i,null,null,S,d);l=E[0],c=E[1],m=l.concat(c)}else if(s.validationSplit!=null&&s.validationSplit>0&&s.validationSplit<1){f=!0;let S=Math.floor(r[0].shape[0]*(1-s.validationSplit)),E=r[0].shape[0];l=Ed(r,S,E),r=Ed(r,0,S),c=Ed(a,S,E),a=Ed(a,0,S),m=l.concat(c)}else s.validationSteps!=null&&(f=!0);let g=r.concat(a).concat(u);e.checkTrainableWeightsConsistency();let A=e.makeTrainFunction(),y=e.getDedupedMetricsNames(),x,b;f?(e.makeTestFunction(),x=e.testFunction,b=y.slice().concat(y.map(S=>"val_"+S))):(x=null,m=[],b=y.slice());let w=yw(s.callbacks,s.yieldEvery);return await yB(e,A,g,y,d,s.epochs,s.verbose,w,x,m,s.shuffle,b,s.initialEpoch,null,null)}finally{e.isTraining=!1,ul(r,t),ul(a,n),ul(l,o),ul(c,i),u!=null&&Q(u)}}function Fw(e){let t=[];e instanceof Ye&&(e=[e]);for(let n=0;nn.push(r.id));else if(t!=null)for(let r in t){let a=t[r];n.push(a.id)}let s=[];if(e instanceof Ye)n.indexOf(e.id)===-1&&s.push(e);else if(Array.isArray(e))e.forEach(r=>{n.indexOf(r.id)===-1&&s.push(r)});else if(e!=null)for(let r in e){let a=e[r];n.indexOf(a.id)===-1&&s.push(a)}s.forEach(r=>{r.isDisposed||r.dispose()})}function bB(e){return e instanceof Ye}function X1(e){return Array.isArray(e)}function Ow(e){return!bB(e)&&!X1(e)}function Mw(e,t,n,s=!0,r=""){if(t==null||t.length===0){if(e!=null){let o=!1;if(X1(e)&&e.length>0)o=!0;else if(Ow(e)){for(let i in e)if(e.hasOwnProperty(i)){o=!0;break}}else o=!0;if(o)throw new q(`Error when checking model ${r} expected no data, but got ${e}`)}return[]}if(e==null)return t.map(o=>null);let a;if(Ow(e)){e=e,a=[];for(let o of t){if(e[o]==null)throw new q(`No data provided for "${o}". Need data for each key in: ${t}`);a.push(e[o])}}else if(X1(e)){if(e=e,e.length!==t.length)throw new q(`Error when checking model ${r}: the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see ${t.length} Tensor(s), but instead got the following list of Tensor(s): ${e}`);a=e}else{if(e=e,t.length>1)throw new q(`The model ${r} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);a=[e]}if(a=Fw(a),n!=null)for(let o=0;o=0&&c!==u)throw new q(`${r} expected a batch of elements where each example has shape [${n[o].slice(1,n[o].length)}] (i.e.,tensor shape [*,${n[o].slice(1,n[o].length)}]) but the ${r} received an input with ${i.shape[0]} examples, each with shape [${i.shape.slice(1,i.shape.length)}] (tensor shape [${i.shape}])`)}}return a}function vB(e,t,n){let s=Co(e.map(a=>a.shape[0]));s.sort();let r=Co(t.map(a=>a.shape[0]));if(r.sort(),s.length>1)throw new q(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map(a=>a.shape))}`);if(r.length>1)throw new q(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map(a=>a.shape))}`);if(s.length>0&&r.length>0&&!v.arraysEqual(s,r))throw new q(`Input Tensors should have the same number of samples as target Tensors. Found ${s[0]} input sample(s) and ${r[0]} target sample(s).`)}function wB(e,t,n){let s=[il,Lf,Cd];for(let r=0;r1)throw new q(`The model expects ${t.length} ${r} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(e.shape)}.`);a=[e]}if(n!=null)for(let o=0;o[]);let n;if(typeof e=="string"||typeof e=="function")n=[e];else if(Array.isArray(e)||typeof e=="object")n=e;else throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${e}`);if(Array.isArray(n))return t.map(s=>n);{let s=[];for(let r of t){let a=n.hasOwnProperty(r)?n[r]:[];Array.isArray(a)||(a=[a]),s.push(a)}return s}}var IB="layers-model",na=class extends Pr{constructor(e){super(e);this.isTraining=!1}summary(e,t,n=console.log){if(!this.built)throw new q("This model has never been called, thus its weights have not been created yet. So no summary can be displayed. Build the model first (e.g., by calling it on some test data).");tB(this,e,t,n)}compile(e){if(e.loss==null&&(e.loss=[]),this.loss=e.loss,typeof e.optimizer=="string")this.optimizer_=eB(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof Qr))throw new q("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=e.optimizer,this.isOptimizerOwned=!1}let t=[];if(!Array.isArray(e.loss)&&typeof e.loss!="string"&&typeof e.loss!="function"){e.loss=e.loss;for(let a in e.loss)if(this.outputNames.indexOf(a)===-1)throw new q(`Unknown entry in loss dictionary: "${a}". Only expected the following keys: ${this.outputNames}`);for(let a of this.outputNames)e.loss[a]==null&&console.warn(`Output "${a}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${a} during training`),t.push(M1(e.loss[a]))}else if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new q(`When passing an Array as loss, it should have one entry per model output. The model has ${this.outputs.length} output(s), but you passed loss=${e.loss}.`);t=e.loss.map(o=>M1(o))}else{let a=M1(e.loss);this.outputs.forEach(o=>{t.push(a)})}this.lossFunctions=t,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let a=0;a{for(let a=0;a1&&(this.metricsTensors.push([o,a]),this.metricsNames.push(this.outputNames[a]+"_loss"))}});let s=kB(e.metrics,this.outputNames),r=(a,o,i)=>{this.outputNames.length>1&&(o=this.outputNames[a]+"_"+o),this.metricsNames.push(o),this.metricsTensors.push([i,a])};al("metric",()=>{for(let a=0;a{let c="",u,d,p;for(let h of l){if(typeof h=="string"&&["accuracy","acc","crossentropy","ce"].indexOf(h)!==-1){let m=this.internalOutputShapes[a];m[m.length-1]===1||this.lossFunctions[a]===Lf?["accuracy","acc"].indexOf(h)!==-1?d=z1:["crossentropy","ce"].indexOf(h)!==-1&&(d=ww):this.lossFunctions[a]===zf?["accuracy","acc"].indexOf(h)!==-1?d=kw:["crossentropy","ce"].indexOf(h)!==-1&&(d=Iw):["accuracy","acc"].indexOf(h)!==-1?d=L1:["crossentropy","ce"].indexOf(h)!==-1&&(d=B1);let g;["accuracy","acc"].indexOf(h)!==-1?g="acc":["crossentropy","ce"].indexOf(h)!==-1&&(g="ce"),p=d,u=c+g}else p=QL(h),u=c+Vf(h);let f;al(u,()=>{f=p}),r(a,u,f)}})(o)}}),this.collectedTrainableWeights=this.trainableWeights}checkTrainableWeightsConsistency(){this.collectedTrainableWeights!=null&&this.trainableWeights.length!==this.collectedTrainableWeights.length&&console.warn("Discrepancy between trainableweights and collected trainable weights. Did you set `model.trainable` without calling `model.compile()` afterwards?")}evaluate(e,t,n={}){let s=n.batchSize==null?32:n.batchSize;H1(s);let r=!0,a=this.standardizeUserDataXY(e,t,r,s);try{let o=a[0].concat(a[1]);this.makeTestFunction();let i=this.testFunction,l=this.testLoop(i,o,s,n.verbose,n.steps);return os(l)}finally{ul(a[0],e),ul(a[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),AB(this,e,t)}checkNumSamples(e,t,n,s="steps"){let r;if(n!=null){if(r=null,t!=null)throw new q(`If ${s} is set, batchSize must be null or undefined.Got batchSize = ${t}`)}else if(e!=null)Array.isArray(e)?r=e[0].shape[0]:r=e.shape[0];else throw new q(`Either the input data should have a defined shape, or ${s} shoud be specified.`);return r}execute(e,t){if(Array.isArray(t)&&t.length===0)throw new q("`outputs` is an empty Array, which is not allowed.");let n=Array.isArray(t),s=n?t:[t],r=this.retrieveSymbolicTensors(s),a=new ll;if(e instanceof Ye&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new q(`The number of inputs provided (${e.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let i=0;io.name);for(let o=0;o0){let s=[];throw t.forEach((r,a)=>{r==null&&s.push(e[a])}),new q(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(s)}`)}return t}predictLoop(e,t=32,n=!1){return j(()=>{let s=this.checkNumSamples(e);if(n)throw new Be("Verbose predictLoop() is not implemented yet.");let r=q1(s,t),a=this.outputs.map(o=>[]);for(let o=0;o{let l=r[o][0],c=r[o][1],u=Ed(e,l,c),d=[];if(Array.isArray(u))for(let h=0;ha[c].push(l));return os(a.map(o=>It(o,0)))})}predict(e,t={}){let n=Fw(e);zw(n,this.inputNames,this.feedInputShapes,!1);try{let s=t.batchSize==null?32:t.batchSize;return H1(s),this.predictLoop(n,s)}finally{ul(n,e)}}predictOnBatch(e){zw(e,this.inputNames,this.feedInputShapes,!0);let t=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,t)}standardizeUserDataXY(e,t,n=!0,s){if(this.optimizer_==null)throw new dr("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");let r=[];for(let a=0;a0&&e[0].shape[0]%s!=0)throw new q(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${s}. Found: ${e[0].shape[0]} sample(s).`);return[e,t]}async standardizeUserData(e,t,n,s,r=!0,a){let[o,i]=this.standardizeUserDataXY(e,t,r,a);if(n!=null)throw new Error("sample weight is not supported yet.");let l=null;if(s!=null){let c=Rw(s,this.outputNames);l=[];for(let u=0;u{let a=this.checkNumSamples(t,n,r,"steps"),o=[];if(s>0)throw new Be("Verbose mode is not implemented yet.");if(r!=null)throw new Be("steps mode in testLoop() is not implemented yet");{let i=q1(a,n),l=Zt(pr(0,a));for(let c=0;c1&&(r+=`_${Hv(e.slice(0,n),s)}`),t.push(r)}return t}makeTrainFunction(){return e=>{let t=[],n=e.slice(0,this.inputs.length),s=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),r=e.slice(this.inputs.length+this.outputs.length,this.inputs.length+this.outputs.length*2),a=[],o=()=>{let u=[];for(let f=0;f1&&f{h=ie(h,f)}),h},i=this.collectedTrainableWeights.map(u=>u.read()),l=!0;return[this.optimizer_.minimize(o,l,i)].concat(a)}}makeTestFunction(){this.testFunction=e=>j(()=>{let t=[],n,s=e.slice(0,this.inputs.length),r=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),a=[];for(let l=0;lta(t))}else{let t=Object.keys(this.loss);e={};let n=this.loss;for(let s of t)if(typeof n[s]=="string")e[s]=ta(n[s]);else throw new Error("Serialization of non-string loss is not supported.")}return e}getMetricIdentifiers(){if(typeof this.metrics=="string"||typeof this.metrics=="function")return[ta(Vf(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(e=>ta(Vf(e)));{let e={};for(let t in this.metrics)e[t]=ta(Vf(this.metrics[t]));return e}}getTrainingConfig(){return{loss:this.getLossIdentifiers(),metrics:this.getMetricIdentifiers(),optimizer_config:{class_name:this.optimizer.getClassName(),config:this.optimizer.getConfig()}}}loadTrainingConfig(e){if(e.weighted_metrics!=null)throw new Error("Loading weight_metrics is not supported yet.");if(e.loss_weights!=null)throw new Error("Loading loss_weights is not supported yet.");if(e.sample_weight_mode!=null)throw new Error("Loading sample_weight_mode is not supported yet.");let t=Td(e.optimizer_config),n=mr(t),s;if(typeof e.loss=="string")s=sl(e.loss);else if(Array.isArray(e.loss))s=e.loss.map(a=>sl(a));else if(e.loss!=null){s={};for(let a in e.loss)s[a]=sl(e.loss[a])}let r;if(Array.isArray(e.metrics))r=e.metrics.map(a=>sl(a));else if(e.metrics!=null){r={};for(let a in e.metrics)r[a]=sl(e.metrics[a])}this.compile({loss:s,metrics:r,optimizer:n})}async save(e,t){if(typeof e=="string"){let l=ns.getSaveHandlers(e);if(l.length===0)throw new q(`Cannot find any save handlers for URL '${e}'`);if(l.length>1)throw new q(`Found more than one (${l.length}) save handlers for URL '${e}'`);e=l[0]}if(e.save==null)throw new q("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");let n=await ns.encodeWeights(this.getNamedWeights(t)),s=!1,r=null,o={modelTopology:this.toJSON(r,s),format:IB,generatedBy:`TensorFlow.js tfjs-layers v${U1}`,convertedBy:null};if((t==null?!1:t.includeOptimizer)&&this.optimizer!=null){o.trainingConfig=this.getTrainingConfig();let l="optimizer",{data:c,specs:u}=await ns.encodeWeights(await this.optimizer.getWeights(),l);n.specs.push(...u),n.data=ns.concatenateArrayBuffers([n.data,c])}if(this.userDefinedMetadata!=null){let l=!0;Cw(this.userDefinedMetadata,this.name,l),o.userDefinedMetadata=this.userDefinedMetadata}return o.weightData=n.data,o.weightSpecs=n.specs,e.save(o)}setUserDefinedMetadata(e){Cw(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}};na.className="Model";le.registerClass(na);var Lw=class extends na{};Lw.className="Functional";le.registerClass(Lw);async function SB(e,t){"modelTopology"in e||(e={modelTopology:e}),e=e;let n=e.modelTopology;n.model_config!=null&&(n=n.model_config);let s=Td(n),r=mr(s,t);if(e.weightsManifest!=null){let a=await ns.loadWeights(e.weightsManifest,e.pathPrefix,r.weights.map(i=>i.originalName)),o={};for(let i of r.weights)o[i.originalName]=a[i.originalName];r.loadWeights(o),Q(a)}return r}async function CB(e,t){if(t==null&&(t={}),typeof e=="string"){let n=ns.getLoadHandlers(e,t);if(n.length===0)n.push(ns.browserHTTPRequest(e,t));else if(n.length>1)throw new q(`Found more than one (${n.length}) load handlers for URL '${e}'`);e=n[0]}return TB(e,void 0,t)}async function TB(e,t,n){if(n==null&&(n={}),e.load==null)throw new q("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");let s=await e.load(),r=s.modelTopology;r.model_config!=null&&(r=r.model_config);let a=n.strict==null?!0:n.strict,o=s.weightData!=null&&s.weightSpecs!=null&&a,i=mr(Td(r),t,o),l=s.trainingConfig;if(l!=null&&i.loadTrainingConfig(l),s.userDefinedMetadata!=null&&i.setUserDefinedMetadata(s.userDefinedMetadata),s.weightData!=null){if(s.weightSpecs==null)throw new q("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");let{modelWeights:c,optimizerWeights:u}=NB(s.weightData,s.weightSpecs);i.loadWeights(c,a),i.optimizer!=null&&u.length>0&&await i.optimizer.setWeights(u),Q(c),Q(u.map(d=>d.tensor))}return i}function NB(e,t){let n=ns.decodeWeights(e,t),s={},r=[];return t.forEach(a=>{a.group==="optimizer"?r.push({name:a.name,tensor:n[a.name]}):s[a.name]=n[a.name]}),{modelWeights:s,optimizerWeights:r}}var K1=class extends na{constructor(e){super({inputs:[],outputs:[]});if(e=e||{},this.trainable=!0,this.built=!1,this.name=e.name!=null?e.name:Df("sequential_"),e.layers!=null)for(let t of e.layers)this.add(t)}checkShape(e){if(e.inboundNodes[0].outputTensors[0].shape.some(n=>n<0))throw new q(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){let t=e instanceof K1||e instanceof na,n;if(t){if(n=e,n.outputs.length!==1)throw new q("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(n.inputs.length!==1)throw new q("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.")}if(this.outputs.length===0){if(e.inboundNodes.length===0){if(e.batchInputShape==null)throw new q("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");let s=pw({batchShape:e.batchInputShape,dtype:e.dtype,name:e.name+"_input"});e.apply(s)}if(t)this.outputs=n.outputs,this.inputs=n.inputs;else{if(e.inboundNodes.length!==1)throw new q(`A layer added to a Sequential model must not already be connected somewhere else. LayersModel received layer ${e.name} which has ${e.inboundNodes.length} pre-existing inbound connections.`);if(e.inboundNodes[0].outputTensors.length!==1)throw new q("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[e.inboundNodes[0].outputTensors[0]],this.inputs=dw(this.outputs[0])}this.inboundNodes=[],new Ff({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:nl(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(s=>s.shape),outputShapes:this.outputs[0].shape})}else{let s=e.apply(this.outputs[0]);if(Array.isArray(s))throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[s],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(e),this.built=!1}pop(){if(this.layers.length===0)throw new TypeError("There are no layers in the model.");if(this.layers.pop(),this.layers.length===0)this.outputs=[],this.inboundNodes=[],this.outboundNodes=[];else{let e=this.layers.length-1;this.layers[e].outboundNodes=[],this.outputs=[this.layers[e].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}}call(e,t){return this.model==null&&this.build(),this.model.call(e,t)}build(e){if(mt(e),this.inputs.length===0||this.outputs.length===0)throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");this.model=new na({inputs:this.inputs,outputs:this.outputs[0],name:this.name+"_model"}),this.model.trainable=this.trainable,this.supportsMasking=this.model.supportsMasking,this.inputLayers=this.model.inputLayers,this.inputLayersNodeIndices=this.model.inputLayersNodeIndices,this.inputLayersTensorIndices=this.model.inputLayersTensorIndices,this.outputLayers=this.model.outputLayers,this.outputLayersNodeIndices=this.model.outputLayersNodeIndices,this.outputLayersTensorIndices=this.model.outputLayersTensorIndices,this.nodesByDepth=this.model.nodesByDepth,this.containerNodes=this.model.containerNodes,this.outputNames=this.model.outputNames,this.inputNames=this.model.inputNames,this.built=!0}countParams(){return this.built||this.build(),super.countParams()}summary(e,t,n=console.log){this.built||this.build(),super.summary(e,t,n)}setWeights(e){this.model==null&&this.build(),this.model.setWeights(e)}evaluate(e,t,n={}){if(!this.built)throw new dr("The model needs to be compiled before being used.");return this.model.evaluate(e,t,n)}async evaluateDataset(e,t){if(!this.built)throw new dr("The model needs to be compiled before being used.");return this.model.evaluateDataset(e,t)}predict(e,t={}){return this.model==null&&this.build(),this.model.predict(e,t)}predictOnBatch(e){return this.model==null&&this.build(),this.model.predictOnBatch(e)}compile(e){this.build(),this.model.compile(e),this.optimizer_=this.model.optimizer,this.isOptimizerOwned=this.model.isOptimizerOwned,this.loss=this.model.loss,this.metrics=this.model.metrics,this.metricsTensors=this.model.metricsTensors,this.metricsNames=this.model.metricsNames}get optimizer(){return this.model==null?void 0:this.model.optimizer}set optimizer(e){this.model.optimizer=e}async fit(e,t,n={}){if(!this.built)throw new dr("The model needs to be compiled before being used.");return this.model.fit(e,t,n)}async fitDataset(e,t){if(!this.built)throw new dr("The model needs to be compiled before being used.");return this.model.fitDataset(e,t)}async trainOnBatch(e,t){return this.model.trainOnBatch(e,t)}static fromConfig(e,t,n={},s=!1){let r,a={};if(t instanceof Array){if(t[0].className==null||t[0].className==="Merge")throw new q("Legacy serialization format not supported yet.");r=t}else v.assert(t.layers!=null,()=>"When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field."),r=t.layers,delete t.layers,a=t;let o=new e(a);if(!(o instanceof K1))throw new Be(`Sequential.fromConfig called on non-Sequential input: ${o}`);for(let i of r){let c=mr(i,void 0,s);s&&c.setFastWeightInitDuringBuild(!0),o.add(c)}return o}set stopTraining(e){if(this.model==null)throw new q("Cannot set the stopTraining property of a sequential model before it is compiled.");this.model.stopTraining=e}get stopTraining(){if(this.model==null)throw new q("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining}getConfig(){let e=[];for(let t of this.layers){let n={};n.className=t.getClassName(),n.config=t.getConfig(),e.push(n)}return{name:this.name,layers:e}}},Gf=K1;Gf.className="Sequential";le.registerClass(Gf);function EB(e){return new na(e)}function RB(e){return new Gf(e)}function $B(e,t){return t==null&&(t={}),CB(e,t)}function Bw(e){return pw(e)}function DB(e,t){F1.registerCallbackConstructor(e,t)}var ls=class extends le.Serializable{getConfig(){return{}}},Ww=class extends ls{apply(e,t=1){return rL(e,t)}};Ww.className="elu";le.registerClass(Ww);var Vw=class extends ls{apply(e){return Y2(e)}};Vw.className="selu";le.registerClass(Vw);var Uw=class extends ls{apply(e){return Rr(e)}};Uw.className="relu";le.registerClass(Uw);var Gw=class extends ls{apply(e){return j(()=>hd(6,Rr(e)))}};Gw.className="relu6";le.registerClass(Gw);var Hw=class extends ls{apply(e){return e}};Hw.className="linear";le.registerClass(Hw);var jw=class extends ls{apply(e){return hs(e)}};jw.className="sigmoid";le.registerClass(jw);var qw=class extends ls{apply(e){return oL(e)}};qw.className="hardSigmoid";le.registerClass(qw);var Xw=class extends ls{apply(e){return Cu(e)}};Xw.className="softplus";le.registerClass(Xw);var Kw=class extends ls{apply(e){return aL(e)}};Kw.className="softsign";le.registerClass(Kw);var Zw=class extends ls{apply(e){return vu(e)}};Zw.className="tanh";le.registerClass(Zw);var Z1=class extends ls{apply(e,t=-1){return $u(e,t)}};Z1.className="softmax";le.registerClass(Z1);var Yw=class extends ls{apply(e,t=-1){return B2(e,t)}};Yw.className="logSoftmax";le.registerClass(Yw);var Jw=class extends ls{apply(e,t=1){return j(()=>W(hs(W(e,t)),e))}};Jw.className="swish";le.registerClass(Jw);var Qw=class extends ls{apply(e){return j(()=>W(e,vu(Cu(e))))}};Qw.className="mish";le.registerClass(Qw);function Ro(e){return e.getClassName()}function Y1(e,t={}){return bd(e,le.SerializationMap.getMap().classNameMap,t,"activation")}function $o(e){if(e==null){let t={};return t.className="linear",t.config={},Y1(t)}if(typeof e=="string"){let t={};return t.className=e,t.config={},Y1(t)}else return e instanceof ls?e:Y1(e)}function J1(e){if(e!=null&&typeof e!="object")throw new Error(`Argument to L1L2 regularizer's constructor is expected to be an object, but received: ${e}`)}var ek=class extends le.Serializable{},Rd=class extends ek{constructor(e){super();J1(e),this.l1=e==null||e.l1==null?.01:e.l1,this.l2=e==null||e.l2==null?.01:e.l2,this.hasL1=this.l1!==0,this.hasL2=this.l2!==0}apply(e){return j(()=>{let t=Ht([1]);return this.hasL1&&(t=ie(t,Ie(W(this.l1,rn(e))))),this.hasL2&&(t=ie(t,Ie(W(this.l2,Id(e))))),G(t,[])})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}};Rd.className="L1L2";le.registerClass(Rd);function _B(e){return J1(e),new Rd({l1:e!=null?e.l1:null,l2:0})}function PB(e){return J1(e),new Rd({l2:e!=null?e.l2:null,l1:0})}var tk={l1l2:"L1L2"};function bt(e){return h1(e)}function nk(e,t={}){return bd(e,le.SerializationMap.getMap().classNameMap,t,"regularizer")}function Dt(e){if(e==null)return null;if(typeof e=="string"){let n={className:e in tk?tk[e]:e,config:{}};return nk(n)}else return e instanceof ek?e:nk(e)}var Q1=class extends nt{constructor(e){super(e==null?{}:e);this.supportsMasking=!0,e!=null&&(this.maxValue=e.maxValue)}call(e,t){e=Ve(e);let n=Rr(e);return this.maxValue!=null&&(n=fs(n,0,this.maxValue)),n}computeOutputShape(e){return e}getConfig(){let e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}};Q1.className="ReLU";le.registerClass(Q1);var eA=class extends nt{constructor(e){super(e==null?{}:e);this.DEFAULT_ALPHA=.3,e==null&&(e={}),this.alpha=e.alpha==null?this.DEFAULT_ALPHA:e.alpha}call(e,t){let n=Ve(e);return Kh(n,this.alpha)}computeOutputShape(e){return e}getConfig(){let e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};eA.className="LeakyReLU";le.registerClass(eA);var tA=class extends nt{constructor(e){super(e==null?{}:e);if(this.DEFAULT_ALPHA_INITIALIZER="zeros",e==null&&(e={}),this.supportsMasking=!0,this.alphaInitializer=$t(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=Dt(e.alphaRegularizer),this.alphaConstraint=un(e.alphaConstraint),e.sharedAxes==null)this.sharedAxes=null;else if(Array.isArray(e.sharedAxes))this.sharedAxes=e.sharedAxes;else if(typeof e.sharedAxes=="number")this.sharedAxes=[e.sharedAxes];else throw new q(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`)}build(e){e=mt(e);let t=e.slice(1);if(this.sharedAxes!=null)for(let s of this.sharedAxes)t[s-1]=1;this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);let n={};if(this.sharedAxes!=null)for(let s=1;s(jt(t),t==="channelsFirst"?et(e,[0,2,3,1]):e))}function sk(e,t){return j(()=>(jt(t),t==="channelsFirst"?et(e,[0,2,3,4,1]):e))}function FB(e,t,n,s=1,r="valid",a,o=1){return j(()=>{if(a==null&&(a=cr()),jt(a),e.shape.length!==3)throw new q(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(t.shape.length!==3)throw new q(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(n!=null&&n.shape.length!==1)throw new q(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);if(a==="channelsFirst"&&(e=et(e,[0,2,1])),r==="causal")throw new Be("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let i=D2(e,t,s,r==="same"?"same":"valid","NWC",o);return n!=null&&(i=hr(i,n)),i})}function rk(e,t,n,s=[1,1],r="valid",a,o,i=null){return j(()=>{if(a==null&&(a=cr()),jt(a),e.rank!==3&&e.rank!==4)throw new q(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(t.rank!==3&&t.rank!==4)throw new q(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let l=aA(e,a);if(r==="causal")throw new Be("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=So.conv2d({x:l,filter:t,strides:s,pad:r==="same"?"same":"valid",dilations:o,dataFormat:"NHWC",bias:n,activation:i}),a==="channelsFirst"&&(l=et(l,[0,3,1,2])),l})}function OB(e,t,n,s=[1,1,1],r="valid",a,o){return j(()=>{if(a==null&&(a=cr()),jt(a),e.rank!==4&&e.rank!==5)throw new q(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(t.rank!==4&&t.rank!==5)throw new q(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let i=sk(e,a);if(r==="causal")throw new Be("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return i=F2(i,t,s,r==="same"?"same":"valid","NDHWC",o),n!=null&&(i=hr(i,n)),a==="channelsFirst"&&(i=et(i,[0,4,1,2,3])),i})}var oA=class extends nt{constructor(e,t){super(t);if(this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",oA.verifyArgs(t),this.rank=e,xn(this.rank,"rank"),this.rank!==1&&this.rank!==2&&this.rank!==3)throw new Be(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=zu(t.kernelSize,e,"kernelSize"),this.strides=zu(t.strides==null?1:t.strides,e,"strides"),this.padding=t.padding==null?"valid":t.padding,$s(this.padding),this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,jt(this.dataFormat),this.activation=$o(t.activation),this.useBias=t.useBias==null?!0:t.useBias,this.biasInitializer=$t(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=un(t.biasConstraint),this.biasRegularizer=Dt(t.biasRegularizer),this.activityRegularizer=Dt(t.activityRegularizer),this.dilationRate=zu(t.dilationRate==null?1:t.dilationRate,e,"dilationRate"),this.rank===1&&Array.isArray(this.dilationRate)&&this.dilationRate.length!==1)throw new q(`dilationRate must be a number or an array of a single number for 1D convolution, but received ${JSON.stringify(this.dilationRate)}`);if(this.rank===2){if(typeof this.dilationRate=="number")this.dilationRate=[this.dilationRate,this.dilationRate];else if(this.dilationRate.length!==2)throw new q(`dilationRate must be a number or array of two numbers for 2D convolution, but received ${JSON.stringify(this.dilationRate)}`)}else if(this.rank===3){if(typeof this.dilationRate=="number")this.dilationRate=[this.dilationRate,this.dilationRate,this.dilationRate];else if(this.dilationRate.length!==3)throw new q(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}}static verifyArgs(e){if($r("kernelSize"in e,"required key 'kernelSize' not in config"),typeof e.kernelSize!="number"&&!m1(e.kernelSize,"number",1,3))throw new q(`BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received ${JSON.stringify(e.kernelSize)}.`)}getConfig(){let e={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:Ro(this.activation),useBias:this.useBias,biasInitializer:Mt(this.biasInitializer),biasRegularizer:bt(this.biasRegularizer),activityRegularizer:bt(this.activityRegularizer),biasConstraint:ln(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}},$d=class extends oA{constructor(e,t){super(e,t);this.kernel=null,$d.verifyArgs(t),this.filters=t.filters,xn(this.filters,"filters"),this.kernelInitializer=$t(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=un(t.kernelConstraint),this.kernelRegularizer=Dt(t.kernelRegularizer)}build(e){e=mt(e);let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new q(`The channel dimension of the input should be defined. Found ${e[t]}`);let n=e[t],s=this.kernelSize.concat([n,this.filters]);this.kernel=this.addWeight("kernel",s,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[{ndim:this.rank+2,axes:{[t]:n}}],this.built=!0}call(e,t){return j(()=>{e=Ve(e);let n,s=this.bias==null?null:this.bias.read(),r=qv(this.activation.getClassName());if(r!=null&&this.rank===2)n=rk(e,this.kernel.read(),s,this.strides,this.padding,this.dataFormat,this.dilationRate,r);else{if(this.rank===1)n=FB(e,this.kernel.read(),s,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)n=rk(e,this.kernel.read(),s,this.strides,this.padding,this.dataFormat,this.dilationRate);else if(this.rank===3)n=OB(e,this.kernel.read(),s,this.strides,this.padding,this.dataFormat,this.dilationRate);else throw new Be("convolutions greater than 3D are not implemented yet.");this.activation!=null&&(n=this.activation.apply(n))}return n})}computeOutputShape(e){e=mt(e);let t=[],n=this.dataFormat==="channelsLast"?e.slice(1,e.length-1):e.slice(2);for(let r=0;r 0 but got ${JSON.stringify(e.filters)}`)}},ak=class extends $d{constructor(e){super(2,e);ak.verifyArgs(e)}getConfig(){let e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!m1(e.kernelSize,"number",1,2))throw new q(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}},Hf=ak;Hf.className="Conv2D";le.registerClass(Hf);var ok=class extends $d{constructor(e){super(3,e);ok.verifyArgs(e)}getConfig(){let e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!(Array.isArray(e.kernelSize)&&(e.kernelSize.length===1||e.kernelSize.length===3)))throw new q(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}},jf=ok;jf.className="Conv3D";le.registerClass(jf);var iA=class extends Hf{constructor(e){super(e);if(this.inputSpec=[new Yt({ndim:4})],this.padding!=="same"&&this.padding!=="valid")throw new q(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=mt(e),e.length!==4)throw new q("Input should have rank 4; Received input shape: "+JSON.stringify(e));let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new q("The channel dimension of the inputs should be defined. Found `None`.");let n=e[t],s=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",s,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new Yt({ndim:4,axes:{[t]:n}})],this.built=!0}call(e,t){return j(()=>{let n=Ve(e);if(n.shape.length!==4)throw new q(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${n.shape.length}`);let s=n.shape,r=s[0],a,o;this.dataFormat==="channelsFirst"?(a=2,o=3):(a=1,o=2);let i=s[a],l=s[o],c=this.kernelSize[0],u=this.kernelSize[1],d=this.strides[0],p=this.strides[1],h=Fr(i,d,c,this.padding),f=Fr(l,p,u,this.padding),m=[r,h,f,this.filters];this.dataFormat!=="channelsLast"&&(n=et(n,[0,2,3,1]));let g=P2(n,this.kernel.read(),m,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(g=et(g,[0,3,1,2])),this.bias!=null&&(g=hr(g,this.bias.read(),this.dataFormat)),this.activation!=null&&(g=this.activation.apply(g)),g})}computeOutputShape(e){e=mt(e);let t=e.slice(),n,s,r;this.dataFormat==="channelsFirst"?(n=1,s=2,r=3):(n=3,s=1,r=2);let a=this.kernelSize[0],o=this.kernelSize[1],i=this.strides[0],l=this.strides[1];return t[n]=this.filters,t[s]=Fr(t[s],i,a,this.padding),t[r]=Fr(t[r],l,o,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};iA.className="Conv2DTranspose";le.registerClass(iA);var lA=class extends jf{constructor(e){super(e);if(this.inputSpec=[new Yt({ndim:5})],this.padding!=="same"&&this.padding!=="valid")throw new q(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=mt(e),e.length!==5)throw new q("Input should have rank 5; Received input shape: "+JSON.stringify(e));let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new q("The channel dimension of the inputs should be defined. Found `None`.");let n=e[t],s=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",s,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new Yt({ndim:5,axes:{[t]:n}})],this.built=!0}call(e,t){return j(()=>{let n=Ve(e);if(n.shape.length!==5)throw new q(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${n.shape.length}`);let s=n.shape,r=s[0],a,o,i;this.dataFormat==="channelsFirst"?(i=2,a=3,o=4):(i=1,a=2,o=3);let l=s[i],c=s[a],u=s[o],d=this.kernelSize[0],p=this.kernelSize[1],h=this.kernelSize[2],f=this.strides[0],m=this.strides[1],g=this.strides[2],A=Fr(l,f,d,this.padding),y=Fr(c,m,p,this.padding),x=Fr(u,g,h,this.padding),b=[r,A,y,x,this.filters];this.dataFormat!=="channelsLast"&&(n=et(n,[0,2,3,4,1]));let w=M3(n,this.kernel.read(),b,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(w=et(w,[0,4,1,2,3])),this.bias!==null&&(w=hr(w,this.bias.read(),this.dataFormat)),this.activation!==null&&(w=this.activation.apply(w)),w})}computeOutputShape(e){e=mt(e);let t=e.slice(),n,s,r,a;this.dataFormat==="channelsFirst"?(n=1,s=2,r=3,a=4):(n=4,s=1,r=2,a=3);let o=this.kernelSize[0],i=this.kernelSize[1],l=this.kernelSize[2],c=this.strides[0],u=this.strides[1],d=this.strides[2];return t[n]=this.filters,t[s]=Fr(t[s],c,o,this.padding),t[r]=Fr(t[r],u,i,this.padding),t[a]=Fr(t[a],d,l,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};lA.className="Conv3DTranspose";le.registerClass(lA);var ik=class extends $d{constructor(e,t){super(e,t);if(this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,t.filters==null)throw new q("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(t.kernelInitializer!=null||t.kernelRegularizer!=null||t.kernelConstraint!=null)throw new q("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(t.padding!=null&&t.padding!=="same"&&t.padding!=="valid")throw new q(`SeparableConv${this.rank}D supports only padding modes: 'same' and 'valid', but received ${JSON.stringify(t.padding)}`);this.depthMultiplier=t.depthMultiplier==null?1:t.depthMultiplier,this.depthwiseInitializer=$t(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=Dt(t.depthwiseRegularizer),this.depthwiseConstraint=un(t.depthwiseConstraint),this.pointwiseInitializer=$t(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=Dt(t.pointwiseRegularizer),this.pointwiseConstraint=un(t.pointwiseConstraint)}build(e){if(e=mt(e),e.length{e=Ve(e);let n;if(this.rank===1)throw new Be("1D separable convolution is not implemented yet.");return this.rank===2&&(this.dataFormat==="channelsFirst"&&(e=et(e,[0,2,3,1])),n=av(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(n=hr(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),this.dataFormat==="channelsFirst"&&(n=et(n,[0,3,1,2])),n})}getConfig(){let e=super.getConfig();return delete e.rank,delete e.kernelInitializer,delete e.kernelRegularizer,delete e.kernelConstraint,e.depthwiseInitializer=Mt(this.depthwiseInitializer),e.pointwiseInitializer=Mt(this.pointwiseInitializer),e.depthwiseRegularizer=bt(this.depthwiseRegularizer),e.pointwiseRegularizer=bt(this.pointwiseRegularizer),e.depthwiseConstraint=ln(this.depthwiseConstraint),e.pointwiseConstraint=ln(this.pointwiseConstraint),e}};ik.className="SeparableConv";var uA=class extends ik{constructor(e){super(2,e)}};uA.className="SeparableConv2D";le.registerClass(uA);var lk=class extends $d{constructor(e){super(1,e);lk.verifyArgs(e),this.inputSpec=[{ndim:3}]}getConfig(){let e=super.getConfig();return delete e.rank,delete e.dataFormat,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!m1(e.kernelSize,"number",1,1))throw new q(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}},cA=lk;cA.className="Conv1D";le.registerClass(cA);var dA=class extends nt{constructor(e){super(e);typeof e.cropping=="number"?this.cropping=[[e.cropping,e.cropping],[e.cropping,e.cropping]]:typeof e.cropping[0]=="number"?this.cropping=[[e.cropping[0],e.cropping[0]],[e.cropping[1],e.cropping[1]]]:this.cropping=e.cropping,this.dataFormat=e.dataFormat===void 0?"channelsLast":e.dataFormat,this.inputSpec=[{ndim:4}]}computeOutputShape(e){return this.dataFormat==="channelsFirst"?[e[0],e[1],e[2]-this.cropping[0][0]-this.cropping[0][1],e[3]-this.cropping[1][0]-this.cropping[1][1]]:[e[0],e[1]-this.cropping[0][0]-this.cropping[0][1],e[2]-this.cropping[1][0]-this.cropping[1][1],e[3]]}call(e,t){return j(()=>{if(e=Ve(e),this.dataFormat==="channelsLast"){let n=wf(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return wf(n,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}else{let n=wf(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return wf(n,this.cropping[1][0],e.shape[3]-this.cropping[1][1]-this.cropping[1][0],4)}})}getConfig(){let e={cropping:this.cropping,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};dA.className="Cropping2D";le.registerClass(dA);var pA=class extends nt{constructor(e){super(e);this.DEFAULT_SIZE=[2,2],this.inputSpec=[{ndim:4}],this.size=e.size==null?this.DEFAULT_SIZE:e.size,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,jt(this.dataFormat),this.interpolation=e.interpolation==null?"nearest":e.interpolation,Yz(this.interpolation)}computeOutputShape(e){if(this.dataFormat==="channelsFirst"){let t=e[2]==null?null:this.size[0]*e[2],n=e[3]==null?null:this.size[1]*e[3];return[e[0],e[1],t,n]}else{let t=e[1]==null?null:this.size[0]*e[1],n=e[2]==null?null:this.size[1]*e[2];return[e[0],t,n,e[3]]}}call(e,t){return j(()=>{let n=Ve(e),s=n.shape;if(this.dataFormat==="channelsFirst"){n=et(n,[0,2,3,1]);let r=this.size[0]*s[2],a=this.size[1]*s[3],o=this.interpolation==="nearest"?$e.resizeNearestNeighbor(n,[r,a]):$e.resizeBilinear(n,[r,a]);return et(o,[0,3,1,2])}else{let r=this.size[0]*s[1],a=this.size[1]*s[2];return this.interpolation==="nearest"?$e.resizeNearestNeighbor(n,[r,a]):$e.resizeBilinear(n,[r,a])}})}getConfig(){let e={size:this.size,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};pA.className="UpSampling2D";le.registerClass(pA);function MB(e,t,n=[1,1],s="valid",r,a){return j(()=>{r==null&&(r=cr()),jt(r);let o=aA(e,r);if(e.rank!==4)throw new q(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(t.rank!==4)throw new q(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return o=cd(o,t,n,s==="same"?"same":"valid","NHWC",a),r==="channelsFirst"&&(o=et(o,[0,3,1,2])),o})}var hA=class extends oA{constructor(e){super(2,e);this.depthwiseKernel=null,this.depthMultiplier=e.depthMultiplier==null?1:e.depthMultiplier,this.depthwiseInitializer=$t(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=un(e.depthwiseConstraint),this.depthwiseRegularizer=Dt(e.depthwiseRegularizer)}build(e){if(e=mt(e),e.length<4)throw new q(`Inputs to DepthwiseConv2D should have rank 4. Received input shape: ${JSON.stringify(e)}.`);let t=this.dataFormat==="channelsFirst"?1:3;if(e[t]==null||e[t]<0)throw new q(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);let n=e[t],s=[this.kernelSize[0],this.kernelSize[1],n,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",s,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[n*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return j(()=>{e=Ve(e);let n=MB(e,this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(n=hr(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),n})}computeOutputShape(e){e=mt(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2],s=this.dataFormat==="channelsFirst"?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,r=gr(t,this.kernelSize[0],this.padding,this.strides[0]),a=gr(n,this.kernelSize[1],this.padding,this.strides[1]);return this.dataFormat==="channelsFirst"?[e[0],s,r,a]:[e[0],r,a,s]}getConfig(){let e=super.getConfig();return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=Mt(this.depthwiseInitializer),e.depthwiseRegularizer=bt(this.depthwiseRegularizer),e.depthwiseConstraint=ln(this.depthwiseRegularizer),e}};hA.className="DepthwiseConv2D";le.registerClass(hA);function uk(e,t,n,s){if(Array.isArray(e)){if(t!=null||n!=null)throw new q("When inputs is an array, neither initialState or constants should be provided");s!=null&&(n=e.slice(e.length-s,e.length),e=e.slice(0,e.length-s)),e.length>1&&(t=e.slice(1,e.length)),e=e[0]}function r(a){return a==null||Array.isArray(a)?a:[a]}return t=r(t),n=r(n),{inputs:e,initialState:t,constants:n}}function ck(e,t,n,s=!1,r,a,o=!1,i=!1){return j(()=>{let l=t.shape.length;if(l<3)throw new q(`Input should be at least 3D, but is ${l}D.`);let c=[1,0].concat(pr(2,l));if(t=et(t,c),a!=null)throw new Be("The rnn() functoin of the deeplearn.js backend does not support constants yet.");o&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),r!=null&&(r=de(de(r,"bool"),"float32"),r.rank===l-1&&(r=Kt(r,-1)),r=et(r,c)),s&&(t=Rs(t,0),r!=null&&(r=Rs(r,0)));let u=[],d,p=n,h=t.shape[0],f=as(t),m;r!=null&&(m=as(r));for(let A=0;Ae(y,p));if(r==null)d=x[0],p=x[1];else{let b=j(()=>{let w=m[A],k=ye(Es(w),w),S=ie(W(x[0],w),W(p[0],k)),E=p.map((P,F)=>ie(W(x[1][F],w),W(P,k)));return{output:S,newStates:E}});d=b.output,p=b.newStates}i&&u.push(d)}let g;return i&&(g=Pn(u,1)),[d,g,p]})}var dk=class extends nt{constructor(e){super(e);let t;if(e.cell==null)throw new q("cell property is missing for the constructor of RNN.");if(Array.isArray(e.cell)?t=new Kf({cells:e.cell}):t=e.cell,t.stateSize==null)throw new q("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");this.cell=t,this.returnSequences=e.returnSequences==null?!1:e.returnSequences,this.returnState=e.returnState==null?!1:e.returnState,this.goBackwards=e.goBackwards==null?!1:e.goBackwards,this._stateful=e.stateful==null?!1:e.stateful,this.unroll=e.unroll==null?!1:e.unroll,this.supportsMasking=!0,this.inputSpec=[new Yt({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){if(this.states_==null){let e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;return pr(0,e).map(t=>null)}else return this.states_}setStates(e){this.states_=e}computeOutputShape(e){D1(e)&&(e=e[0]),e=e;let t=this.cell.stateSize;Array.isArray(t)||(t=[t]);let n=t[0],s;if(this.returnSequences?s=[e[0],e[1],n]:s=[e[0],n],this.returnState){let r=[];for(let a of t)r.push([e[0],a]);return[s].concat(r)}else return s}computeMask(e,t){return j(()=>{Array.isArray(t)&&(t=t[0]);let n=this.returnSequences?t:null;if(this.returnState){let s=this.states.map(r=>null);return[n].concat(s)}else return n})}get states(){if(this.states_==null){let e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,t=[];for(let n=0;no.shape[o.shape.length-1]),a))throw new q(`An initialState was passed that is not compatible with cell.stateSize. Received stateSpec=${this.stateSpec}; However cell.stateSize is ${this.cell.stateSize}`)}else this.stateSpec=a.map(o=>new Yt({shape:[null,o]}));this.stateful&&this.resetStates()}resetStates(e,t=!1){j(()=>{if(!this.stateful)throw new ea("Cannot call resetStates() on an RNN Layer that is not stateful.");let n=this.inputSpec[0].shape[0];if(n==null)throw new q("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(this.states_==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(s=>Ht([n,s])):this.states_=[Ht([n,this.cell.stateSize])];else if(e==null)Q(this.states_),this.keptStates!=null&&(Q(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(s=>Ht([n,s])):this.states_[0]=Ht([n,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new q(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);t===!0?this.keptStates.push(this.states_.slice()):Q(this.states_);for(let s=0;syn(s.clone()))})}apply(e,t){let n=t==null?null:t.initialState,s=t==null?null:t.constants;t==null&&(t={});let r=uk(e,n,s,this.numConstants);e=r.inputs,n=r.initialState,s=r.constants;let a=[],o=[];if(n!=null){t.initialState=n,a=a.concat(n),this.stateSpec=[];for(let l of n)this.stateSpec.push(new Yt({shape:l.shape}));o=o.concat(this.stateSpec)}if(s!=null&&(t.constants=s,a=a.concat(s),this.numConstants=s.length),a[0]instanceof fr){let l=[e].concat(a),c=this.inputSpec.concat(o),u=this.inputSpec;this.inputSpec=c;let d=super.apply(l,t);return this.inputSpec=u,d}else return super.apply(e,t)}call(e,t){return j(()=>{let n=t==null?null:t.mask,s=t==null?null:t.training,r=t==null?null:t.initialState;e=Ve(e),r==null&&(this.stateful?r=this.states_:r=this.getInitialState(e));let a=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(r.length!==a)throw new q(`RNN Layer has ${a} state(s) but was passed ${r.length} initial state(s).`);this.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");let o={training:s},l=ck((h,f)=>{let m=this.cell.call([h].concat(f),o);return[m[0],m.slice(1)]},e,r,this.goBackwards,n,null,this.unroll,this.returnSequences),c=l[0],u=l[1],d=l[2];this.stateful&&this.resetStates(d,s);let p=this.returnSequences?u:c;return this.returnState?[p].concat(d):p})}getInitialState(e){return j(()=>{let t=Ht(e.shape);return t=Ie(t,[1,2]),t=kd(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(n=>n>1?k1(t,[1,n]):t):this.cell.stateSize>1?[k1(t,[1,this.cell.stateSize])]:[t]})}get trainableWeights(){return this.trainable?this.cell.trainableWeights:[]}get nonTrainableWeights(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.cell!=null&&this.cell.setFastWeightInitDuringBuild(e)}getConfig(){let e=super.getConfig(),t={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};this.numConstants!=null&&(t.numConstants=this.numConstants);let n=this.cell.getConfig();return this.getClassName()===dk.className&&(t.cell={className:this.cell.getClassName(),config:n}),{...n,...e,...t}}static fromConfig(e,t,n={}){let s=t.cell,r=mr(s,n);return new e(Object.assign(t,{cell:r}))}},sa=dk;sa.className="RNN";le.registerClass(sa);var Dd=class extends nt{},qf=class extends Dd{constructor(e){super(e);this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,xn(this.units,"units"),this.activation=$o(e.activation==null?this.DEFAULT_ACTIVATION:e.activation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=$t(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=$t(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=$t(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Dt(e.kernelRegularizer),this.recurrentRegularizer=Dt(e.recurrentRegularizer),this.biasRegularizer=Dt(e.biasRegularizer),this.kernelConstraint=un(e.kernelConstraint),this.recurrentConstraint=un(e.recurrentConstraint),this.biasConstraint=un(e.biasConstraint),this.dropout=Pu([1,No([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Pu([1,No([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=mt(e),this.kernel=this.addWeight("kernel",[e[e.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return j(()=>{if(e=e,e.length!==2)throw new q(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let n=e[1];e=e[0];let s=t.training==null?!1:t.training;0Es(e),rate:this.dropout,training:s,dropoutFunc:this.dropoutFunc})),0Es(n),rate:this.recurrentDropout,training:s,dropoutFunc:this.dropoutFunc}));let r,a=this.dropoutMask,o=this.recurrentDropoutMask;a!=null?r=Dr(W(e,a),this.kernel.read()):r=Dr(e,this.kernel.read()),this.bias!=null&&(r=hr(r,this.bias.read())),o!=null&&(n=W(n,o));let i=ie(r,Dr(n,this.recurrentKernel.read()));return this.activation!=null&&(i=this.activation.apply(i)),[i,i]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:Ro(this.activation),useBias:this.useBias,kernelInitializer:Mt(this.kernelInitializer),recurrentInitializer:Mt(this.recurrentInitializer),biasInitializer:Mt(this.biasInitializer),kernelRegularizer:bt(this.kernelRegularizer),recurrentRegularizer:bt(this.recurrentRegularizer),biasRegularizer:bt(this.biasRegularizer),activityRegularizer:bt(this.activityRegularizer),kernelConstraint:ln(this.kernelConstraint),recurrentConstraint:ln(this.recurrentConstraint),biasConstraint:ln(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return{...e,...t}}};qf.className="SimpleRNNCell";le.registerClass(qf);var fA=class extends sa{constructor(e){e.cell=new qf(e);super(e)}call(e,t){return j(()=>{this.cell.dropoutMask!=null&&(Q(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Q(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let n=t==null?null:t.mask,s=t==null?null:t.training,r=t==null?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:r})})}static fromConfig(e,t){return new e(t)}};fA.className="SimpleRNN";le.registerClass(fA);var Xf=class extends Dd{constructor(e){super(e);if(this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.resetAfter)throw new q("GRUCell does not support reset_after parameter set to true.");this.units=e.units,xn(this.units,"units"),this.activation=$o(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=$o(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=$t(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=$t(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=$t(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Dt(e.kernelRegularizer),this.recurrentRegularizer=Dt(e.recurrentRegularizer),this.biasRegularizer=Dt(e.biasRegularizer),this.kernelConstraint=un(e.kernelConstraint),this.recurrentConstraint=un(e.recurrentConstraint),this.biasConstraint=un(e.biasConstraint),this.dropout=Pu([1,No([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Pu([1,No([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=mt(e);let t=e[e.length-1];this.kernel=this.addWeight("kernel",[t,this.units*3],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*3],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units*3],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return j(()=>{if(e=e,e.length!==2)throw new q(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);let n=t.training==null?!1:t.training,s=e[1];e=e[0],0Es(e),rate:this.dropout,training:n,count:3,dropoutFunc:this.dropoutFunc})),0Es(s),rate:this.recurrentDropout,training:n,count:3,dropoutFunc:this.dropoutFunc}));let r=this.dropoutMask,a=this.recurrentDropoutMask,o,i,l;0{this.cell.dropoutMask!=null&&(Q(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Q(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let n=t==null?null:t.mask,s=t==null?null:t.training,r=t==null?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:r})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}};mA.className="GRU";le.registerClass(mA);var _d=class extends Dd{constructor(e){super(e);this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,xn(this.units,"units"),this.activation=$o(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=$o(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=$t(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=$t(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=$t(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=Dt(e.kernelRegularizer),this.recurrentRegularizer=Dt(e.recurrentRegularizer),this.biasRegularizer=Dt(e.biasRegularizer),this.kernelConstraint=un(e.kernelConstraint),this.recurrentConstraint=un(e.recurrentConstraint),this.biasConstraint=un(e.biasConstraint),this.dropout=Pu([1,No([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Pu([1,No([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=[this.units,this.units],this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){var t;e=mt(e);let n=e[e.length-1];this.kernel=this.addWeight("kernel",[n,this.units*4],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*4],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint);let s;if(this.useBias){if(this.unitForgetBias){let r=this.biasInitializer,a=this.units;s=new(t=class extends Zs{apply(o,i){let l=r.apply([a]),c=new If().apply([a]),u=r.apply([a*2]);return nw(nw(l,c),u)}},t.className="CustomInit",t)}else s=this.biasInitializer;this.bias=this.addWeight("bias",[this.units*4],null,s,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,t){return j(()=>{let n=t.training==null?!1:t.training;if(e=e,e.length!==3)throw new q(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let s=e[1],r=e[2];e=e[0],0Es(e),rate:this.dropout,training:n,count:4,dropoutFunc:this.dropoutFunc})),0Es(s),rate:this.recurrentDropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));let a=this.dropoutMask,o=this.recurrentDropoutMask,i,l,c,u;0{this.cell.dropoutMask!=null&&(Q(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Q(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let n=t==null?null:t.mask,s=t==null?null:t.training,r=t==null?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:r})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}};gA.className="LSTM";le.registerClass(gA);var Kf=class extends Dd{constructor(e){super(e);this.cells=e.cells}get stateSize(){let e=[];for(let t of this.cells.slice().reverse())Array.isArray(t.stateSize)?e.push(...t.stateSize):e.push(t.stateSize);return e}call(e,t){return j(()=>{e=e;let n=e.slice(1),s=[];for(let o of this.cells.slice().reverse())Array.isArray(o.stateSize)?s.push(n.splice(0,o.stateSize.length)):s.push(n.splice(0,1));s.reverse();let r=[],a;for(let o=0;o{al(`RNNCell_${s}`,()=>{n.build(e),Array.isArray(n.stateSize)?t=n.stateSize[0]:t=n.stateSize,e=[e[0],t]})}),this.built=!0}getConfig(){let e=super.getConfig(),t=r=>({className:r.getClassName(),config:r.getConfig()}),s={cells:this.cells.map(t)};return{...e,...s}}static fromConfig(e,t,n={}){let s=[];for(let r of t.cells)s.push(mr(r,n));return new e({cells:s})}get trainableWeights(){if(!this.trainable)return[];let e=[];for(let t of this.cells)e.push(...t.trainableWeights);return e}get nonTrainableWeights(){let e=[];for(let t of this.cells)e.push(...t.nonTrainableWeights);if(!this.trainable){let t=[];for(let n of this.cells)t.push(...n.trainableWeights);return t.concat(e)}return e}getWeights(){let e=[];for(let t of this.cells)e.push(...t.weights);return _1(e)}setWeights(e){let t=[];for(let n of this.cells){let s=n.weights.length,r=e.splice(s);for(let a=0;aa!=null?a(t(),n):rw(t(),n),i=()=>Sd(o,t,s);return!r||r<=1?yn(i().clone()):Array(r).fill(void 0).map(i).map(c=>yn(c.clone()))}var pk=class extends sa{constructor(e){if(e.unroll)throw new Be("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new Be("It is not possible at the moment to stack convolutional cells.");super(e);this.inputSpec=[new Yt({ndim:5})]}call(e,t){return j(()=>{if(this.cell.dropoutMask!=null&&(Q(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Q(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new q("ConvRNN2D cell does not support constants");let n=t==null?null:t.mask,s=t==null?null:t.training,r=t==null?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:r})})}computeOutputShape(e){let t=this.computeSingleOutputShape(e);return this.returnSequences||(t=[t[0],...t.slice(2)]),this.returnState&&(t=[t,...Array(2).fill([e[0],...t.slice(-3)])]),t}getInitialState(e){return j(()=>{let{stateSize:t}=this.cell,n=e.shape,s=this.computeSingleOutputShape(n),r=[s[0],...s.slice(2)],a=Ht(r);return Array.isArray(t)?Array(t.length).fill(a):[a]})}resetStates(e,t=!1){j(()=>{if(!this.stateful)throw new ea("Cannot call resetStates() on an RNN Layer that is not stateful.");let n=this.inputSpec[0].shape,s=this.computeSingleOutputShape(n),r=[s[0],...s.slice(2)];if(n[0]==null)throw new q("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(this.getStates()==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>Ht(r)):this.states_=[Ht(r)];else if(e==null)Q(this.states_),this.keptStates!=null&&(Q(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>Ht(r)):this.states_[0]=Ht(r);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new q(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);t?this.keptStates.push(this.states_.slice()):Q(this.states_);for(let o=0;oyn(o.clone()))})}computeSingleOutputShape(e){let{dataFormat:t,filters:n,kernelSize:s,padding:r,strides:a,dilationRate:o}=this.cell,i=t==="channelsFirst",l=e[i?3:2],c=e[i?4:3],u=gr(l,s[0],r,a[0],o[0]),d=gr(c,s[1],r,a[1],o[1]);return[...e.slice(0,2),...i?[n,u,d]:[u,d,n]]}};pk.className="ConvRNN2D";var Zf=class extends _d{constructor(e){let{filters:t,kernelSize:n,strides:s,padding:r,dataFormat:a,dilationRate:o}=e;super({...e,units:t});this.filters=t,xn(this.filters,"filters"),this.kernelSize=zu(n,2,"kernelSize"),this.kernelSize.forEach(i=>xn(i,"kernelSize")),this.strides=zu(s||1,2,"strides"),this.strides.forEach(i=>xn(i,"strides")),this.padding=r||"valid",$s(this.padding),this.dataFormat=a||"channelsLast",jt(this.dataFormat),this.dilationRate=zu(o||1,2,"dilationRate"),this.dilationRate.forEach(i=>xn(i,"dilationRate"))}build(e){var t;e=mt(e);let n=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[n]==null)throw new q(`The channel dimension of the input should be defined. Found ${e[n]}`);let s=e[n],r=4,a=this.kernelSize.concat([s,this.filters*r]);this.kernel=this.addWeight("kernel",a,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);let o=this.kernelSize.concat([this.filters,this.filters*r]);if(this.recurrentKernel=this.addWeight("recurrent_kernel",o,null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){let i;if(this.unitForgetBias){let l=this.biasInitializer,c=this.filters;i=new(t=class extends Zs{apply(u,d){let p=l.apply([c]),h=gs([c]),f=l.apply([c*2]);return w1([p,h,f])}},t.className="CustomInit",t)}else i=this.biasInitializer;this.bias=this.addWeight("bias",[this.filters*r],null,i,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(e,t){return j(()=>{if(e.length!==3)throw new q(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let n=t.training||!1,s=e[0],r=e[1],a=e[2],o=4;0Es(s),rate:this.dropout,training:n,count:o,dropoutFunc:this.dropoutFunc}));let i=this.dropoutMask,l=(ee,Y,se)=>!Y||!Y[se]?ee:W(Y[se],ee),c=l(s,i,0),u=l(s,i,1),d=l(s,i,2),p=l(s,i,3);0Es(r),rate:this.recurrentDropout,training:n,count:o,dropoutFunc:this.dropoutFunc}));let h=this.recurrentDropoutMask,f=l(r,h,0),m=l(r,h,1),g=l(r,h,2),A=l(r,h,3),y=3,[x,b,w,k]=Sn(this.kernel.read(),o,y),[S,E,P,F]=this.useBias?Sn(this.bias.read(),o):[null,null,null,null];c=this.inputConv(c,x,S,this.padding),u=this.inputConv(u,b,E,this.padding),d=this.inputConv(d,w,P,this.padding),p=this.inputConv(p,k,F,this.padding);let[R,_,T,M]=Sn(this.recurrentKernel.read(),o,y);f=this.recurrentConv(f,R),m=this.recurrentConv(m,_),g=this.recurrentConv(g,T),A=this.recurrentConv(A,M);let U=this.recurrentActivation.apply(ie(c,f)),H=this.recurrentActivation.apply(ie(u,m)),z=ie(W(H,a),W(U,this.activation.apply(ie(d,g)))),X=W(this.recurrentActivation.apply(ie(p,A)),this.activation.apply(z));return[X,X,z]})}getConfig(){let{units:e,...t}=super.getConfig(),n={filters:this.filters,kernelSize:this.kernelSize,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,strides:this.strides};return{...t,...n}}inputConv(e,t,n,s){let r=ko(e,t,this.strides,s||"valid",this.dataFormat==="channelsFirst"?"NCHW":"NHWC",this.dilationRate);return n?hr(r,n,this.dataFormat):r}recurrentConv(e,t){return ko(e,t,1,"same",this.dataFormat==="channelsFirst"?"NCHW":"NHWC")}};Zf.className="ConvLSTM2DCell";le.registerClass(Zf);var AA=class extends pk{constructor(e){let t=new Zf(e);super({...e,cell:t})}static fromConfig(e,t){return new e(t)}};AA.className="ConvLSTM2D";le.registerClass(AA);var Yf=class extends nt{constructor(e){super(e);this.rate=Math.max(Math.min(e.rate,1),0),this.noiseShape=e.noiseShape,this.seed=e.seed,this.supportsMasking=!0}getNoiseShape(e){if(this.noiseShape==null)return this.noiseShape;let t=e.shape,n=[];for(let s=0;s{this.invokeCallHook(e,t);let n=Ve(e);if(0rw(n,this.rate,r,this.seed),()=>n,s)}return e})}getConfig(){let e={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},t=super.getConfig();return Object.assign(e,t),e}dispose(){return super.dispose()}};Yf.className="Dropout";le.registerClass(Yf);var yA=class extends Yf{constructor(e){super(e);this.inputSpec=[{ndim:3}]}getNoiseShape(e){let t=e.shape;return[t[0],1,t[2]]}};yA.className="SpatialDropout1D";le.registerClass(yA);var xA=class extends nt{constructor(e){super(e);if(this.activation=null,this.useBias=!0,this.kernel=null,this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.batchInputShape==null&&e.inputShape==null&&e.inputDim!=null){let t=null;e.batchSize!=null&&(t=e.batchSize),this.batchInputShape=[t,e.inputDim]}this.units=e.units,xn(this.units,"units"),this.activation=$o(e.activation),e.useBias!=null&&(this.useBias=e.useBias),this.kernelInitializer=$t(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=$t(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=un(e.kernelConstraint),this.biasConstraint=un(e.biasConstraint),this.kernelRegularizer=Dt(e.kernelRegularizer),this.biasRegularizer=Dt(e.biasRegularizer),this.activityRegularizer=Dt(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){e=mt(e);let t=e[e.length-1];this.kernel==null&&(this.kernel=this.addWeight("kernel",[t,this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint))),this.inputSpec=[{minNDim:2,axes:{[-1]:t}}],this.built=!0}computeOutputShape(e){e=mt(e);let t=e.slice();return t[t.length-1]=this.units,t}call(e,t){return j(()=>{this.invokeCallHook(e,t);let n=Ve(e),s=qv(this.activation.getClassName()),r;return s!=null?r=Dr(n,this.kernel.read(),s,this.bias?this.bias.read():null):(r=Dr(n,this.kernel.read()),this.bias!=null&&(r=hr(r,this.bias.read())),this.activation!=null&&(r=this.activation.apply(r))),r})}getConfig(){let e={units:this.units,activation:Ro(this.activation),useBias:this.useBias,kernelInitializer:Mt(this.kernelInitializer),biasInitializer:Mt(this.biasInitializer),kernelRegularizer:bt(this.kernelRegularizer),biasRegularizer:bt(this.biasRegularizer),activityRegularizer:bt(this.activityRegularizer),kernelConstraint:ln(this.kernelConstraint),biasConstraint:ln(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}};xA.className="Dense";le.registerClass(xA);var bA=class extends nt{constructor(e){e=e||{};super(e);this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=mt(e);for(let t of e.slice(1))if(t==null)throw new q(`The shape of the input to "Flatten" is not fully defined (got ${e.slice(1)}). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.`);return[e[0],To(e,1)]}call(e,t){return j(()=>{this.invokeCallHook(e,t);let n=Ve(e);if(this.dataFormat==="channelsFirst"&&n.rank>1){let s=[0];for(let r=2;r{this.invokeCallHook(e,t);let n=Ve(e);return this.activation.apply(n)})}getConfig(){let e={activation:Ro(this.activation)},t=super.getConfig();return Object.assign(e,t),e}};vA.className="Activation";le.registerClass(vA);var wA=class extends nt{constructor(e){super(e);this.n=e.n,this.inputSpec=[{ndim:2}]}computeOutputShape(e){return[e[0],this.n,e[1]]}call(e,t){return j(()=>(e=Ve(e),tL(e,this.n)))}getConfig(){let e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}};wA.className="RepeatVector";le.registerClass(wA);var kA=class extends nt{constructor(e){super(e);this.targetShape=e.targetShape;for(let t=0;t{this.invokeCallHook(e,t);let n=Ve(e),s=n.shape,r=s.slice(0,1).concat(this.fixUnknownDimension(s.slice(1),this.targetShape));return G(n,r)})}getConfig(){let e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}};kA.className="Reshape";le.registerClass(kA);var IA=class extends nt{constructor(e){super(e);if(e.dims==null)throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if(!Array.isArray(e.dims))throw new Error(`Permute constructor requires \`dims\` to be an Array, but received ${e.dims} instead.`);let t=pr(1,e.dims.length+1);if(!v.arraysEqual(e.dims.slice().sort(),t))throw new Error("Invalid permutation `dims`: "+JSON.stringify(e.dims)+" `dims` must contain consecutive integers starting from 1.");this.dims=e.dims,this.dimsIncludingBatch=[0].concat(this.dims),this.inputSpec=[new Yt({ndim:this.dims.length+1})]}computeOutputShape(e){e=mt(e);let t=e.slice();return this.dims.forEach((n,s)=>{t[s+1]=e[n]}),t}call(e,t){return et(Ve(e),this.dimsIncludingBatch)}getConfig(){let e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}};IA.className="Permute";le.registerClass(IA);var SA=class extends nt{constructor(e){super(e==null?{}:e);this.supportsMasking=!0,e!=null?this.maskValue=e.maskValue==null?0:e.maskValue:this.maskValue=0}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={maskValue:this.maskValue};return Object.assign(t,e),t}computeMask(e,t){let n=Ve(e),s=-1;return Uh(Tu(n,this.maskValue),s)}call(e,t){return j(()=>{this.invokeCallHook(e,t);let n=Ve(e),s=-1,r=!0,a=Uh(Tu(n,this.maskValue),s,r);return W(n,de(a,n.dtype))})}};SA.className="Masking";le.registerClass(SA);var CA=class extends nt{constructor(e){super(e);if(this.embeddings=null,this.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",e.batchInputShape==null&&e.inputShape==null){let t=null;e.batchSize!=null&&(t=e.batchSize),e.inputLength==null?this.batchInputShape=[t,null]:this.batchInputShape=[t].concat(Ct(e.inputLength))}this.inputDim=e.inputDim,xn(this.inputDim,"inputDim"),this.outputDim=e.outputDim,xn(this.outputDim,"outputDim"),this.embeddingsInitializer=$t(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=Dt(e.embeddingsRegularizer),this.activityRegularizer=Dt(e.activityRegularizer),this.embeddingsConstraint=un(e.embeddingsConstraint),this.maskZero=e.maskZero,this.supportsMasking=e.maskZero,this.inputLength=e.inputLength}build(e){this.embeddings=this.addWeight("embeddings",[this.inputDim,this.outputDim],this.dtype,this.embeddingsInitializer,this.embeddingsRegularizer,!0,this.embeddingsConstraint),this.built=!0}warnOnIncompatibleInputShape(e){}computeMask(e,t){return j(()=>this.maskZero?(e=Ve(e),Tu(e,tt(e))):null)}computeOutputShape(e){if(e=mt(e),this.inputLength==null)return[...e,this.outputDim];let t=Ct(this.inputLength);if(t.length!==e.length-1)throw new q(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let n=0;for(let s=0;s{this.invokeCallHook(e,t);let n=Ve(e);n.dtype!=="int32"&&(n=vf(n,"int32"));let s=sw(this.embeddings.read(),G(n,[n.size]));return G(s,mt(this.computeOutputShape(n.shape)))})}getConfig(){let e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:Mt(this.embeddingsInitializer),embeddingsRegularizer:bt(this.embeddingsRegularizer),activityRegularizer:bt(this.activityRegularizer),embeddingsConstraint:ln(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}};CA.className="Embedding";le.registerClass(CA);var cl=class extends nt{constructor(e){super(e||{});this.supportsMasking=!0}mergeFunction(e){throw new Be}computeElementwiseOpOutputShape(e,t){if(e==null||t==null)return null;if(e.length1)throw new q(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(e)}.`);let n=e[0]==null?null:e[0].slice(1);for(let r=1;rr.length);e.indexOf(null)===-1&&Co(s).length===1?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return j(()=>{if(e=e,this.reshapeRequired){let n=[],s=e.map(r=>r.rank);if(s.indexOf(null)===-1){let r=No(s);for(let a of e){let o=a.rank;for(let i=0;i1){let c=pr(1,l).concat([0]);n.push(et(i,c)),r=!0}else n.push(i)}let a=this.mergeFunction(n),o=a.rank;if(r){if(o==null){let i=a.shape,l=i.length,c=i[l-1],u=[c].concat(i.slice(0,i.length-1));a=G(et(G(a,[-1,c]),[1,0]),u)}else if(o>1){let i=[o-1].concat(pr(0,o-1));a=et(a,i)}}return a}}else return this.mergeFunction(e)})}computeOutputShape(e){e=e;let t;e[0]==null?t=null:t=e[0].slice(1);for(let s=1;s{if(t==null)return null;if(!Array.isArray(t))throw new q("`mask` should be an Array");if(!Array.isArray(e))throw new q("`inputs` should be an Array");if(t.length!==e.length)throw new q(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${e.length} vs ${t.length})`);if(t.every(s=>s==null))return null;t=t.map(s=>s==null?s:Kt(s,0));let n=t[0];for(let s=1;s{let t=e[0].clone();for(let n=1;n{let t=e[0].clone();for(let n=1;n{let t=e[0].clone();for(let n=1;n{let t=e[0];for(let n=1;n{let t=e[0];for(let n=1;n1)throw new q("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return j(()=>w1(e,this.axis))}computeOutputShape(e){if(!(Array.isArray(e)&&Array.isArray(e[0])))throw new q("A `Concatenate` layer should be called on a list of inputs.");let t=e,n=t[0].slice(),s=this.axis<0?n.length+this.axis:this.axis;for(let r of t.slice(1)){if(n[s]==null||r[s]==null){n[s]=null;break}n[s]+=r[s]}return n}computeMask(e,t){if(t==null)return null;if(!Array.isArray(t))throw new q("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new q("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new q(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return j(()=>{let n=!0;if(t.forEach(a=>{if(a!=null){n=!1;return}}),n)return null;let s=[];for(let a=0;a3||t.shape.length>3)throw new Be("batchDot is not implemented for tensors of 4D or higher rank yet");if(v.assert(e.shape.length>=2,()=>`batchDot requires the rank of x to be >= 2, but got ${e.shape.length}`),v.assert(e.shape.length>=2,()=>`batchDot requires the rank of y to be >= 2, but got ${t.shape.length}`),typeof n=="number"&&(n=[n,n]),e.dtype==="complex64"||t.dtype==="complex64")throw new Be("batchDot is not implemented for complex64-type Tensors yet.");let s=e.shape.length,r=t.shape.length;n==null&&(n=[s-1,r-2]);let a=n;return j(()=>{let o;if(s>r){o=s-r;let l=[];for(let c=0;cs){o=r-s;let l=[];for(let c=0;c0){let l;s>r?l=s+r-3:l=s-1;let c=[];for(let u=l;u"A `Dot` layer should be called on a list of exactly 2 inputs.");let t=e[0],n=e[1];if(t.length>3||n.length>3)throw new Be("Dot layer does not support tensors of 4D or higher rank yet.");let s=this.interpretAxes(t,n);if(t[s[0]]!==n[s[1]])throw new q(`Dimension incompatibility: ${t[s[0]]} !== ${n[s[1]]}`)}mergeFunction(e){if(e.length!==2)throw new q(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);let t=e[0],n=e[1],s;return Array.isArray(this.axes)?s=this.axes.map((r,a)=>Pd(r,e[a].shape.length)):s=[Pd(this.axes,t.shape.length),Pd(this.axes,n.shape.length)],this.normalize&&(t=Of(t,s[0]),n=Of(n,s[1])),zB(t,n,s)}interpretAxes(e,t){let n;return Array.isArray(this.axes)?n=this.axes:n=[Pd(this.axes,e.length),Pd(this.axes,t.length)],n}computeOutputShape(e){v.assert(Array.isArray(e)&&e.length===2&&Array.isArray(e[0])&&Array.isArray(e[1]),()=>"A `Dot` layer should be called on a list of exactly 2 inputs.");let t=e[0].slice(),n=e[1].slice();if(t.length>3||n.length>3)throw new Be("Dot layer does not support tensors of 4D or higher rank yet.");let s=this.interpretAxes(t,n);t.splice(s[0],1),n.splice(s[1],1),n.splice(0,1);let r=t.concat(n);return r.length===1&&r.push(1),r}computeMask(e,t){return null}getConfig(){let e={axes:this.axes,normalize:this.normalize},t=super.getConfig();return Object.assign(e,t),e}};_A.className="Dot";le.registerClass(_A);var PA=class extends nt{constructor(e){super(e);this.supportsMasking=!0,this.stddev=e.stddev}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={stddev:this.stddev};return Object.assign(t,e),t}call(e,t){return j(()=>{this.invokeCallHook(e,t);let n=Ve(e);return Sd(()=>ie(kf(n.shape,0,this.stddev),n),()=>n,t.training||!1)})}};PA.className="GaussianNoise";le.registerClass(PA);var FA=class extends nt{constructor(e){super(e);this.supportsMasking=!0,this.rate=e.rate}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return j(()=>{this.invokeCallHook(e,t);let n=Ve(e);return this.rate>0&&this.rate<1?Sd(()=>{let r=Math.sqrt(this.rate/(1-this.rate));return W(n,kf(n.shape,1,r))},()=>n,t.training||!1):n})}};FA.className="GaussianDropout";le.registerClass(FA);var OA=class extends nt{constructor(e){super(e);this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||Ve(e).shape}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return j(()=>{if(this.rate<1&&this.rate>0){let n=this._getNoiseShape(e);return Sd(()=>{let r=Ve(e),a=1.6732632423543772,o=1.0507009873554805,i=-a*o,l=Yi(Nu(n),this.rate);l=vf(l,"float32");let c=((1-this.rate)*(1+this.rate*i**2))**-.5,u=-c*i*this.rate,d=ie(W(r,l),W(ie(l,-1),i));return ie(W(d,c),u)},()=>Ve(e),t.training||!1)}return e})}};OA.className="AlphaDropout";le.registerClass(OA);function Fd(e,t,n,s,r,a=.001){let o;if(e.rank===2)o=N3(e,t,n,s,r,a);else if(e.rank===3)o=E3(e,t,n,s,r,a);else if(e.rank===4)o=R3(e,t,n,s,r,a);else throw new Be(`batchNormalization is not implemented for array of rank ${e.rank} yet`);return o}function LB(e,t,n,s,r=.001){return j(()=>{let a=tf(e,s),o=a.mean,i=a.variance;return[Fd(e,o,i,n,t,r),o,i]})}function BB(e,t,n,s,r=.001){return j(()=>{let a=tf(e,s),o=a.mean,i=a.variance,l=[];for(let f of pr(0,e.rank))s.indexOf(f)!==-1?l.push(1):l.push(e.shape[f]);let c=G(o,l),u=G(i,l),d=t==null?null:G(t,l),p=n==null?null:G(n,l);return[Fd(e,c,u,p,d,r),o,i]})}function WB(e,t,n,s,r=.001){return v.arraysEqual(s.slice().sort(),pr(0,e.rank-1))?LB(e,t,n,s,r):BB(e,t,n,s,r)}var MA=class extends nt{constructor(e){e==null&&(e={});super(e);this.supportsMasking=!0,this.axis=e.axis==null?-1:e.axis,this.momentum=e.momentum==null?.99:e.momentum,this.epsilon=e.epsilon==null?.001:e.epsilon,this.center=e.center==null?!0:e.center,this.scale=e.scale==null?!0:e.scale,this.betaInitializer=$t(e.betaInitializer||"zeros"),this.gammaInitializer=$t(e.gammaInitializer||"ones"),this.movingMeanInitializer=$t(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=$t(e.movingVarianceInitializer||"ones"),this.betaConstraint=un(e.betaConstraint),this.gammaConstraint=un(e.gammaConstraint),this.betaRegularizer=Dt(e.betaRegularizer),this.gammaRegularizer=Dt(e.gammaRegularizer)}build(e){e=mt(e);let t=this.axis>=0?this.axis:this.axis+e.length,n=e[t];if(n==null)throw new q(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new Yt({ndim:e.length,axes:{[t]:n}})];let s=[n];this.scale&&(this.gamma=this.addWeight("gamma",s,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",s,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",s,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",s,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(e,t){return j(()=>{let n=t.training==null?!1:t.training,s=Ve(e),r=s.shape,a=r.length,o=pr(0,a),i=this.axis>=0?this.axis:this.axis+a;o.splice(i,1);let l=nl(1,a);l[i]=r[i];let c=o.slice();c.sort();let u=!v.arraysEqual(c,pr(0,a).slice(0,a-1)),d=()=>{if(u){let A=G(this.movingMean.read(),l),y=G(this.movingVariance.read(),l),x=this.center?G(this.beta.read(),l):null,b=this.scale?G(this.gamma.read(),l):null;return Fd(s,A,y,x,b,this.epsilon)}else return Fd(s,this.movingMean.read(),this.movingVariance.read(),this.beta==null?null:this.beta.read(),this.gamma==null?null:this.gamma.read(),this.epsilon)};if(!n)return d();let[p,h,f]=WB(s,this.gamma.read(),this.beta.read(),o,this.epsilon),m=(A,y,x)=>{j(()=>{let b=1-x,w=A.read(),k=W(ye(w,y),b);A.write(ye(w,k))})};return(()=>{m(this.movingMean,h,this.momentum),m(this.movingVariance,f,this.momentum)})(),p})}getConfig(){let e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Mt(this.betaInitializer),gammaInitializer:Mt(this.gammaInitializer),movingMeanInitializer:Mt(this.movingMeanInitializer),movingVarianceInitializer:Mt(this.movingVarianceInitializer),betaRegularizer:bt(this.betaRegularizer),gammaRegularizer:bt(this.gammaRegularizer),betaConstraint:ln(this.betaConstraint),gammaConstraint:ln(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}};MA.className="BatchNormalization";le.registerClass(MA);var zA=class extends nt{constructor(e){e==null&&(e={});super(e);if(this.axis=e.axis==null?-1:e.axis,typeof this.axis=="number"){if(!Number.isInteger(this.axis))throw new Error(`Expected axis to be an integer, but received ${this.axis}`)}else if(Array.isArray(this.axis)){for(let t of this.axis)if(!Number.isInteger(t))throw new Error(`Expected axis to be an array of integers, but received ${JSON.stringify(this.axis)}`)}else throw new Error(`Expected axis to be an integer or an array of integers, but received ${JSON.stringify(this.axis)}`);this.epsilon=e.epsilon==null?.001:e.epsilon,this.center=e.center==null?!0:e.center,this.scale=e.scale==null?!0:e.scale,this.betaInitializer=$t(e.betaInitializer||"zeros"),this.gammaInitializer=$t(e.gammaInitializer||"ones"),this.betaRegularizer=Dt(e.betaRegularizer),this.gammaRegularizer=Dt(e.gammaRegularizer),this.supportsMasking=!0}build(e){e=mt(e);let t=e.length;typeof this.axis=="number"&&(this.axis=[this.axis]);for(let r=0;r=t)throw new Error(`Invalid axis: ${r}`);if(this.axis.length!==Co(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);let n=this.axis.map(r=>e[r]),s=!0;this.scale?this.gamma=this.addWeight("gamma",n,"float32",this.gammaInitializer,this.gammaRegularizer,s):this.gamma=null,this.center?this.beta=this.addWeight("beta",n,"float32",this.betaInitializer,this.betaRegularizer,s):this.beta=null,this.built=!0}call(e,t){let n=Ve(e),s=n.shape,r=s.length;return j(()=>{let a=!0,{mean:o,variance:i}=tf(n,this.axis,a),l=nl(1,r);for(let f of this.axis)l[f]=s[f];let c=f=>f!=null&&f.shape.length!==r?G(f,l):f,u=c(this.gamma.read()),d=c(this.beta.read()),p=[],h=[];for(let f=0;f{if(e.rank!==4)throw new q(`temporalPadding expects input tensor to be 4-D, but received a ${e.rank}-D tensor.`);if(t==null&&(t=[[1,1],[1,1]]),t.length!==2||t[0].length!==2||t[1].length!==2)throw new q("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(n==null&&(n=cr()),n!=="channelsLast"&&n!=="channelsFirst")throw new q(`Unknown data format: ${n}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let s;return n==="channelsFirst"?s=[[0,0],[0,0],t[0],t[1]]:s=[[0,0],t[0],t[1],[0,0]],qs(e,s)})}var LA=class extends nt{constructor(e){e==null&&(e={});super(e);if(this.dataFormat=e.dataFormat==null?cr():e.dataFormat,e.padding==null)this.padding=[[1,1],[1,1]];else if(typeof e.padding=="number")this.padding=[[e.padding,e.padding],[e.padding,e.padding]];else{if(e.padding=e.padding,e.padding.length!==2)throw new q(`ZeroPadding2D expects padding to be a length-2 array, but received a length-${e.padding.length} array.`);let t,n;if(typeof e.padding[0]=="number")t=[e.padding[0],e.padding[0]],n=[e.padding[1],e.padding[1]];else{if(e.padding=e.padding,e.padding[0].length!==2)throw new q(`ZeroPadding2D expects height padding to be a length-2 array, but received a length-${e.padding[0].length} array.`);if(t=e.padding[0],e.padding[1].length!==2)throw new q(`ZeroPadding2D expects width padding to be a length-2 array, but received a length-${e.padding[1].length} array.`);n=e.padding[1]}this.padding=[t,n]}this.inputSpec=[new Yt({ndim:4})]}computeOutputShape(e){e=mt(e);let t,n;return this.dataFormat==="channelsFirst"?(e[2]!=null&&e[2]>=0?t=e[2]+this.padding[0][0]+this.padding[0][1]:t=null,e[3]!=null&&e[3]>=0?n=e[3]+this.padding[1][0]+this.padding[1][1]:n=null,[e[0],e[1],t,n]):(e[1]!=null&&e[1]>=0?t=e[1]+this.padding[0][0]+this.padding[0][1]:t=null,e[2]!=null&&e[2]>=0?n=e[2]+this.padding[1][0]+this.padding[1][1]:n=null,[e[0],t,n,e[3]])}call(e,t){return j(()=>VB(Ve(e),this.padding,this.dataFormat))}getConfig(){let e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};LA.className="ZeroPadding2D";le.registerClass(LA);function Jf(e,t,n,s,r,a){return j(()=>{jt(r),Yv(a),$s(s),n==null&&(n=[1,1]),s==null&&(s="valid"),r==null&&(r=cr()),a==null&&(a="max"),e=aA(e,r);let o,i=s==="same"?"same":"valid";return a==="max"?o=Qh(e,t,n,i):o=Hh(e,t,n,i),r==="channelsFirst"&&(o=et(o,[0,3,1,2])),o})}function hk(e,t,n,s,r,a){return j(()=>{jt(r),Yv(a),$s(s),n==null&&(n=[1,1,1]),s==null&&(s="valid"),r==null&&(r=cr()),a==null&&(a="max"),e=sk(e,r);let o,i=s==="same"?"same":"valid";return a==="max"?o=G2(e,t,n,i):o=R2(e,t,n,i),r==="channelsFirst"&&(o=et(o,[0,4,1,2,3])),o})}var fk=class extends nt{constructor(e){e.poolSize==null&&(e.poolSize=2);super(e);if(typeof e.poolSize=="number")this.poolSize=[e.poolSize];else if(Array.isArray(e.poolSize)&&e.poolSize.length===1&&typeof e.poolSize[0]=="number")this.poolSize=e.poolSize;else throw new q(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);if(xn(this.poolSize,"poolSize"),e.strides==null)this.strides=this.poolSize;else if(typeof e.strides=="number")this.strides=[e.strides];else if(Array.isArray(e.strides)&&e.strides.length===1&&typeof e.strides[0]=="number")this.strides=e.strides;else throw new q(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);xn(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,$s(this.padding),this.inputSpec=[new Yt({ndim:3})]}computeOutputShape(e){e=mt(e);let t=gr(e[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return j(()=>{this.invokeCallHook(e,t),e=kd(Ve(e),2);let n=this.poolingFunction(Ve(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return pt(n,[2])})}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}},BA=class extends fk{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return jt(r),$s(s),Jf(e,t,n,s,r,"max")}};BA.className="MaxPooling1D";le.registerClass(BA);var WA=class extends fk{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return jt(r),$s(s),Jf(e,t,n,s,r,"avg")}};WA.className="AveragePooling1D";le.registerClass(WA);var mk=class extends nt{constructor(e){e.poolSize==null&&(e.poolSize=[2,2]);super(e);if(this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],e.strides==null)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==2)throw new q(`If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides];xn(this.poolSize,"poolSize"),xn(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,jt(this.dataFormat),$s(this.padding),this.inputSpec=[new Yt({ndim:4})]}computeOutputShape(e){e=mt(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2];return t=gr(t,this.poolSize[0],this.padding,this.strides[0]),n=gr(n,this.poolSize[1],this.padding,this.strides[1]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,n]:[e[0],t,n,e[3]]}call(e,t){return j(()=>(this.invokeCallHook(e,t),this.poolingFunction(Ve(e),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},VA=class extends mk{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return jt(r),$s(s),Jf(e,t,n,s,r,"max")}};VA.className="MaxPooling2D";le.registerClass(VA);var UA=class extends mk{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return jt(r),$s(s),Jf(e,t,n,s,r,"avg")}};UA.className="AveragePooling2D";le.registerClass(UA);var gk=class extends nt{constructor(e){e.poolSize==null&&(e.poolSize=[2,2,2]);super(e);if(this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize,e.poolSize],e.strides==null)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==3)throw new q(`If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides,e.strides];xn(this.poolSize,"poolSize"),xn(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,jt(this.dataFormat),$s(this.padding),this.inputSpec=[new Yt({ndim:5})]}computeOutputShape(e){e=mt(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2],s=this.dataFormat==="channelsFirst"?e[4]:e[3];return t=gr(t,this.poolSize[0],this.padding,this.strides[0]),n=gr(n,this.poolSize[1],this.padding,this.strides[1]),s=gr(s,this.poolSize[2],this.padding,this.strides[2]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,n,s]:[e[0],t,n,s,e[4]]}call(e,t){return j(()=>(this.invokeCallHook(e,t),this.poolingFunction(Ve(e),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},GA=class extends gk{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return jt(r),$s(s),hk(e,t,n,s,r,"max")}};GA.className="MaxPooling3D";le.registerClass(GA);var HA=class extends gk{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return jt(r),$s(s),hk(e,t,n,s,r,"avg")}};HA.className="AveragePooling3D";le.registerClass(HA);var Ak=class extends nt{constructor(e){super(e);this.inputSpec=[new Yt({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new Be}},jA=class extends Ak{constructor(e){super(e||{})}call(e,t){return j(()=>{let n=Ve(e);return Wt(n,1)})}};jA.className="GlobalAveragePooling1D";le.registerClass(jA);var qA=class extends Ak{constructor(e){super(e||{})}call(e,t){return j(()=>{let n=Ve(e);return rs(n,1)})}};qA.className="GlobalMaxPooling1D";le.registerClass(qA);var yk=class extends nt{constructor(e){super(e);this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,jt(this.dataFormat),this.inputSpec=[new Yt({ndim:4})]}computeOutputShape(e){return e=e,this.dataFormat==="channelsLast"?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new Be}getConfig(){let e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},XA=class extends yk{call(e,t){return j(()=>{let n=Ve(e);return this.dataFormat==="channelsLast"?Wt(n,[1,2]):Wt(n,[2,3])})}};XA.className="GlobalAveragePooling2D";le.registerClass(XA);var KA=class extends yk{call(e,t){return j(()=>{let n=Ve(e);return this.dataFormat==="channelsLast"?rs(n,[1,2]):rs(n,[2,3])})}};KA.className="GlobalMaxPooling2D";le.registerClass(KA);var xk=class extends nt{constructor(e){super(e);this.layer=e.layer}build(e){this.built=!0}get trainable(){return this.layer!=null?this.layer.trainable:!1}set trainable(e){this.layer!=null&&(this.layer.trainable=e)}get trainableWeights(){return this.layer.trainableWeights}get nonTrainableWeights(){return this.layer.nonTrainableWeights}get updates(){return this.layer._updates}get losses(){return this.layer.losses}getWeights(){return this.layer.getWeights()}setWeights(e){this.layer.setWeights(e)}getConfig(){let e={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},t=super.getConfig();return Object.assign(e,t),e}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.layer!=null&&this.layer.setFastWeightInitDuringBuild(e)}static fromConfig(e,t,n={}){let s=t.layer,r=mr(s,n);delete t.layer;let a={layer:r};return Object.assign(a,t),new e(a)}},ZA=class extends xk{constructor(e){super(e);this.supportsMasking=!0}build(e){if(e=mt(e),e.length<3)throw new q(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(e)}`);this.inputSpec=[{shape:e}];let t=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(t),this.layer.built=!0),super.build(e)}computeOutputShape(e){e=mt(e);let t=[e[0]].concat(e.slice(2)),n=this.layer.computeOutputShape(t),s=e[1];return[n[0],s].concat(n.slice(1))}call(e,t){return j(()=>(e=Ve(e),ck((a,o)=>[Ve(this.layer.call(a,t)),[]],e,[],!1,null,null,!1,!0)[1]))}};ZA.className="TimeDistributed";le.registerClass(ZA);function UB(e){rl(Zz,"BidirectionalMergeMode",e)}var GB="concat",YA=class extends xk{constructor(e){super(e);let t=e.layer.getConfig(),n={};n.className=e.layer.getClassName(),n.config=t,this.forwardLayer=mr(n),t.goBackwards=t.goBackwards!==!0;let s={};if(s.className=e.layer.getClassName(),s.config=t,this.backwardLayer=mr(s),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=e.mergeMode===void 0?GB:e.mergeMode,UB(this.mergeMode),e.weights)throw new Be("weights support is not implemented for Bidirectional layer yet.");this._stateful=e.layer.stateful,this.returnSequences=e.layer.returnSequences,this.returnState=e.layer.returnState,this.supportsMasking=!0,this._trainable=!0,this.inputSpec=e.layer.inputSpec,this.numConstants=null}get trainable(){return this._trainable}set trainable(e){this._trainable=e,this.forwardLayer!=null&&(this.forwardLayer.trainable=e),this.backwardLayer!=null&&(this.backwardLayer.trainable=e)}getWeights(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())}setWeights(e){let t=e.length,n=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,n)),this.backwardLayer.setWeights(e.slice(n))}computeOutputShape(e){let t=this.forwardLayer.computeOutputShape(e);Array.isArray(t)&&Array.isArray(t[0])||(t=[t]),t=t;let n,s,r;return this.returnState&&(r=t.slice(1)),n=t[0],n=n,this.mergeMode==="concat"?(n[n.length-1]*=2,s=[n]):this.mergeMode==null?s=[n,n.slice()]:s=[n],this.returnState?this.mergeMode==null?s.concat(r).concat(r.slice()):[n].concat(r).concat(r.slice()):os(s)}apply(e,t){let n=t==null?null:t.initialState,s=t==null?null:t.constants;t==null&&(t={});let r=uk(e,n,s,this.numConstants);if(e=r.inputs,n=r.initialState,s=r.constants,Array.isArray(e)&&(n=e.slice(1),e=e[0]),(n==null||n.length===0)&&s==null)return super.apply(e,t);let a=[],o=[];if(n!=null){let l=n.length;if(l%2>0)throw new q("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");t.initialState=n,a.push(...n);let c=n.map(u=>new Yt({shape:u.shape}));this.forwardLayer.stateSpec=c.slice(0,l/2),this.backwardLayer.stateSpec=c.slice(l/2),o.push(...c)}if(s!=null)throw new Be("Support for constants in Bidirectional layers is not implemented yet.");let i=a[0]instanceof fr;for(let l of a)if(l instanceof fr!==i)throw new q("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(i){let l=[e].concat(a),c=this.inputSpec.concat(o),u=this.inputSpec;this.inputSpec=c;let d=super.apply(l,t);return this.inputSpec=u,d}else return super.apply(e,t)}call(e,t){return j(()=>{let n=t.initialState,s,r;if(n==null)s=this.forwardLayer.call(e,t),r=this.backwardLayer.call(e,t);else{let i=n.slice(0,n.length/2),l=n.slice(n.length/2);s=this.forwardLayer.call(e,Object.assign(t,{initialState:i})),r=this.backwardLayer.call(e,Object.assign(t,{initialState:l}))}let a;this.returnState&&(Array.isArray(s)&&(a=s.slice(1).concat(r.slice(1))),s=s[0],r=r[0]),this.returnSequences&&(r=Rs(r,1));let o;return this.mergeMode==="concat"?o=w1([s,r]):this.mergeMode==="sum"?o=ie(s,r):this.mergeMode==="ave"?o=W(.5,ie(s,r)):this.mergeMode==="mul"?o=W(s,r):this.mergeMode==null&&(o=[s,r]),this.returnState?this.mergeMode==null?o.concat(a):[o].concat(a):o})}resetStates(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(e){al(this.forwardLayer.name,()=>{this.forwardLayer.build(e)}),al(this.backwardLayer.name,()=>{this.backwardLayer.build(e)}),this.built=!0}computeMask(e,t){Array.isArray(t)&&(t=t[0]);let n;if(this.returnSequences?this.mergeMode==null?n=[t,t]:n=t:this.mergeMode==null?n=[null,null]:n=null,this.returnState){let r=this.forwardLayer.states.map(a=>null);return Array.isArray(n)?n.concat(r).concat(r):[n].concat(r).concat(r)}else return n}get trainableWeights(){return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights)}get nonTrainableWeights(){return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights)}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.forwardLayer!=null&&this.forwardLayer.setFastWeightInitDuringBuild(e),this.backwardLayer!=null&&this.backwardLayer.setFastWeightInitDuringBuild(e)}getConfig(){let e={mergeMode:this.mergeMode},t=super.getConfig();return Object.assign(e,t),e}static fromConfig(e,t){let n=mr(t.layer);if(delete t.layer,t.numConstants!=null)throw new Be("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");let s=t;return s.layer=n,new e(s)}};YA.className="Bidirectional";le.registerClass(YA);function HB(e){return new Fu(e)}function jB(e){return new nA(e)}function qB(e){return new Q1(e)}function XB(e){return new eA(e)}function KB(e){return new tA(e)}function ZB(e){return new rA(e)}function YB(e){return new sA(e)}function JB(e){return new cA(e)}function QB(e){return new Hf(e)}function eW(e){return new iA(e)}function tW(e){return new jf(e)}function nW(e){return new lA(e)}function sW(e){return new uA(e)}function rW(e){return new dA(e)}function aW(e){return new pA(e)}function oW(e){return new hA(e)}function iW(e){return new vA(e)}function lW(e){return new xA(e)}function uW(e){return new Yf(e)}function cW(e){return new yA(e)}function dW(e){return new bA(e)}function pW(e){return new wA(e)}function hW(e){return new kA(e)}function fW(e){return new IA(e)}function mW(e){return new CA(e)}function gW(e){return new TA(e)}function AW(e){return new EA(e)}function yW(e){return new DA(e)}function xW(e){return new RA(e)}function bW(e){return new $A(e)}function vW(e){return new NA(e)}function wW(e){return new _A(e)}function kW(e){return new MA(e)}function IW(e){return new zA(e)}function SW(e){return new LA(e)}function JA(e){return new WA(e)}function CW(e){return JA(e)}function TW(e){return JA(e)}function QA(e){return new UA(e)}function NW(e){return QA(e)}function EW(e){return QA(e)}function ey(e){return new HA(e)}function RW(e){return ey(e)}function $W(e){return ey(e)}function DW(e){return new jA(e)}function _W(e){return new XA(e)}function bk(e){return new qA(e)}function vk(e){return new KA(e)}function wk(e){return new BA(e)}function kk(e){return new VA(e)}function PW(e){return new GA(e)}function FW(e){return new mA(e)}function OW(e){return new Xf(e)}function MW(e){return new gA(e)}function zW(e){return new _d(e)}function LW(e){return new fA(e)}function BW(e){return new qf(e)}function WW(e){return new AA(e)}function VW(e){return new Zf(e)}function UW(e){return new sa(e)}function GW(e){return new Kf(e)}function HW(e){return new YA(e)}function jW(e){return new ZA(e)}var qW=bk,XW=vk,KW=wk,ZW=kk;function YW(e){return new PA(e)}function JW(e){return new FA(e)}function QW(e){return new OA(e)}function eV(e){return new SA(e)}var Ik={};ze(Ik,{MAPE:()=>dV,MSE:()=>fV,binaryAccuracy:()=>tV,binaryCrossentropy:()=>nV,categoricalAccuracy:()=>rV,categoricalCrossentropy:()=>aV,cosineProximity:()=>lV,mape:()=>pV,meanAbsoluteError:()=>uV,meanAbsolutePercentageError:()=>cV,meanSquaredError:()=>hV,mse:()=>mV,precision:()=>oV,recall:()=>iV,sparseCategoricalAccuracy:()=>sV});function tV(e,t){return z1(e,t)}function nV(e,t){return ww(e,t)}function sV(e,t){return kw(e,t)}function rV(e,t){return L1(e,t)}function aV(e,t){return B1(e,t)}function oV(e,t){return vw(e,t)}function iV(e,t){return HL(e,t)}function lV(e,t){return O1(e,t)}function uV(e,t){return Mf(e,t)}function cV(e,t){return Mu(e,t)}function dV(e,t){return Mu(e,t)}function pV(e,t){return Mu(e,t)}function hV(e,t){return il(e,t)}function fV(e,t){return il(e,t)}function mV(e,t){return il(e,t)}var Sk={};ze(Sk,{modelFromJSON:()=>SB});var Ck={};ze(Ck,{l1:()=>AV,l1l2:()=>gV,l2:()=>yV});function gV(e){return new Rd(e)}function AV(e){return _B(e)}function yV(e){return PB(e)}var Tk=class extends Ou{constructor(){super(...arguments);this.model=null}setModel(e){if(!(e instanceof na))throw new Error("model must be a LayersModel, not some other Container");this.model=e}};function Qf(e,t){return et}var Ek=class extends Tk{constructor(e){super();if(e==null&&(e={}),e.restoreBestWeights)throw new Be("restoreBestWeights = True is not implemented in EarlyStopping yet.");this.monitor=e.monitor||"val_loss",this.minDelta=Math.abs(e.minDelta||0),this.patience=e.patience||0,this.verbose=e.verbose||0,this.mode=e.mode||"auto",this.baseline=e.baseline,["auto","min","max"].indexOf(this.mode)===-1&&(console.warn(`EarlyStopping mode '${this.mode}' is invalid. Falling back to mode 'auto'.`),this.mode="auto"),this.mode==="min"?this.monitorFunc=Qf:this.mode==="max"?this.monitorFunc=Nk:this.monitor.indexOf("acc")!==-1?this.monitorFunc=Nk:this.monitorFunc=Qf,this.monitorFunc===Qf&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,this.baseline!=null?this.best=this.baseline:this.best=this.monitorFunc===Qf?1/0:-1/0}async onEpochEnd(e,t){await Eo(t);let n=this.getMonitorValue(t);n!=null&&(this.monitorFunc(n-this.minDelta,this.best)?(this.best=n,this.wait=0):(this.wait++,this.wait>=this.patience&&(this.stoppedEpoch=e,this.model.stopTraining=!0)))}async onTrainEnd(e){this.stoppedEpoch>0&&this.verbose&&console.log(`Epoch ${this.stoppedEpoch}: early stopping.`)}getMonitorValue(e){e==null&&(e={});let t=e[this.monitor];return t==null&&console.warn(`Metric for EarlyStopping ${this.monitor} is not available. Available metrics are: ${Object.keys(e)}`),t}};function xV(e){return new Ek(e)}var bV={earlyStopping:xV},Ar;(function(e){e[e.DT_INVALID=0]="DT_INVALID",e[e.DT_FLOAT=1]="DT_FLOAT",e[e.DT_DOUBLE=2]="DT_DOUBLE",e[e.DT_INT32=3]="DT_INT32",e[e.DT_UINT8=4]="DT_UINT8",e[e.DT_INT16=5]="DT_INT16",e[e.DT_INT8=6]="DT_INT8",e[e.DT_STRING=7]="DT_STRING",e[e.DT_COMPLEX64=8]="DT_COMPLEX64",e[e.DT_INT64=9]="DT_INT64",e[e.DT_BOOL=10]="DT_BOOL",e[e.DT_QINT8=11]="DT_QINT8",e[e.DT_QUINT8=12]="DT_QUINT8",e[e.DT_QINT32=13]="DT_QINT32",e[e.DT_BFLOAT16=14]="DT_BFLOAT16",e[e.DT_FLOAT_REF=101]="DT_FLOAT_REF",e[e.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",e[e.DT_INT32_REF=103]="DT_INT32_REF",e[e.DT_UINT8_REF=104]="DT_UINT8_REF",e[e.DT_INT16_REF=105]="DT_INT16_REF",e[e.DT_INT8_REF=106]="DT_INT8_REF",e[e.DT_STRING_REF=107]="DT_STRING_REF",e[e.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",e[e.DT_INT64_REF=109]="DT_INT64_REF",e[e.DT_BOOL_REF=110]="DT_BOOL_REF",e[e.DT_QINT8_REF=111]="DT_QINT8_REF",e[e.DT_QUINT8_REF=112]="DT_QUINT8_REF",e[e.DT_QINT32_REF=113]="DT_QINT32_REF",e[e.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF"})(Ar||(Ar={}));var Rk;(function(e){let t;(function(n){n[n.LEGACY=0]="LEGACY",n[n.V1=1]="V1",n[n.V2=2]="V2"})(t=e.CheckpointFormatVersion||(e.CheckpointFormatVersion={}))})(Rk||(Rk={}));var ty={};function vV(e,t){let n={tfOpName:e,category:"custom",inputs:[],attrs:[],customExecutor:t};ty[e]=n}function $k(e){return ty[e]}function wV(e){delete ty[e]}function I(e,t,n,s,r){let a=t.inputParams[e];if(a&&a.inputIndexStart!==void 0){let i=a.inputIndexStart,l=a.inputIndexEnd===0?void 0:a.inputIndexEnd===void 0?i+1:a.inputIndexEnd;if(a.type==="tensor")return Un(t.inputNames[a.inputIndexStart],n,s,r);if(a.type==="tensors")return t.inputNames.slice(i,l).map(p=>Un(p,n,s,r));let c=Un(t.inputNames.slice(i)[0],n,s,r),u=c.dataSync();return a.type==="number"?u[0]:v.toNestedArray(c.shape,u)}let o=t.attrParams[e];return o&&o.value}function Un(e,t,n,s){let[r,a]=As(e);if(s!=null){let i=s.getHashTableHandleByName(r);if(i!=null)return i}let o=n.currentContextIds.find(i=>!!t[em(r,i)]);return o!==void 0?t[em(r,o)][a]:void 0}function kV(e,t,n){return t[em(e,n.currentContextId)]}function ra(e,t){let[n,s,r]=As(e);return[em(n,t&&t.currentContextId),s,r]}function em(e,t){return t?`${e}-${t}`:e}function As(e){let t=e.split(":");if(t.length===1)return[e,0,void 0];let n=t[0],s=t.length===3?t[1]:void 0,r=Number(t[t.length-1]);return[n,r,s]}function tm(e,t,n){let s=I("pad",e,t,n);if(s==="explicit"){s=I("explicitPaddings",e,t,n);let r=[[0,0],[0,0],[0,0],[0,0]];for(let a=0;a<4;a++)r[a][0]=s[a*2],r[a][1]=s[a*2+1];return r}return s}function aa(e){return e.kept?e:or(e)}var Dk={};ze(Dk,{json:()=>IV});var IV=[{tfOpName:"Add",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddV2",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddN",category:"arithmetic",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"BiasAdd",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"Sub",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"RealDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Div",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"DivNoNan",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mul",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Maximum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Minimum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Pow",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SquaredDifference",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorMod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],_k={};ze(_k,{json:()=>SV});var SV=[{tfOpName:"Abs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan2",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ceil",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ClipByValue",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"clipValueMin",type:"number"},{start:2,name:"clipValueMax",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Complex",category:"basic_math",inputs:[{start:0,name:"real",type:"tensor"},{start:1,name:"imag",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ComplexAbs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Elu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Exp",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Floor",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Imag",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Neg",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Real",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Prelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"alpha",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu6",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Selu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sigmoid",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Rsqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Square",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sign",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Round",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Expm1",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log1p",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Reciprocal",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Softplus",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Erf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Prod",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axes",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LeakyRelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"alpha",name:"alpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsNan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],Pk={};ze(Pk,{json:()=>CV});var CV=[{tfOpName:"EmptyTensorList",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"maxNumElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"LoopCond",category:"control",inputs:[{start:0,name:"pred",type:"tensor"}]},{tfOpName:"Switch",category:"control",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"pred",type:"tensor"}]},{tfOpName:"Merge",category:"control",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"Enter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"frame_name",name:"frameName",type:"string"},{tfName:"is_constant",name:"isConstant",type:"bool"}]},{tfOpName:"Exit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NextIteration",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayV3",category:"control",inputs:[{start:0,name:"size",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"dynamic_size",name:"dynamicSize",type:"bool"},{tfName:"clear_after_read",name:"clearAfterRead",type:"bool"},{tfName:"identical_element_shapes",name:"identicalElementShapes",type:"bool"},{tfName:"tensor_array_name",name:"name",type:"string"}]},{tfOpName:"TensorArrayWriteV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayReadV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayGatherV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"}]},{tfOpName:"TensorArrayScatterV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArrayConcatV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape_except0",name:"elementShapeExcept0",type:"shape",notSupported:!0}]},{tfOpName:"TensorArraySplitV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"tensor",type:"tensor"},{start:2,name:"lengths",type:"number[]"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArraySizeV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}]},{tfOpName:"TensorArrayCloseV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"}]},{tfOpName:"StatelessIf",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"If",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"StatelessWhile",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"While",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"TensorListScatter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListScatterV2",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"},{start:3,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGather",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListSetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListReserve",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListFromTensor",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListStack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"},{tfName:"num_elements",name:"numElements",type:"dtype"}]},{tfOpName:"TensorListSplit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"},{start:2,name:"lengths",type:"number[]"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcat",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPopBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPushBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]}],Fk={};ze(Fk,{json:()=>TV});var TV=[{tfOpName:"AvgPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[],notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPoolWithArgmax",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"include_batch_in_index",name:"includeBatchInIndex",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AvgPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Conv1D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"stride",name:"stride",type:"number"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NWC"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"dilation",name:"dilation",type:"number",defaultValue:1}]},{tfOpName:"Conv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"useCudnnOnGpu",name:"useCudnnOnGpu",type:"bool"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"_FusedConv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"use_cudnn_on_gpu",name:"useCudnnOnGpu",type:"bool",defaultValue:!0},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number"}]},{tfOpName:"Conv2DBackpropInput",category:"convolution",inputs:[{start:2,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:0,name:"outputShape",type:"number[]"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]",notSupported:!0}]},{tfOpName:"DepthwiseConv2d",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"DepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"FusedDepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]}]},{tfOpName:"Conv3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"Dilation2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"rates",name:"dilations",type:"number[]"},{tfName:"padding",name:"pad",type:"string"}]}],Ok={};ze(Ok,{json:()=>NV});var NV=[{tfOpName:"Fill",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"},{start:1,name:"value",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"LinSpace",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"num",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"OneHot",category:"creation",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"depth",type:"number"},{start:2,name:"onValue",type:"number",defaultValue:1},{start:3,name:"offValue",type:"number",defaultValue:0}],attrs:[{tfName:"axis",name:"axis",type:"number",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ones",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"OnesLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"RandomUniform",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number",defaultValue:0},{tfName:"maxval",name:"maxval",type:"number",defaultValue:1},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Range",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"step",type:"number",defaultValue:0}],attrs:[{tfName:"Tidx",name:"dtype",type:"dtype"}]},{tfOpName:"TruncatedNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"means",name:"mean",type:"number",defaultValue:0},{tfName:"stddev",name:"stdDev",type:"number",defaultValue:1},{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Zeros",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"ZerosLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Multinomial",category:"creation",inputs:[{start:0,name:"logits",type:"tensor"},{start:1,name:"numSamples",type:"number"}],attrs:[{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number"},{tfName:"T",name:"dtype",type:"dtype"},{tfName:"output_dtype",name:"output_dtype",type:"dtype"}]}],Mk={};ze(Mk,{json:()=>EV});var EV=[{tfOpName:"NonMaxSuppressionV2",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV3",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV4",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"T_threshold",name:"threshold",type:"dtype",notSupported:!0},{tfName:"pad_to_max_output_size",name:"padToMaxOutputSize",type:"bool"}]},{tfOpName:"NonMaxSuppressionV5",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"},{start:5,name:"softNmsSigma",type:"number"}]},{tfOpName:"Where",category:"dynamic",inputs:[{start:0,name:"condition",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ListDiff",category:"dynamic",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],zk={};ze(zk,{json:()=>RV});var RV=[{tfOpName:"TopKV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"k",type:"number"}],attrs:[{tfName:"sorted",name:"sorted",type:"bool"}]},{tfOpName:"Unique",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"UniqueV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]}],Lk={};ze(Lk,{json:()=>$V});var $V=[{tfOpName:"PlaceholderWithDefault",category:"graph",inputs:[{start:0,name:"default",type:"tensor"}],attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Placeholder",category:"graph",attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Const",category:"graph"},{tfOpName:"Identity",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IdentityN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Snapshot",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Rank",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Size",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Shape",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"ShapeN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Print",category:"graph",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"data",type:"tensors"}],attrs:[{tfName:"message",name:"message",type:"string"},{tfName:"first_n",name:"firstN",type:"number",notSupported:!0},{tfName:"summarize",name:"summarize",type:"number",defaultValue:3}]},{tfOpName:"NoOp",category:"graph",inputs:[]},{tfOpName:"StopGradient",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"FakeQuantWithMinMaxVars",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"min",name:"min",type:"number"},{tfName:"max",name:"max",type:"number"}]}],Bk={};ze(Bk,{json:()=>DV});var DV=[{tfOpName:"HashTable",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"HashTableV2",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"LookupTableImport",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableImportV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFind",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFindV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableSize",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]},{tfOpName:"LookupTableSizeV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]}],Wk={};ze(Wk,{json:()=>_V});var _V=[{tfOpName:"ResizeBilinear",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ResizeNearestNeighbor",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"CropAndResize",category:"image",inputs:[{start:0,name:"image",type:"tensor"},{start:1,name:"boxes",type:"tensor"},{start:2,name:"boxInd",type:"tensor"},{start:3,name:"cropSize",type:"number[]"}],attrs:[{tfName:"method",name:"method",type:"string"},{tfName:"extrapolation_value",name:"extrapolationValue",type:"number"}]}],Vk={};ze(Vk,{json:()=>PV});var PV=[{tfOpName:"Equal",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NotEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Greater",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"GreaterEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Less",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LessEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalAnd",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalNot",category:"logical",inputs:[{start:0,name:"a",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalOr",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Select",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SelectV2",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],Uk={};ze(Uk,{json:()=>FV});var FV=[{tfOpName:"_FusedMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMulV2",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Transpose",category:"matrices",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"perm",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Einsum",category:"matrices",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"equation",name:"equation",type:"string"},{tfName:"N",name:"n",type:"number",defaultValue:2},{tfName:"T",name:"dtype",type:"dtype"}]}],Gk={};ze(Gk,{json:()=>OV});var OV=[{tfOpName:"FusedBatchNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV2",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV3",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"LRN",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"depth_radius",name:"radius",type:"number",defaultValue:5},{tfName:"bias",name:"bias",type:"number",defaultValue:1},{tfName:"alpha",name:"alpha",type:"number",defaultValue:1},{tfName:"beta",name:"beta",type:"number",defaultValue:.5}]},{tfOpName:"Softmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"LogSoftmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"SparseToDense",category:"normalization",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!0,notSupported:!0}]}],Hk={};ze(Hk,{json:()=>MV});var MV=[{tfOpName:"Bincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}]},{tfOpName:"DenseBincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}],attrs:[{tfName:"binary_output",name:"binaryOutput",type:"bool"}]},{tfOpName:"Max",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Mean",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Min",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Sum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"All",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Any",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"ArgMax",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"ArgMin",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Prod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Cumsum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]}],jk={};ze(jk,{json:()=>zV});var zV=[{tfOpName:"ConcatV2",category:"slice_join",inputs:[{start:0,end:-1,name:"tensors",type:"tensors"},{start:-1,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"Concat",category:"slice_join",inputs:[{start:1,end:0,name:"tensors",type:"tensors"},{start:0,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"GatherV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"axis",type:"number",defaultValue:0}],attrs:[{tfName:"batch_dims",name:"batchDims",type:"number",defaultValue:0}]},{tfOpName:"Gather",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",notSupported:!0}]},{tfOpName:"Reverse",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"dims",type:"bool[]"}]},{tfOpName:"ReverseV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}]},{tfOpName:"Slice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"size",type:"number[]"}]},{tfOpName:"StridedSlice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"end",type:"number[]"},{start:3,name:"strides",type:"number[]"}],attrs:[{tfName:"begin_mask",name:"beginMask",type:"number",defaultValue:0},{tfName:"end_mask",name:"endMask",type:"number",defaultValue:0},{tfName:"new_axis_mask",name:"newAxisMask",type:"number",defaultValue:0},{tfName:"ellipsis_mask",name:"ellipsisMask",type:"number",defaultValue:0},{tfName:"shrink_axis_mask",name:"shrinkAxisMask",type:"number",defaultValue:0}]},{tfOpName:"Pack",category:"slice_join",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Unpack",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"num",name:"num",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Tile",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"reps",type:"number[]"}]},{tfOpName:"Split",category:"slice_join",inputs:[{start:0,name:"axis",type:"number",defaultValue:0},{start:1,name:"x",type:"tensor"}],attrs:[{tfName:"num_split",name:"numOrSizeSplits",type:"number",defaultValue:1}]},{tfOpName:"SplitV",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"numOrSizeSplits",type:"number[]"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"ScatterNd",category:"slice_join",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"shape",type:"number[]"}]},{tfOpName:"GatherNd",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}]},{tfOpName:"SparseToDense",category:"slice_join",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!1,notSupported:!0}]}],qk={};ze(qk,{json:()=>LV});var LV=[{tfOpName:"SparseFillEmptyRows",category:"sparse",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"denseShape",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}]},{tfOpName:"SparseReshape",category:"sparse",inputs:[{start:0,name:"inputIndices",type:"tensor"},{start:1,name:"inputShape",type:"tensor"},{start:2,name:"newShape",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SparseSegmentMean",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]},{tfOpName:"SparseSegmentSum",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]}],Xk={};ze(Xk,{json:()=>BV});var BV=[{tfOpName:"FFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"RFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]},{tfOpName:"IRFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]}],Kk={};ze(Kk,{json:()=>WV});var WV=[{tfOpName:"StringNGrams",category:"string",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"dataSplits",type:"tensor"}],attrs:[{tfName:"separator",name:"separator",type:"string"},{tfName:"ngram_widths",name:"nGramWidths",type:"number[]"},{tfName:"left_pad",name:"leftPad",type:"string"},{tfName:"right_pad",name:"rightPad",type:"string"},{tfName:"pad_width",name:"padWidth",type:"number"},{tfName:"preserve_short_sequences",name:"preserveShortSequences",type:"bool"}],outputs:["ngrams","ngrams_splits"]},{tfOpName:"StringSplit",category:"string",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"delimiter",type:"tensor"}],attrs:[{tfName:"skip_empty",name:"skipEmpty",type:"bool"}],outputs:["indices","values","shape"]},{tfOpName:"StringToHashBucketFast",category:"string",inputs:[{start:0,name:"input",type:"tensor"}],attrs:[{tfName:"num_buckets",name:"numBuckets",type:"number"}]}],Zk={};ze(Zk,{json:()=>VV});var VV=[{tfOpName:"Cast",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"SrcT",name:"sdtype",type:"dtype",notSupported:!0},{tfName:"DstT",name:"dtype",type:"dtype"}]},{tfOpName:"ExpandDims",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"MirrorPad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"mode",name:"mode",type:"string"}]},{tfOpName:"Pad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"constant_value",name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"PadV2",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"},{start:2,name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"Reshape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"Squeeze",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"axis",tfDeprecatedName:"squeeze_dims",name:"axis",type:"number[]"}]},{tfOpName:"SpaceToBatchND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"paddings",type:"number[]"}]},{tfOpName:"BatchToSpaceND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"crops",type:"number[]"}]},{tfOpName:"DepthToSpace",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"block_size",name:"blockSize",type:"number"},{tfName:"data_format",name:"dataFormat",type:"string"}]},{tfOpName:"BroadcastTo",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}],attrs:[]},{tfOpName:"BroadcastArgs",category:"transformation",inputs:[{start:0,name:"s0",type:"tensor"},{start:1,name:"s1",type:"tensor"}],attrs:[]}],Yk=class{static get Instance(){return this._instance||(this._instance=new this)}constructor(){let e=[Dk,_k,Pk,Fk,Ok,Mk,zk,Lk,Bk,Wk,Vk,Uk,Gk,Hk,jk,qk,Xk,Kk,Zk],t=[].concat(...e.map(n=>n.json));this.opMappers=t.reduce((n,s)=>(n[s.tfOpName]=s,n),{})}transformGraph(e,t={}){let n=e.node,s=[],r=[],a=[],o=n.reduce((f,m)=>(f[m.name]=this.mapNode(m),m.op.startsWith("Placeholder")?s.push(f[m.name]):m.op==="Const"?r.push(f[m.name]):(m.input==null||m.input.length===0)&&a.push(f[m.name]),f),{}),i=[],l=[],c={},u={};t!=null&&(c=this.mapSignatureEntries(t.inputs),u=this.mapSignatureEntries(t.outputs));let d=Object.keys(o);d.forEach(f=>{let m=o[f];m.inputNames.forEach((g,A)=>{let[y,,x]=ra(g),b=o[y];if(b.outputs!=null){let w=b.outputs.indexOf(x);if(w!==-1){let k=`${y}:${w}`;m.inputNames[A]=k}}m.inputs.push(b),b.children.push(m)})}),Object.keys(u).length===0?d.forEach(f=>{let m=o[f];m.children.length===0&&l.push(m)}):Object.keys(u).forEach(f=>{let[m]=ra(f),g=o[m];g!=null&&(g.signatureKey=u[f],l.push(g))}),Object.keys(c).length>0?Object.keys(c).forEach(f=>{let[m]=ra(f),g=o[m];g&&(g.signatureKey=c[f],i.push(g))}):i=s;let p={};e.library!=null&&e.library.function!=null&&(p=e.library.function.reduce((f,m)=>(f[m.signature.name]=this.mapFunction(m),f),{}));let h={nodes:o,inputs:i,outputs:l,weights:r,placeholders:s,signature:t,functions:p};return a.length>0&&(h.initNodes=a),h}mapSignatureEntries(e){return Object.keys(e||{}).reduce((t,n)=>(t[e[n].name]=n,t),{})}mapNode(e){let t=$k(e.op)||this.opMappers[e.op]||{};e.attr==null&&(e.attr={});let n={name:e.name,op:e.op,category:t.category,inputNames:(e.input||[]).map(s=>s.startsWith("^")?s.substr(1):s),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:e.attr,outputs:t.outputs};return t.inputs!=null&&(n.inputParams=t.inputs.reduce((s,r)=>(s[r.name]={type:r.type,inputIndexStart:r.start,inputIndexEnd:r.end},s),{})),t.attrs!=null&&(n.attrParams=t.attrs.reduce((s,r)=>{let a=r.type,o;switch(r.type){case"string":o=ny(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=ny(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"string[]":o=cy(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=cy(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"number":o=ry(e.attr,r.tfName,r.defaultValue||0),o===void 0&&!!r.tfDeprecatedName&&(o=ry(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"number[]":o=uy(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=uy(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"bool":o=sy(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=sy(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"bool[]":o=py(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=py(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"shape":o=ly(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=ly(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"shape[]":o=dy(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=dy(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"dtype":o=oy(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=oy(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"dtype[]":o=iy(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=iy(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"func":o=Qk(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=Qk(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error(`Unsupported param type: ${r.type} for op: ${e.op}`)}return s[r.name]={value:o,type:a},s},{})),n}mapFunction(e){let t=e.nodeDef,n=[],s=[],r={};t!=null&&(r=t.reduce((u,d)=>(u[d.name]=this.mapNode(d),d.op==="Const"&&s.push(u[d.name]),u),{}));let a=[],o=[];e.signature.inputArg.forEach(u=>{let[d]=ra(u.name),p={name:d,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:ay(u.type),type:"dtype"}},children:[]};p.signatureKey=u.name,a.push(p),r[d]=p}),Object.keys(r).forEach(u=>{let d=r[u];d.inputNames.forEach((p,h)=>{let[f,,m]=ra(p),g=r[f];if(g.outputs!=null){let A=g.outputs.indexOf(m);if(A!==-1){let y=`${f}:${A}`;d.inputNames[h]=y}}d.inputs.push(g),g.children.push(d)})});let l=e.ret;e.signature.outputArg.forEach(u=>{let[d,p]=ra(l[u.name]),h=r[d];h!=null&&(h.defaultOutput=p,o.push(h))});let c=this.mapArgsToSignature(e);return{nodes:r,inputs:a,outputs:o,weights:s,placeholders:n,signature:c}}mapArgsToSignature(e){return{methodName:e.signature.name,inputs:e.signature.inputArg.reduce((t,n)=>(t[n.name]=this.mapArgToTensorInfo(n),t),{}),outputs:e.signature.outputArg.reduce((t,n)=>(t[n.name]=this.mapArgToTensorInfo(n,e.ret),t),{})}}mapArgToTensorInfo(e,t){let n=e.name;return t!=null&&(n=t[n]),{name:n,dtype:e.type}}};function UV(e){let t=K().global;if(typeof t.atob!="undefined")return t.atob(e);if(typeof Buffer!="undefined")return new Buffer(e,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}function Jk(e,t){let n=Array.isArray(e)?String.fromCharCode.apply(null,e):UV(e);return t?n:n.toLowerCase()}function ny(e,t,n,s=!1){let r=e[t];return r!=null?Jk(r.s,s):n}function sy(e,t,n){let s=e[t];return s?s.b:n}function ry(e,t,n){let s=e[t]||{},r=s.i!=null?s.i:s.f!=null?s.f:n;return typeof r=="number"?r:parseInt(r,10)}function ay(e){switch(typeof e=="string"&&(e=Ar[e]),e){case Ar.DT_FLOAT:return"float32";case Ar.DT_INT32:case Ar.DT_INT64:case Ar.DT_INT8:case Ar.DT_UINT8:return"int32";case Ar.DT_BOOL:return"bool";case Ar.DT_DOUBLE:return"float32";case Ar.DT_STRING:return"string";default:return null}}function Qk(e,t,n){let s=e[t];return s&&s.func?s.func.name:n}function oy(e,t,n){let s=e[t];return s&&s.type?ay(s.type):n}function iy(e,t,n){let s=e[t];return s&&s.list&&s.list.type?s.list.type.map(r=>ay(r)):n}function e7(e){if(!e.unknownRank)return e.dim!=null?e.dim.map(t=>typeof t.size=="number"?t.size:parseInt(t.size,10)):[]}function ly(e,t,n){let s=e[t];return s&&s.shape?e7(s.shape):n}function uy(e,t,n){let s=e[t];return s?((s.list.f&&s.list.f.length?s.list.f:s.list.i)||[]).map(r=>typeof r=="number"?r:parseInt(r,10)):n}function cy(e,t,n,s=!1){let r=e[t];return r&&r.list&&r.list.s?r.list.s.map(a=>Jk(a,s)):n}function dy(e,t,n){let s=e[t];return s&&s.list&&s.list.shape?s.list.shape.map(r=>e7(r)):n}function py(e,t,n){let s=e[t];return s&&s.list&&s.list.b?s.list.b:n}var GV=class{constructor(e,t,n){this.node=e,this.tensorMap=t,this.context=n,this.inputs=[],this.attrs={},this.inputs=e.inputNames.map(s=>this.getInput(s)),e.rawAttrs!=null&&(this.attrs=Object.keys(e.rawAttrs).reduce((s,r)=>(s[r]=this.getAttr(r),s),{}))}getInput(e){return Un(e,this.tensorMap,this.context)}getAttr(e,t){let n=this.node.rawAttrs[e];if(n.tensor!=null)return Un(e,this.tensorMap,this.context);if(n.i!=null||n.f!=null)return ry(this.node.rawAttrs,e,t);if(n.s!=null)return ny(this.node.rawAttrs,e,t);if(n.b!=null)return sy(this.node.rawAttrs,e,t);if(n.shape!=null)return ly(this.node.rawAttrs,e,t);if(n.type!=null)return oy(this.node.rawAttrs,e,t);if(n.list!=null){if(n.list.i!=null||n.list.f!=null)return uy(this.node.rawAttrs,e,t);if(n.list.s!=null)return cy(this.node.rawAttrs,e,t);if(n.list.shape!=null)return dy(this.node.rawAttrs,e,t);if(n.list.b!=null)return py(this.node.rawAttrs,e,t);if(n.list.type!=null)return iy(this.node.rawAttrs,e,t)}return t}},HV=(e,t,n)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[ie(I("a",e,t,n),I("b",e,t,n))];case"AddN":return[Vh(I("tensors",e,t,n))];case"FloorMod":case"Mod":return[tv(I("a",e,t,n),I("b",e,t,n))];case"Mul":return[W(I("a",e,t,n),I("b",e,t,n))];case"RealDiv":case"Div":return[he(I("a",e,t,n),I("b",e,t,n))];case"DivNoNan":return[W3(I("a",e,t,n),I("b",e,t,n))];case"FloorDiv":return[C2(I("a",e,t,n),I("b",e,t,n))];case"Sub":return[ye(I("a",e,t,n),I("b",e,t,n))];case"Minimum":return[hd(I("a",e,t,n),I("b",e,t,n))];case"Maximum":return[Yr(I("a",e,t,n),I("b",e,t,n))];case"Pow":return[Io(I("a",e,t,n),I("b",e,t,n))];case"SquaredDifference":return[n1(I("a",e,t,n),I("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},jV=(e,t,n)=>{switch(e.op){case"Abs":case"ComplexAbs":return[rn(I("x",e,t,n))];case"Acos":return[A3(I("x",e,t,n))];case"Acosh":return[y3(I("x",e,t,n))];case"Asin":return[b3(I("x",e,t,n))];case"Asinh":return[v3(I("x",e,t,n))];case"Atan":return[w3(I("x",e,t,n))];case"Atan2":return[k3(I("x",e,t,n),I("y",e,t,n))];case"Atanh":return[I3(I("x",e,t,n))];case"Ceil":return[D3(I("x",e,t,n))];case"Complex":return[yo(I("real",e,t,n),I("imag",e,t,n))];case"Cos":return[qh(I("x",e,t,n))];case"Cosh":return[O2(I("x",e,t,n))];case"Elu":return[dd(I("x",e,t,n))];case"Erf":return[U3(I("x",e,t,n))];case"Exp":return[Ts(I("x",e,t,n))];case"Expm1":return[G3(I("x",e,t,n))];case"Floor":return[pd(I("x",e,t,n))];case"Log":return[Ns(I("x",e,t,n))];case"Log1p":return[Zh(I("x",e,t,n))];case"Imag":return[Xh(I("x",e,t,n))];case"Neg":return[Ot(I("x",e,t,n))];case"Reciprocal":return[rv(I("x",e,t,n))];case"Real":return[fd(I("x",e,t,n))];case"Relu":return[Rr(I("x",e,t,n))];case"Round":return[K2(I("x",e,t,n))];case"Selu":return[Y2(I("x",e,t,n))];case"Sigmoid":return[hs(I("x",e,t,n))];case"Sin":return[J2(I("x",e,t,n))];case"Sign":return[iv(I("x",e,t,n))];case"Sinh":return[Q2(I("x",e,t,n))];case"Softplus":return[Cu(I("x",e,t,n))];case"Sqrt":return[_n(I("x",e,t,n))];case"Square":return[xt(I("x",e,t,n))];case"Tanh":return[vu(I("x",e,t,n))];case"Tan":return[uv(I("x",e,t,n))];case"ClipByValue":return[fs(I("x",e,t,n),I("clipValueMin",e,t,n),I("clipValueMax",e,t,n))];case"Relu6":return[X2(I("x",e,t,n))];case"Rsqrt":return[Z2(Un(e.inputNames[0],t,n))];case"Prod":return[H2(I("x",e,t,n),I("axes",e,t,n))];case"LeakyRelu":return[Kh(I("x",e,t,n),I("alpha",e,t,n))];case"Prelu":return[sf(I("x",e,t,n),I("alpha",e,t,n))];case"IsNan":return[H3(Un(e.inputNames[0],t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function Ys(e,t,n=""){if(!(typeof e=="number"||typeof t=="number")){v.assert(e.length===t.length,()=>n+` Shapes ${e} and ${t} must match`);for(let s=0;sn+` Shapes ${e} and ${t} must match`)}}}function t7(e){return!(typeof e=="number"||e.some(t=>t<0))}function Od(e,t,n){let s=hy(e,n),r=!t7(s);if(r&&t.length===0)throw new Error(`Tried to calculate elements of an empty list with non-fully-defined elementShape: ${s}`);if(r&&t.forEach(a=>{s=hy(a.shape,s)}),!t7(s))throw new Error(`Non-fully-defined elementShape: ${s}`);return s}function hy(e,t){if(typeof e=="number")return t;if(typeof t=="number")return e;if(e.length!==t.length)throw new Error(`Incompatible ranks during merge: ${e} vs. ${t}`);let n=[];for(let s=0;s=0&&a>=0&&r!==a)throw new Error(`Incompatible shape during merge: ${e} vs. ${t}`);n[s]=r>=0?r:a}return n}var qV=class{constructor(e,t,n,s,r,a,o){this.name=e,this.dtype=t,this.maxSize=n,this.elementShape=s,this.identicalElementShapes=r,this.dynamicSize=a,this.clearAfterRead=o,this.tensors=[],this.closed_=!1,this.idTensor=Ee(0),yn(this.idTensor)}get id(){return this.idTensor.id}get closed(){return this.closed_}clearAndClose(e){this.tensors.forEach(t=>{(e==null||!e.has(t.tensor.id))&&t.tensor.dispose()}),this.tensors=[],this.closed_=!0,this.idTensor.dispose()}size(){return this.tensors.length}read(e){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||e>=this.size())throw new Error(`Tried to read from index ${e}, but array size is: ${this.size()}`);let t=this.tensors[e];if(t.cleared)throw new Error(`TensorArray ${this.name}: Could not read index ${e} twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).`);return this.clearAfterRead&&(t.cleared=!0),t.read=!0,t.tensor}readMany(e){return e.map(t=>this.read(t))}write(e,t){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||!this.dynamicSize&&e>=this.maxSize)throw new Error(`Tried to write to index ${e}, but array is not resizeable and size is: ${this.maxSize}`);let n=this.tensors[e]||{};if(t.dtype!==this.dtype)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, +2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(l!=null){let c={};for(let h of Object.keys(Ks))c[h]=Ks[h];for(let h of Object.keys(n))c[h]=n[h];let u=a.config;u.customObjects=c;let d={...Ks};for(let h of Object.keys(n))Ks[h]=n[h];f1(a.config);let p=l(i,a.config,n,r);return Ks={...d},p}else{let c={...Ks};for(let d of Object.keys(n))Ks[d]=n[d];let u=new i(a.config);return Ks={...c},u}}}function Lz(e,t){return et?1:0}function bf(e,t){return-1*Lz(e,t)}function Co(e){if(e==null)return e;let t=[];for(let n of e)t.indexOf(n)===-1&&t.push(n);return t}function Bz(e){if(e==null)throw new q(`Invalid value in obj: ${JSON.stringify(e)}`);for(let t in e)if(e.hasOwnProperty(t))return!1;return!0}function rl(e,t,n){if(n!=null&&e.indexOf(n)<0)throw new q(`${n} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function m1(e,t,n=0,s=1/0){return $r(n>=0),$r(s>=n),Array.isArray(e)&&e.length>=n&&e.length<=s&&e.every(r=>typeof r===t)}function xn(e,t){Array.isArray(e)?(v.assert(e.length>0,()=>`${t} is unexpectedly an empty array.`),e.forEach((n,s)=>xn(n,`element ${s+1} of ${t}`))):v.assert(Number.isInteger(e)&&e>0,()=>`Expected ${t} to be a positive integer, but got ${jv(e)}.`)}function jv(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>jv(t)).join(",")+"]":typeof e=="string"?`"${e}"`:`${e}`}function Wz(e,t,n){let s=n!=null?n():v.now(),r;return(...o)=>{let i=n!=null?n():v.now();return i-s_n(Ie(W(e,e),t,!0)))}var vd=class extends le.Serializable{getConfig(){return{}}},A1=class extends vd{constructor(e){super();this.defaultMaxValue=2,this.defaultAxis=0,this.maxValue=e.maxValue!=null?e.maxValue:this.defaultMaxValue,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return j(()=>{let t=g1(e,this.axis),n=fs(t,0,this.maxValue);return W(e,fe(n,ie(on(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}};A1.className="MaxNorm";le.registerClass(A1);var y1=class extends vd{constructor(e){super();this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return j(()=>fe(e,ie(on(),g1(e,this.axis))))}getConfig(){return{axis:this.axis}}};y1.className="UnitNorm";le.registerClass(y1);var x1=class extends vd{apply(e){return Rr(e)}};x1.className="NonNeg";le.registerClass(x1);var b1=class extends vd{constructor(e){super();this.defaultMinValue=0,this.defaultMaxValue=1,this.defaultRate=1,this.defaultAxis=0,this.minValue=e.minValue!=null?e.minValue:this.defaultMinValue,this.maxValue=e.maxValue!=null?e.maxValue:this.defaultMaxValue,this.rate=e.rate!=null?e.rate:this.defaultRate,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return j(()=>{let t=g1(e,this.axis),n=ie(W(this.rate,fs(t,this.minValue,this.maxValue)),W(1-this.rate,t));return W(e,fe(n,ie(on(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}};b1.className="MinMaxNorm";le.registerClass(b1);var Xv={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function ln(e){return h1(e)}function Kv(e,t={}){return bd(e,le.SerializationMap.getMap().classNameMap,t,"constraint")}function un(e){if(e==null)return null;if(typeof e=="string"){let n={className:e in Xv?Xv[e]:e,config:{}};return Kv(n)}else return e instanceof vd?e:Kv(e)}function Vz(e){return new A1(e)}function Uz(e){return new y1(e)}function Gz(){return new x1}function Hz(e){return new b1(e)}var Zv={};ze(Zv,{constant:()=>fL,glorotNormal:()=>vL,glorotUniform:()=>bL,heNormal:()=>wL,heUniform:()=>kL,identity:()=>yL,leCunNormal:()=>IL,leCunUniform:()=>SL,ones:()=>hL,orthogonal:()=>CL,randomNormal:()=>gL,randomUniform:()=>mL,truncatedNormal:()=>AL,varianceScaling:()=>xL,zeros:()=>pL});var jz=["channelsFirst","channelsLast"],qz=["nearest","bilinear"],Xz=["valid","same","causal"],Kz=["max","avg"],Zz=["sum","mul","concat","ave"],_u=new Map;function jt(e){rl(jz,"DataFormat",e)}function Yz(e){rl(qz,"InterpolationFormat",e)}function $s(e){rl(Xz,"PaddingMode",e)}function Yv(e){rl(Kz,"PoolMode",e)}var wd=[],Jv="/";function al(e,t){wd.push(e);try{let n=t();return wd.pop(),n}catch(n){throw wd.pop(),n}}function Jz(){return wd.length===0?"":wd.join(Jv)+Jv}function Qv(e){if(!tw(e))throw new Error("Not a valid tensor name: '"+e+"'");return Jz()+e}function ew(e){if(!tw(e))throw new Error("Not a valid tensor name: '"+e+"'");_u.has(e)||_u.set(e,0);let t=_u.get(e);if(_u.set(e,_u.get(e)+1),t>0){let n=`${e}_${t}`;return _u.set(n,1),n}else return e}var Qz=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function tw(e){return!!e.match(Qz)}function eL(e){return e===parseInt(e.toString(),10)}function To(e,t,n){t==null&&(t=0),n==null&&(n=e.length);let s=1;for(let r=t;rt&&(t=s)}return t}function pr(e,t){if(t{if(e.shape.length!==2)throw new q(`repeat() expects a rank-2 tensor, but received a rank-${e.shape.length} tensor.`);let n=kd(e,1);return k1(n,[1,t,1])})}function nL(e){let t=[To(e.shape)];return G(e,t)}function sL(e){if(e.rank<=1)throw new q(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);let t=[e.shape[0],To(e.shape,1)];return G(e,t)}function ol(e,t,n){return j(()=>{switch(e.rank){case 1:return rf(e,t,n);case 2:return e1(e,[t,0],[n,e.shape[1]]);case 3:return Ru(e,[t,0,0],[n,e.shape[1],e.shape[2]]);case 4:return md(e,[t,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3]]);case 5:return _e(e,[t,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return _e(e,[t,0,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4],e.shape[5]]);default:throw new q(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}})}function v1(e,t,n){return j(()=>{switch(e.rank){case 1:return rf(e,t,n);case 2:return e1(e,[0,t],[e.shape[0],n]);case 3:return Ru(e,[0,0,t],[e.shape[0],e.shape[1],n]);case 4:return md(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],n]);default:throw new q(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function wf(e,t,n,s){return j(()=>{switch(e.rank){case 1:return rf(e,t,n);case 2:switch(s){case 1:return ol(e,t,n);case 2:return v1(e,t,n);default:throw new q(`The axis is not within the rank of the tensor ${s}`)}case 3:switch(s){case 1:return ol(e,t,n);case 2:return Ru(e,[0,t,0],[e.shape[0],n,e.shape[2]]);case 3:return v1(e,t,n);default:throw new q(`The axis is not within the rank of the tensor ${s}`)}case 4:switch(s){case 1:return ol(e,t,n);case 2:return md(e,[0,t,0,0],[e.shape[0],n,e.shape[2],e.shape[3]]);case 3:return md(e,[0,0,t,0],[e.shape[0],e.shape[1],n,e.shape[3]]);case 4:return v1(e,t,n);default:throw new q(`The axis is not within the rank of the tensor ${s}`)}default:throw new q(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function w1(e,t=-1){let n;return t<0&&(n=e[0].rank,n!==0?t=n:t=0),t===e[0].rank&&(t=-1),It(e,t)}function nw(e,t){switch(e.rank){case 1:return _3([e,t]);case 2:return ku([e,t],0);case 3:return P3([e,t],0);case 4:return F3([e,t],0);default:throw new q(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function k1(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new q(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return js(e,t)}function kf(e,t=0,n=1,s,r){return sv(e,t,n,s,r)}function Dr(e,t,n,s){if(e.rank<2||t.rank<2)throw new Be(`dot requires both inputs to be rank >= 2 but got x shape = ${e.shape} and y shape = ${t.shape}`);if(t.rank>=3){let r=e.shape.slice(-1)[0],a=t.shape.slice(-2)[0];if(r!==a)throw new Be(`If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = ${e.shape} and y shape = ${t.shape}`)}if(e.rank===2&&t.rank===2){let r=!1,a=!1;return So.matMul({a:e,b:t,transposeA:r,transposeB:a,bias:s?I1(e.rank,s,cr()):null,activation:n})}else{let r=e.shape.slice(),a=r.pop();e=G(e,[-1,a]);let o=t.shape.slice(),i=o.pop(),l=o.pop(),c=[...o,i],u=Array.from({length:t.rank},(f,m)=>m===0?t.rank-2:m<=t.rank-2?m-1:m);t=G(et(t,u),[l,-1]);let d=[...r,...c],p=!1,h=!1;return G(So.matMul({a:e,b:t,transposeA:p,transposeB:h,bias:s?I1(e.rank,s,cr()):null,activation:n}),d)}}function sw(e,t,n){return j(()=>(Array.isArray(t)?t=Zt(t,"int32"):t=he(t,"int32"),Su(e,t,n)))}function Id(e){return W(e,e)}function I1(e,t,n){let s=t.shape;if(t.rank!==1&&t.rank!==e)throw new q(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${e}`);if(e===5){if(n==="channelsFirst")return s.length===1?G(t,[1,s[0],1,1,1]):G(t,[1,s[3],s[0],s[1],s[2]]);if(n==="channelsLast")return s.length===1?G(t,[1,1,1,1,s[0]]):G(t,[1].concat(s))}else if(e===4){if(n==="channelsFirst")return s.length===1?G(t,[1,s[0],1,1]):G(t,[1,s[2],s[0],s[1]]);if(n==="channelsLast")return s.length===1?G(t,[1,1,1,s[0]]):G(t,[1].concat(s))}else if(e===3){if(n==="channelsFirst")return s.length===1?G(t,[1,s[0],1]):G(t,[1,s[1],s[0]]);if(n==="channelsLast")return s.length===1?G(t,[1,1,s[0]]):G(t,[1].concat(s))}else if(e<3)return t;throw new q(`Unsupported input rank by biasAdd: ${t.rank}`)}function hr(e,t,n){return j(()=>(n==null&&(n=cr()),jt(n),ie(e,I1(e.rank,t,n))))}function rL(e,t=1){if(t!==1)throw new Be(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return dd(e)}function aL(e){return j(()=>fe(e,ie(rn(e),1)))}function rw(e,t,n,s){return j(()=>Av(e,t,n,s))}function oL(e){return j(()=>{let t=ie(.5,W(.2,e));return fs(t,0,1)})}function Sd(e,t,n=!1){return n?e():t()}var iL=["fanIn","fanOut","fanAvg"],lL=["normal","uniform","truncatedNormal"];function uL(e){rl(iL,"FanMode",e)}function cL(e){rl(lL,"Distribution",e)}var Zs=class extends le.Serializable{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}},S1=class extends Zs{apply(e,t){return Ht(e,t)}};S1.className="Zeros";le.registerClass(S1);var If=class extends Zs{apply(e,t){return gs(e,t)}};If.className="Ones";le.registerClass(If);var C1=class extends Zs{constructor(e){super();if(typeof e!="object")throw new q(`Expected argument of type ConstantConfig but got ${e}`);if(e.value===void 0)throw new q(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return j(()=>W(Ee(this.value),gs(e,t)))}getConfig(){return{value:this.value}}};C1.className="Constant";le.registerClass(C1);var T1=class extends Zs{constructor(e){super();this.DEFAULT_MINVAL=-.05,this.DEFAULT_MAXVAL=.05,this.minval=e.minval||this.DEFAULT_MINVAL,this.maxval=e.maxval||this.DEFAULT_MAXVAL,this.seed=e.seed}apply(e,t){return Nu(e,this.minval,this.maxval,t)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}};T1.className="RandomUniform";le.registerClass(T1);var N1=class extends Zs{constructor(e){super();this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if(t=t||"float32",t!=="float32"&&t!=="int32")throw new Be(`randomNormal does not support dType ${t}.`);return kf(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};N1.className="RandomNormal";le.registerClass(N1);var E1=class extends Zs{constructor(e){super();this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if(t=t||"float32",t!=="float32"&&t!=="int32")throw new Be(`truncatedNormal does not support dType ${t}.`);return lf(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};E1.className="TruncatedNormal";le.registerClass(E1);var R1=class extends Zs{constructor(e){super();this.gain=e.gain!=null?e.gain:1}apply(e,t){return j(()=>{if(e.length!==2||e[0]!==e[1])throw new q("Identity matrix initializer can only be used for 2D square matrices.");return W(this.gain,z2(e[0]))})}getConfig(){return{gain:this.gain}}};R1.className="Identity";le.registerClass(R1);function dL(e,t="channelsLast"){let n,s;if(jt(t),e.length===2)n=e[0],s=e[1];else if([3,4,5].indexOf(e.length)!==-1){if(t==="channelsFirst"){let r=To(e,2);n=e[1]*r,s=e[0]*r}else if(t==="channelsLast"){let r=To(e,0,e.length-2);n=e[e.length-2]*r,s=e[e.length-1]*r}}else{let r=To(e);n=Math.sqrt(r),s=Math.sqrt(r)}return[n,s]}var is=class extends Zs{constructor(e){super();if(e.scale<0)throw new q(`scale must be a positive float. Got: ${e.scale}`);this.scale=e.scale==null?1:e.scale,this.mode=e.mode==null?"fanIn":e.mode,uL(this.mode),this.distribution=e.distribution==null?"normal":e.distribution,cL(this.distribution),this.seed=e.seed}apply(e,t){let n=dL(e),s=n[0],r=n[1],a=this.scale;if(this.mode==="fanIn"?a/=Math.max(1,s):this.mode==="fanOut"?a/=Math.max(1,r):a/=Math.max(1,(s+r)/2),this.distribution==="normal"){let o=Math.sqrt(a);if(t=t||"float32",t!=="float32"&&t!=="int32")throw new Be(`${this.getClassName()} does not support dType ${t}.`);return lf(e,0,o,t,this.seed)}else{let o=Math.sqrt(3*a);return Nu(e,-o,o,t)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}};is.className="VarianceScaling";le.registerClass(is);var Sf=class extends is{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return is.className}};Sf.className="GlorotUniform";le.registerClass(Sf);var Cf=class extends is{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return is.className}};Cf.className="GlorotNormal";le.registerClass(Cf);var Tf=class extends is{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return is.className}};Tf.className="HeNormal";le.registerClass(Tf);var Nf=class extends is{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return is.className}};Nf.className="HeUniform";le.registerClass(Nf);var Ef=class extends is{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return is.className}};Ef.className="LeCunNormal";le.registerClass(Ef);var Rf=class extends is{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return is.className}};Rf.className="LeCunNormal";le.registerClass(Rf);var $1=class extends Zs{constructor(e){super();if(this.DEFAULT_GAIN=1,this.gain=e.gain==null?this.DEFAULT_GAIN:e.gain,this.seed=e.seed,this.seed!=null)throw new Be("Random seed is not implemented for Orthogonal Initializer yet.")}apply(e,t){return j(()=>{if(e.length<2)throw new Be("Shape must be at least 2D.");e[0]*e[1]>2e3&&console.warn(`Orthogonal initializer is being called on a matrix with more than 2000 (${e[0]*e[1]}) elements: Slowness may result.`);let n=e[0]>e[1]?[e[1],e[0]]:e,s=kf(n,0,1,"float32"),r=Nv.gramSchmidt(s);return e[0]>e[1]&&(r=et(r)),W(this.gain,r)})}getConfig(){return{gain:this.gain,seed:this.seed}}};$1.className="Orthogonal";le.registerClass($1);var aw={constant:"Constant",glorotNormal:"GlorotNormal",glorotUniform:"GlorotUniform",heNormal:"HeNormal",heUniform:"HeUniform",identity:"Identity",leCunNormal:"LeCunNormal",leCunUniform:"LeCunUniform",ones:"Ones",orthogonal:"Orthogonal",randomNormal:"RandomNormal",randomUniform:"RandomUniform",truncatedNormal:"TruncatedNormal",varianceScaling:"VarianceScaling",zeros:"Zeros"};function ow(e,t={}){return bd(e,le.SerializationMap.getMap().classNameMap,t,"initializer")}function Mt(e){return h1(e)}function $t(e){if(typeof e=="string"){let t=e in aw?aw[e]:e;if(t==="GlorotNormal")return new Cf;if(t==="GlorotUniform")return new Sf;if(t==="HeNormal")return new Tf;if(t==="HeUniform")return new Nf;if(t==="LeCunNormal")return new Ef;if(t==="LeCunUniform")return new Rf;{let n={};return n.className=t,n.config={},ow(n)}}else return e instanceof Zs?e:ow(e)}function pL(){return new S1}function hL(){return new If}function fL(e){return new C1(e)}function mL(e){return new T1(e)}function gL(e){return new N1(e)}function AL(e){return new E1(e)}function yL(e){return new R1(e)}function xL(e){return new is(e)}function bL(e){return new Sf(e)}function vL(e){return new Cf(e)}function wL(e){return new Tf(e)}function kL(e){return new Nf(e)}function IL(e){return new Ef(e)}function SL(e){return new Rf(e)}function CL(e){return new $1(e)}var iw={};ze(iw,{Layer:()=>nt,RNN:()=>sa,RNNCell:()=>Dd,activation:()=>iW,add:()=>gW,alphaDropout:()=>QW,average:()=>AW,averagePooling1d:()=>JA,averagePooling2d:()=>QA,averagePooling3d:()=>ey,avgPool1d:()=>CW,avgPool2d:()=>NW,avgPool3d:()=>RW,avgPooling1d:()=>TW,avgPooling2d:()=>EW,avgPooling3d:()=>$W,batchNormalization:()=>kW,bidirectional:()=>HW,concatenate:()=>yW,conv1d:()=>JB,conv2d:()=>QB,conv2dTranspose:()=>eW,conv3d:()=>tW,conv3dTranspose:()=>nW,convLstm2d:()=>WW,convLstm2dCell:()=>VW,cropping2D:()=>rW,dense:()=>lW,depthwiseConv2d:()=>oW,dot:()=>wW,dropout:()=>uW,elu:()=>jB,embedding:()=>mW,flatten:()=>dW,gaussianDropout:()=>JW,gaussianNoise:()=>YW,globalAveragePooling1d:()=>DW,globalAveragePooling2d:()=>_W,globalMaxPool1d:()=>qW,globalMaxPool2d:()=>XW,globalMaxPooling1d:()=>bk,globalMaxPooling2d:()=>vk,gru:()=>FW,gruCell:()=>OW,input:()=>Bw,inputLayer:()=>HB,layerNormalization:()=>IW,leakyReLU:()=>XB,lstm:()=>MW,lstmCell:()=>zW,masking:()=>eV,maxPool1d:()=>KW,maxPool2d:()=>ZW,maxPooling1d:()=>wk,maxPooling2d:()=>kk,maxPooling3d:()=>PW,maximum:()=>xW,minimum:()=>bW,multiply:()=>vW,permute:()=>fW,prelu:()=>KB,reLU:()=>qB,repeatVector:()=>pW,reshape:()=>hW,rnn:()=>UW,separableConv2d:()=>sW,simpleRNN:()=>LW,simpleRNNCell:()=>BW,softmax:()=>ZB,spatialDropout1d:()=>cW,stackedRNNCells:()=>GW,thresholdedReLU:()=>YB,timeDistributed:()=>jW,upSampling2d:()=>aW,zeroPadding2d:()=>SW});var TL=0;function lw(){return TL++}var $f={};function Df(e=""){return e in $f||($f[e]=0),$f[e]+=1,e+$f[e].toString()}function D1(e){return Array.isArray(e)&&Array.isArray(e[0])}function _f(e){return e.length===0?[]:Array.isArray(e[0])?e:[e]}function Ve(e){let t;if(Array.isArray(e)){if(e.length!==1)throw new q(`Expected Tensor length to be 1; got ${e.length}`);t=e[0]}else t=e;return t}function mt(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(e.length===1)return e=e,e[0];throw new q(`Expected exactly 1 Shape; got ${e.length}`)}else return e}function Pf(e){let t=0;for(let n of e)n.shape.length===0?t+=1:t+=n.shape.reduce((s,r)=>s*r);return t}var uw="Variable",cw=class{constructor(e,t="float32",n=uw,s=!0,r=null){this.dtype=t==null?"float32":t,this.shape=e.shape,this.id=lw(),n=n==null?uw:n,this.originalName=Qv(n),this.name=ew(this.originalName),this.trainable_=s,this.constraint=r,this.val=pv(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),NL(this.val,e),this.val.id!==e.id&&(this.val.assign(e),this.constraint!=null&&this.val.assign(this.constraint.apply(this.val))),this}dispose(){this.assertNotDisposed(),this.val.dispose()}assertNotDisposed(){if(this.val.isDisposed)throw new Error(`LayersVariable ${this.name} is already disposed.`)}get trainable(){return this.trainable_}set trainable(e){this.trainable_=e,this.val.trainable=e}};function NL(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape))}function _1(e){return e.map(t=>t.read())}function P1(e){e.forEach(t=>{t[0].write(t[1])})}var Yt=class{constructor(e){this.dtype=e.dtype,this.shape=e.shape,e.shape!=null?this.ndim=e.shape.length:this.ndim=e.ndim,this.maxNDim=e.maxNDim,this.minNDim=e.minNDim,this.axes=e.axes||{}}},fr=class{constructor(e,t,n,s,r,a,o){this.dtype=e,this.shape=t,this.sourceLayer=n,this.inputs=s,this.callArgs=r,this.outputTensorIndex=o,this.id=lw(),a!=null&&(this.originalName=Qv(a),this.name=ew(this.originalName)),this.rank=t.length}},EL=0,Ff=class{constructor(e,t){this.callArgs=t,this.id=EL++,this.outboundLayer=e.outboundLayer,this.inboundLayers=e.inboundLayers,this.nodeIndices=e.nodeIndices,this.tensorIndices=e.tensorIndices,this.inputTensors=e.inputTensors,this.outputTensors=e.outputTensors,this.inputMasks=e.inputMasks,this.outputMasks=e.outputMasks,this.inputShapes=e.inputShapes,this.outputShapes=e.outputShapes;for(let n of e.inboundLayers)n!=null&&n.outboundNodes.push(this);e.outboundLayer.inboundNodes.push(this)}getConfig(){let e=[];for(let t of this.inboundLayers)t!=null?e.push(t.name):e.push(null);return{outboundLayer:this.outboundLayer?this.outboundLayer.name:null,inboundLayers:e,nodeIndices:this.nodeIndices,tensorIndices:this.tensorIndices}}},RL=0,nt=class extends le.Serializable{constructor(e={}){super();this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=RL++,this.activityRegularizer=null,this.inputSpec=null,this.supportsMasking=!1,this._trainableWeights=[],this._nonTrainableWeights=[],this._losses=[],this._updates=[],this._built=!1,this.inboundNodes=[],this.outboundNodes=[];let t=e.name;if(!t){let n=this.getClassName();t=ta(n)+"_"+Df(n)}if(this.name=t,this.trainable_=e.trainable==null?!0:e.trainable,e.inputShape!=null||e.batchInputShape!=null){let n;if(e.batchInputShape!=null)n=e.batchInputShape;else if(e.inputShape!=null){let r=null;e.batchSize!=null&&(r=e.batchSize),n=[r].concat(e.inputShape)}this.batchInputShape=n;let s=e.dtype;s==null&&(s=e.inputDType),s==null&&(s="float32"),this.dtype=s}e.weights!=null?this.initialWeights=e.weights:this.initialWeights=null,this._refCount=null,this.fastWeightInitDuringBuild=!1}static nodeKey(e,t){return e.name+"_ib-"+t.toString()}getNodeAtIndex(e,t){if(this.inboundNodes.length===0)throw new dr(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new q(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return os(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return os(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new ea(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use \`getInputAt(nodeIndex)\` instead.`);if(this.inboundNodes.length===0)throw new ea(`Layer ${this.name} is not connected, no input to return.`);return os(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(this.inboundNodes.length===0)throw new ea(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new ea(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return os(this.getNodeAtIndex(0,"output").outputTensors)}get losses(){return this._losses}calculateLosses(){return this.losses.map(e=>e())}get updates(){return this._updates}get built(){return this._built}set built(e){this._built=e}get trainable(){return this.trainable_}set trainable(e){this._trainableWeights.forEach(t=>t.trainable=e),this.trainable_=e}get trainableWeights(){return this.trainable_?this._trainableWeights.filter(e=>e.trainable):[]}set trainableWeights(e){this._trainableWeights=e}get nonTrainableWeights(){return this.trainable?this._trainableWeights.filter(e=>!e.trainable).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)}set nonTrainableWeights(e){this._nonTrainableWeights=e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}get stateful(){return this._stateful}resetStates(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")}assertInputCompatibility(e){if(e=Ct(e),this.inputSpec==null||this.inputSpec.length===0)return;let t=Ct(this.inputSpec);if(e.length!==t.length)throw new q(`Layer ${this.name} expects ${t.length} inputs, but it received ${e.length} input tensors. Input received: ${e}`);for(let n=0;nr.maxNDim)throw new q(`Input ${n} is incompatible with layer ${this.name}: expected max_ndim=${r.maxNDim}, found ndim=${a}`);if(r.minNDim!=null&&a=0?o[l]:o[o.length+l];if(c!=null&&[c,null].indexOf(u)===-1)throw new q(`Input ${n} is incompatible with layer ${this.name}: expected axis ${l} of input shape to have value ${c} but got shape ${o}.`)}}if(r.shape!=null)for(let o=0;o{if(!this.built){this.assertInputCompatibility(e);let a=[];for(let o of Ct(e))a.push(o.shape);this.build(os(a)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),this._refCount===null&&r&&(this._refCount=1)}if(this.assertInputCompatibility(e),r){let a=this.call(e,t),o=Ct(a),i=[];for(let l of o)n.indexOf(l)!==-1&&(l=l.clone()),i.push(l);if(a=os(i),this.activityRegularizer!=null)throw new Be("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return a}else{let a=$L(e),o=this.computeOutputShape(a),i,l=DL(e);if(this.warnOnIncompatibleInputShape(Array.isArray(e)?a[0]:a),o!=null&&o.length>0&&Array.isArray(o[0])?i=o.map((c,u)=>new fr(l,c,this,Ct(e),t,this.name,u)):i=new fr(l,o,this,Ct(e),t,this.name),this.addInboundNode(e,i,null,null,a,o,t),this._refCount++,this.activityRegularizer!=null)throw new Be("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return i}})}warnOnIncompatibleInputShape(e){if(this.batchInputShape!=null)if(e.length!==this.batchInputShape.length)console.warn(`The rank of the input tensor provided (shape: ${JSON.stringify(e)}) does not match that of the batchInputShape (${JSON.stringify(this.batchInputShape)}) of the layer ${this.name}`);else{let t=!1;this.batchInputShape.forEach((n,s)=>{n!=null&&e[s]!=null&&e[s]!==n&&(t=!0)}),t&&console.warn(`The shape of the input tensor (${JSON.stringify(e)}) does not match the expectation of layer ${this.name}: ${JSON.stringify(this.batchInputShape)}`)}}get outputShape(){if(this.inboundNodes==null||this.inboundNodes.length===0)throw new ea(`The layer ${this.name} has never been called and thus has no defined output shape.`);let e=[];for(let t of this.inboundNodes){let n=JSON.stringify(t.outputShapes);e.indexOf(n)===-1&&e.push(n)}if(e.length===1){let t=this.inboundNodes[0].outputShapes;return Array.isArray(t)&&Array.isArray(t[0])&&t.length===1?t[0]:t}else throw new ea(`The layer ${this.name} has multiple inbound nodes with different output shapes. Hence the notion of "output shape" is ill-defined for the layer.`)}countParams(){if(!this.built)throw new dr(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return Pf(this.weights)}build(e){this.built=!0}getWeights(e=!1){return _1(e?this.trainableWeights:this.weights)}setWeights(e){j(()=>{let t=this.weights;if(t.length!==e.length)throw new q(`You called setWeights(weights) on layer "${this.name}" with a weight list of length ${e.length}, but the layer was expecting ${t.length} weights. Provided weights: ${e}...`);if(t.length===0)return;let n=[],s=_1(t);for(let r=0;rr.apply(c.read())),a==null&&(a=!0),a?this._trainableWeights.push(c):this._nonTrainableWeights.push(c),c}setFastWeightInitDuringBuild(e){this.fastWeightInitDuringBuild=e}addLoss(e){e==null||Array.isArray(e)&&e.length===0||(e=Ct(e),this._losses!==void 0&&this._losses!==null&&this.losses.push(...e))}computeOutputShape(e){return e}computeMask(e,t){if(!this.supportsMasking){if(t!=null)if(Array.isArray(t))t.forEach(n=>{if(n!=null)throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`)});else throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);return null}return t}addInboundNode(e,t,n,s,r,a,o=null){let i=Ct(e);t=Ct(t),n=Ct(n),s=Ct(s),r=_f(r),a=_f(a);let l=[],c=[],u=[];for(let d of i)l.push(d.sourceLayer),c.push(d.nodeIndex),u.push(d.tensorIndex);new Ff({outboundLayer:this,inboundLayers:l,nodeIndices:c,tensorIndices:u,inputTensors:i,outputTensors:t,inputMasks:n,outputMasks:s,inputShapes:r,outputShapes:a},o);for(let d=0;de.dispose()),this.weights.length}assertNotDisposed(){if(this._refCount===0)throw new Error(`Layer '${this.name}' is already disposed.`)}dispose(){if(!this.built)throw new Error(`Cannot dispose Layer ${this.name} because it has not been built yet.`);if(this._refCount===null)throw new Error(`Cannot dispose Layer ${this.name} because it has not been used yet.`);this.assertNotDisposed();let e=0;return--this._refCount==0&&(e=this.disposeWeights()),{refCountAfterDispose:this._refCount,numDisposedVariables:e}}};function $L(e){e=Ct(e);let t=[];for(let n of e)t.push(n.shape);return os(t)}function DL(e){return"float32"}function dw(e,t,n){if((t==null||n!=null&&n>0)&&(t=e.sourceLayer,n=e.nodeIndex),t.inboundNodes.length===0)return[e];{let s=t.inboundNodes[n];if(s.inboundLayers.length===0)return s.inputTensors;{let r=[];for(let a=0;a0){let r=await Promise.all(t);for(let a=0;aie(this.totals[s],W(r,n)));this.totals[s]=o,a!=null&&a.dispose()}}}async onEpochEnd(e,t){if(t!=null)for(let n of this.params.metrics)this.totals[n]!=null&&(typeof this.totals[n]=="number"?t[n]=this.totals[n]/this.seen:j(()=>{let s=W(fe(1,this.seen),this.totals[n]);t[n]=s,this.totals[n].dispose(),yn(t[n])}))}},gw=class extends Ou{async onTrainBegin(e){this.epoch=[],this.history={}}async onEpochEnd(e,t){t==null&&(t={}),this.epoch.push(e);for(let n in t)this.history[n]==null&&(this.history[n]=[]),this.history[n].push(t[n])}async syncData(){let e=[],t=[],n=[];for(let r in this.history){let a=this.history[r];for(let o=0;onew Aw(s,t))}var _r=class{constructor(){}static registerCallbackConstructor(e,t){v.assert(e>=0&&Number.isInteger(e),()=>`Verbosity level is expected to be an integer >= 0, but got ${e}`),_r.checkForDuplicate(t),_r.constructors[e]==null&&(_r.constructors[e]=[]),_r.constructors[e].push(t)}static checkForDuplicate(e){for(let t in _r.constructors)_r.constructors[+t].forEach(s=>{if(s===e)throw new q("Duplicate callback constructor.")})}static clear(){_r.constructors={}}static createCallbacks(e){let t=[];for(let n in _r.constructors){let s=+n;e>=s&&t.push(..._r.constructors[s])}return t.map(n=>new n)}},F1=_r;F1.constructors={};function xw(e,t,n,s,r,a,o,i,l){let c=new gw,u=[new PL,...F1.createCallbacks(t)];e!=null&&u.push(...e),u.push(c);let d=new mw(u);return d.setParams({epochs:n,initialEpoch:s,samples:r,steps:a,batchSize:o,verbose:t,doValidation:i,metrics:l}),{callbackList:d,history:c}}function mr(e,t={},n=!1){return bd(e,le.SerializationMap.getMap().classNameMap,t,"layer",n)}function Of(e,t){return j(()=>{e.dtype!=="float32"&&(e=he(e,"float32"));let n=Ie(Id(e),t,!0),s=Iu(n.shape,on()),r=_n(Yr(n,s));return fe(e,r)})}function il(e,t){return j(()=>Wt(Id(xe(t,e)),-1))}function Mf(e,t){return j(()=>Wt(rn(xe(t,e)),-1))}function Mu(e,t){return j(()=>{let n=xe(e,t),s=fs(rn(e),on(),Number.MAX_VALUE),r=rn(fe(n,s));return W(100,Wt(r,-1))})}function FL(e,t){return j(()=>{let n=fs(t,on(),Number.MAX_VALUE),s=Ns(ie(1,n)),r=fs(e,on(),Number.MAX_VALUE),a=Ns(ie(1,r));return Wt(Id(xe(s,a)),-1)})}function OL(e,t){return j(()=>{let n=Yr(0,xe(1,W(e,t)));return Wt(Id(n),-1)})}function ML(e,t){return j(()=>{let n=Yr(0,xe(1,W(e,t)));return Wt(n,-1)})}function zL(e,t){return j(()=>{let n=Ie(W(e,t),-1),s=rs(W(xe(1,e),t),-1);return Yr(0,ie(1,xe(s,n)))})}function LL(e,t){return j(()=>{let n=Math.log(2),s=xe(t,e),r=xe(ie(s,Cu(W(-2,s))),n);return Wt(r,-1)})}function Cd(e,t,n=!1){return j(()=>{if(n)t=$u(t);else{let s=Ie(t,t.shape.length-1,!0);t=fe(t,s)}return t=fs(t,on(),1-on()),Ot(Ie(W(he(e,"float32"),Ns(t)),t.shape.length-1))})}function zf(e,t,n=!1){return j(()=>{let s=he(pd(nL(e)),"int32");t=fs(t,on(),1-on());let r=t.shape,a=G(id(s,r[r.length-1]),r);return Cd(a,t,n)})}function BL(e,t){if(!v.arraysEqual(e.shape,t.shape))throw new q(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(t.shape)}`);return j(()=>{let n=Rr(t),s=Ot(rn(t));return ie(xe(n,W(t,e)),Zh(Ts(s)))})}function Lf(e,t){return j(()=>{let n;return n=fs(t,on(),1-on()),n=Ns(fe(n,xe(1,n))),Wt(BL(e,n),-1)})}function WL(e,t){return j(()=>{let n=fs(e,on(),1),s=fs(t,on(),1);return Ie(W(e,Ns(fe(n,s))),-1)})}function VL(e,t){return j(()=>{let n=Ns(ie(on(),t));return Wt(xe(t,W(e,n)),-1)})}function O1(e,t){return j(()=>{let n=Of(e,-1),s=Of(t,-1),r=W(n,s);return Ot(Ie(r,-1))})}var Bf={meanSquaredError:il,meanAbsoluteError:Mf,meanAbsolutePercentageError:Mu,meanSquaredLogarithmicError:FL,squaredHinge:OL,hinge:ML,categoricalHinge:zL,logcosh:LL,categoricalCrossentropy:Cd,sparseCategoricalCrossentropy:zf,binaryCrossentropy:Lf,kullbackLeiblerDivergence:WL,poisson:VL,cosineProximity:O1};function M1(e){if(typeof e=="string"){if(e in Bf)return Bf[e];let t=`Unknown loss ${e}`;throw e.toLowerCase().includes("softmaxcrossentropy")&&(t=`Unknown loss ${e}. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy`),new q(t)}else return e}function z1(e,t){return j(()=>{let n=W(.5,Es(t)),s=vf(ms(t,n),e.dtype);return Wt(Cs(e,s),-1)})}function L1(e,t){return j(()=>vf(Cs(Hs(e,-1),Hs(t,-1)),"float32"))}function bw(e,t){return j(()=>he(Ie(lr(Cs(e,1),Cs(t,1))),"float32"))}function UL(e,t){return j(()=>he(Ie(lr(Cs(e,1),Cs(t,0))),"float32"))}function GL(e,t){return j(()=>he(Ie(lr(Cs(e,0),Cs(t,1))),"float32"))}function vw(e,t){return j(()=>{let n=bw(e,t),s=GL(e,t),r=ie(n,s);return he(Wn(ms(r,0),fe(n,r),0),"float32")})}function HL(e,t){return j(()=>{let n=bw(e,t),s=UL(e,t),r=ie(n,s);return he(Wn(ms(r,0),fe(n,r),0),"float32")})}function ww(e,t){return Lf(e,t)}function kw(e,t){return e.rank===t.rank&&(e=pt(e,[e.rank-1])),t=Hs(t,-1),t.dtype!==e.dtype&&(t=he(t,e.dtype)),he(Cs(e,t),"float32")}var jL=il,qL=il,XL=Mf,KL=Mf,ZL=Mu,YL=Mu,B1=Cd,JL=O1,Iw=zf,Wf={binaryAccuracy:z1,categoricalAccuracy:L1,precision:vw,categoricalCrossentropy:B1,sparseCategoricalCrossentropy:Iw,mse:jL,MSE:qL,mae:XL,MAE:KL,mape:ZL,MAPE:YL,cosine:JL};function QL(e){if(typeof e=="string"&&e in Wf)return Wf[e];if(typeof e!="string"&&e!=null)return e;throw new q(`Unknown metric ${e}`)}function Vf(e){if($r(e!==null,`Unknown LossOrMetricFn ${e}`),typeof e=="string")return e;{let t;for(let n of Object.keys(Bf))if(Bf[n]===e){t=n;break}if(t!==void 0)return t;for(let n of Object.keys(Wf))if(Wf[n]===e){t=n;break}return t!==void 0?t:e.name}}function eB(e){let t={Adagrad:()=>tl.adagrad(.01),Adadelta:()=>tl.adadelta(1,.95,on()),Adam:()=>tl.adam(.001,.9,.999,on()),Adamax:()=>tl.adamax(.002,.9,.999,on(),0),RMSProp:()=>tl.rmsprop(.001,.9,0,on()),SGD:()=>tl.sgd(.01)};if(t.adagrad=t.Adagrad,t.adadelta=t.Adadelta,t.adam=t.Adam,t.adamax=t.Adamax,t.rmsprop=t.RMSProp,t.sgd=t.SGD,e in t)return t[e]();throw new q(`Unknown Optimizer ${e}`)}var Sw=1*1024*1024;function Cw(e,t,n=!1){if(e==null||typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype||!W1(e))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(n){let s=JSON.stringify(e);s.length>Sw&&console.warn(`User-defined metadata of model "${t}" is too large in size (length=${s.length} when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= ${Sw}.`)}}function W1(e){if(e===null)return!0;if(typeof e=="object")if(Object.getPrototypeOf(e)===Object.prototype){let t=Object.keys(e);for(let n of t)if(typeof n!="string"||!W1(e[n]))return!1;return!0}else if(Array.isArray(e)){for(let t of e)if(!W1(t))return!1;return!0}else return!1;else{let t=typeof e;return t==="string"||t==="number"||t==="boolean"}}function tB(e,t,n,s=console.log){let r=sB(e),a=["Layer (type)","Output shape","Param #"];r?(t=t||65,n=n||[.45,.85,1]):(t=t||98,n=n||[.33,.55,.67,1]),n[n.length-1]<=1&&(n=n.map(u=>Math.floor(t*u)));let o;if(!r){a.push("Receives inputs"),o=[];for(let u in e.nodesByDepth)o.push(...e.nodesByDepth[u])}s("_".repeat(t)),Uf(a,n,s),s("=".repeat(t));let i=e.layers;for(let u=0;u1||r.length===1&&r[0].inboundLayers.length>1){t=!1;break}s.push(...r)}if(t)for(let r of e.layers){let a=!1;for(let o of r.inboundNodes)if(s.indexOf(o)!==-1)if(a){t=!1;break}else a=!0;if(!t)break}return t}function Uf(e,t,n=console.log){let s="";for(let r=0;r0&&(s=s.slice(0,s.length-1)+" "),s+=e[r],s=s.slice(0,t[r]),s+=" ".repeat(t[r]-s.length);n(s)}function rB(e,t,n){let s;try{s=JSON.stringify(e.outputShape)}catch(i){s="multiple"}let r=e.name,a=e.getClassName(),o=[`${r} (${a})`,s,e.countParams().toString()];Uf(o,t,n)}function aB(e,t,n,s){let r;try{r=JSON.stringify(e.outputShape)}catch(u){r="multiple"}let a=[];for(let u of e.inboundNodes)if(!(n!=null&&n.length>0&&n.indexOf(u)===-1))for(let d=0;df.name),l=[],c=t.names();for(let f of i)c.indexOf(f)!==-1?l.push(t.getValue(f)):l.push(null);s!=null&&(s.maxNumTensors=-1/0,s.minNumTensors=1/0);let u=i.join(",")+"|"+t.names().join(","),d,p;if(G1[u]==null){let f=iB(o,t);d=f.sorted,p=f.recipientCounts,G1[u]=d,Nw[u]=p}d=G1[u],p={},r||Object.assign(p,Nw[u]);let h=new ll(t);for(let f=0;fs.maxNumTensors&&(s.maxNumTensors=$),$0,()=>"Expected at least one fetch, got none");let n=[],s={};if(e.length===1){let r=Ew(e[0],t);n=r.sorted,s=r.recipientMap}else{let r=new Set;for(let a of e){let{sorted:o,recipientMap:i}=Ew(a,t);for(let l of o)r.has(l.name)||(n.push(l),r.add(l.name));for(let l in i)s[l]==null&&(s[l]=new Set),i[l].forEach(c=>s[l].add(c))}}return{sorted:n,recipientCounts:lB(s)}}function lB(e){let t={};for(let n in e)t[n]=e[n].size;return t}function Ew(e,t){let n=new Set,s=[],r={};for(let i of t.names())n.add(i);let a=[],o=[];for(a.push(e);a.length>0;){let i=a[a.length-1];if(n.has(i.name)){a.pop();continue}let l=o[o.length-1]===a.length-1;if(i.inputs.length===0||l)a.pop(),s.push(i),n.add(i.name),l&&o.pop();else{o.push(a.length-1);for(let c of i.inputs)r[c.name]==null&&(r[c.name]=new Set),r[c.name].add(i.name),!n.has(c.name)&&a.push(c)}}return{sorted:s,recipientMap:r}}function uB(e){let t;if(e.sourceLayer.inboundNodes.length===1)t=e.sourceLayer.output;else{let n=null;for(let s=0;sA.name)}`);Co(this.outputs).length!==this.outputs.length&&console.warn(`The list of outputs passed to the model is redundant. All outputs should only appear once. Found: ${this.outputs.map(A=>A.name)}`),this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];for(let A of this.outputs){let y=A.sourceLayer,x=A.nodeIndex,b=A.tensorIndex;this.outputLayers.push(y),this.outputLayersNodeIndices.push(x),this.outputLayersTensorIndices.push(b)}for(let A of this.inputs){let y=A.sourceLayer,x=A.nodeIndex,b=A.tensorIndex;$r(x===0,"input layer has >1 nodes"),$r(b===0,"input layer has >1 tensors"),this.inputLayers.push(y),this.inputLayersNodeIndices.push(x),this.inputLayersTensorIndices.push(b)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let A=0;AA.shape),this.internalOutputShapes=this.outputs.map(A=>A.shape);let t={},n={},s={},r={},a={},o=[],i=(A,y,x,b,w,k)=>{(b==null||w==null||k==null)&&(b=A.sourceLayer,w=A.nodeIndex,k=A.tensorIndex);let S=b.inboundNodes[w];if(x.indexOf(S)!==-1)throw new dr(`The tensor ${A.name} at layer "${b.name}" is part of a cycle.`);if(y.indexOf(S)!==-1)return;this.containerNodes.add(Pr.nodeKey(b,w)),b.id in a||(a[b.id]=Object.keys(a).length),x.indexOf(S)===-1&&x.push(S);let E=S.inboundLayers.length;for(let $=0;$=0;)x.splice(x.indexOf(S),1);o.push(S)},l=[],c=[];for(let A of this.outputs)i(A,l,c);let u=o.slice().reverse();for(let A of u){n[A.id]=A,A.id in t||(t[A.id]=0);let y=t[A.id],x=s[A.outboundLayer.id]==null?0:s[A.outboundLayer.id];y=Math.max(y,x),s[A.outboundLayer.id]=y,r[A.outboundLayer.id]=A.outboundLayer,t[A.id]=y;for(let b=0;bparseInt(A,10)).sort(bf);this.layers=[];for(let A of h){let y=p[A];y.sort((x,b)=>{let w=a[x.id],k=a[b.id];return wk?1:0});for(let x of y)x instanceof Pr&&this.internalContainerRefs.push(x),this.layers.push(x)}this.layersByDepth=p,h=Object.keys(d).map(A=>parseInt(A,10)).sort(bf);let f=this.inputs.slice(),m=[];for(let A of h)for(let y of d[A]){let x=y.outboundLayer;if(x!=null){for(let b of y.inputTensors)if(f.indexOf(b)===-1)throw new dr(`Graph disconnected: cannot obtain value for tensor ${b} at layer "${x.name}". The following previous layers were accessed without issue: ${m}`);for(let b of y.outputTensors)f.push(b);m.push(x.name)}}this.nodesByDepth=d;let g=this.layers.map(A=>A.name);for(let A of g){let y=g.filter(x=>x===A).length;if(y!==1)throw new dr(`The name "${A}" is used ${y} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(g))}this.outboundNodes=[],this.inboundNodes=[],new Ff({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:this.inputs.map(A=>null),outputMasks:this.outputs.map(A=>null),inputShapes:this.inputs.map(A=>A.shape),outputShapes:this.outputs.map(A=>A.shape)}),this.built=!0,this._refCount=1}assertNotDisposed(){if(this._refCount===0)throw new Error(`Container '${this.name}' is already disposed.`)}dispose(){this.assertNotDisposed();let e={refCountAfterDispose:null,numDisposedVariables:0};if(--this._refCount==0){for(let t of this.layers)e.numDisposedVariables+=t.dispose().numDisposedVariables;for(let t of this.internalContainerRefs)e.numDisposedVariables+=t.dispose().numDisposedVariables}return e.refCountAfterDispose=this._refCount,e}get trainable(){return this.trainable_}set trainable(e){this.layers.forEach(t=>{t._trainableWeights.forEach(n=>n.trainable=e)}),this.trainable_=e}get trainableWeights(){if(this._trainableWeights.length>0)throw new q("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];let e=[];for(let t of this.layers)e=e.concat(t.trainableWeights);return e}get nonTrainableWeights(){let e=[];for(let t of this.layers)e.push(...t.nonTrainableWeights);if(!this.trainable){let t=[];for(let n of this.layers)t.push(...n.trainableWeights);return t.concat(e)}return e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(e,t=!0){let n={},s=0;for(let a of this.layers)for(let o of a.weights){if(n[o.originalName]!=null)throw new q(`Duplicate weight name: ${o.originalName}`);n[o.originalName]=o,s++}let r=[];for(let a in e){let o=a;if(n[a]==null){let i=a.split("/");o=i.slice(0,-2).concat([i[i.length-1]]).join("/")}if(n[o]!=null)r.push([n[o],e[a]]);else if(t)throw new q(`Provided weight data has no target variable: ${a}`);delete n[o]}if(t){let a=[];for(let o in n)a.push(o);if(a.length>0)throw new q(`${a.length} of ${s} weights are not set: ${a}`)}P1(r)}updatedConfig(){let e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${U1}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){let n=V1(this.updatedConfig());return t?JSON.stringify(n):n}call(e,t){return j(()=>{e=Ct(e);let n=new ll;for(let s=0;s{e=Ct(e);let n;return t==null?n=nl(null,e.length):n=Ct(t),this.runInternalGraph(e,n)[1]})}computeOutputShape(e){let t=_f(e);if(t.length!==this.inputLayers.length)throw new q(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);let n={};for(let o=0;oparseInt(o,10)).sort(bf);if(s.length>1)for(let o of s){let i=this.nodesByDepth[o];for(let l of i){let c=l.outboundLayer;if(this.inputLayers.map(f=>f.id).indexOf(c.id)!==-1)continue;let u=[];for(let f=0;fparseInt(i,10)).sort(bf);for(let i of s){let l=this.nodesByDepth[i];for(let c of l){let u=c.outboundLayer,d=c.inputTensors,p=c.outputTensors,h=new Array;for(let f of d)f.id in n&&h.push(n[f.id]);if(h.length===d.length){let f={},m,g,A,y;if(c.callArgs!=null&&(f=c.callArgs),h.length===1){let[x,b]=h[0];f.mask==null&&(f.mask=b),A=Ct(u.call(x,f)),y=Ct(u.computeMask(x,b)),m=[x],g=[b]}else m=h.map(x=>x[0]),g=h.map(x=>x[1]),f.mask==null&&(f.mask=g),A=Ct(u.call(m,f)),y=Ct(u.computeMask(m,g));if(u.activityRegularizer)throw new Be("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let x=0;x{let e=[];for(let t of this.layers)for(let n=0;n0){let f=[];for(let m=0;m0&&m.apply(os(A),y)}function l(m){let g=m.name,A=mr(m,t.customObjects!=null?t.customObjects:{});A.setFastWeightInitDuringBuild(s),r[g]=A,m.inboundNodes.forEach(x=>{if(!(x instanceof Array))throw new q(`Corrupted configuration, expected array for nodeData: ${x}`);o(A,x)})}let c=t.name,u=t.layers;for(let m of u)l(m);for(;!Bz(a);)for(let m of u){let g=r[m.name];if(g.name in a){let A=a[g.name];delete a[g.name];for(let y of A)i(g,y)}}let d=[],p=[],h=t.inputLayers;for(let m of h){let g=m[0],A=m[1],y=m[2];$r(g in r);let b=r[g].inboundNodes[A].outputTensors;d.push(b[y])}let f=t.outputLayers;for(let m of f){let g=m[0],A=m[1],y=m[2];$r(g in r);let b=r[g].inboundNodes[A].outputTensors;p.push(b[y])}return new e({inputs:d,outputs:p,name:c})}get stateful(){if(this._stateful)throw new q("Container instance unexpectedly has _stateful = true. The statefulness of a Container is determined by the Layers it contains. Its _stateful property must remain the default false.");for(let e of this.layers)if(e.stateful)return!0;return!1}resetStates(){j(()=>{this.layers.forEach(e=>{e.stateful&&e.resetStates()})})}};function cB(e,t,n){let s=t.length;if(e==null||Array.isArray(e)&&e.length===0)return t.map(r=>null);if(s===1)return Array.isArray(e)&&e.length===1?e:typeof e=="object"&&t[0]in e?[e[t[0]]]:[e];if(Array.isArray(e)){if(e.length!==s)throw new Error(`Provided ${n} is an array of ${e.length} element(s), but the model has ${s} outputs. Make sure a set of weights is provided for each model output.`);return e}else if(typeof e=="object"&&Object.keys(e).length>0&&typeof e[Object.keys(e)[0]]=="object"){let r=[];return t.forEach(a=>{a in e?r.push(e[a]):r.push(null)}),r}else throw new Error(`The model has multiple (${s}) outputs, so ${n} must be either an array with ${s} elements or an object with ${t} keys. Provided ${n} not understood: ${JSON.stringify(e)}`)}function Rw(e,t){return cB(e,t,"classWeight")}async function $w(e,t,n,s){if(t!=null||s!=null)throw new Error("Support sampleWeight is not implemented yet");if(n!=null){let r=j(()=>{if(e.shape.length===1)return or(e);if(e.shape.length===2){if(e.shape[1]>1)return Hs(e,1);if(e.shape[1]===1)return G(e,[e.shape[0]]);throw new Error(`Encountered unexpected last-dimension size (${e.shape[1]}) during handling of class weights. The size is expected to be >= 1.`)}else throw new Error(`Unexpected rank of target (y) tensor (${e.rank}) during handling of class weights. The rank is expected to be 1 or 2.`)}),a=Array.from(await r.data());Q(r);let o=[];return a.forEach(i=>{if(n[i]==null)throw new Error(`classWeight must contain all classes in the training data. The class ${i} exists in the data but not in classWeight`);o.push(n[i])}),Zt(o,"float32")}else return null}function dB(e,t){return W(e,t)}var pB=32;function Dw(e,t){let n,s,r=t;n=r.xs,s=r.ys,v.assert(n!=null&&s!=null,()=>`A Dataset iterator for fitDataset() is expected to generate objects of the form \`{xs: xVal, ys: yVal}\`, where the two values may be \`tf.Tensor\`, an array of Tensors, or a map of string to Tensor. The provided Dataset instead generates ${t}`);let a=_w("input",e.inputNames,n),o=_w("output",e.outputNames,s),i=a[0].shape[0];v.assert(a.length===e.inputs.length,()=>`LayersModel has ${e.inputs.length} inputs, but the dataset provides ${a.length} inputs. (Expected input keys: ${JSON.stringify(e.inputNames)})`),v.assert(o.length===e.outputs.length,()=>`LayersModel has ${e.outputs.length} outputs, but the dataset provides ${o.length} outputs. (Expected output keys: ${JSON.stringify(e.outputNames)})`);for(let l=0;l`Batch size mismatch: input ${e.inputNames[l]} has ${a[l].shape[0]}; expected ${i} based on input ${e.inputNames[0]}.`);for(let l=0;l`Batch size mismatch: output ${e.outputNames[l]} has ${o[l].shape[0]}; expected ${i} based on input ${e.inputNames[0]}.`);return{xs:a,ys:o}}function _w(e,t,n){if(n instanceof Ye)return[n];if(Array.isArray(n))return v.assert(n.length===t.length,()=>`Received an array of ${n.length} Tensors, but expected ${t.length} to match the ${e} keys ${t}.`),n;{let s=[];for(let r of t){if(n[r]==null)throw new q(`The feature data generated by the dataset lacks the required ${e} key '${r}'.`);s.push(n[r])}return s}}function hB(e){if(e.length===3)throw new Be("Validation with sample weights is not implemented yet.");return{xs:e[0],ys:e[1]}}async function fB(e,t,n){let s=n.batchesPerEpoch!=null;if(v.assert(e.optimizer!=null,()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."),v.assert(n!=null,()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."),v.assert(n.epochs!=null&&n.epochs>0&&Number.isInteger(n.epochs),()=>`For fitDataset(), config.epochs is expected to be a positive integer, but got ${n.epochs}`),v.assert(!s||n.batchesPerEpoch>0&&Number.isInteger(n.batchesPerEpoch),()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${n.batchesPerEpoch}`),v.assert(n.validationSplit==null,()=>"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."),e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0;try{let r=n.validationData!=null,a,o;if(r)if(Pw(n.validationData))v.assert(n.validationBatches==null||n.validationBatches>0&&Number.isInteger(n.validationBatches),()=>`For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got ${n.validationBatches}`);else{let g=hB(n.validationData);a=g.xs,o=g.ys}let i=e.makeTrainFunction(),l=e.getDedupedMetricsNames(),c;r?c=l.slice().concat(l.map(g=>"val_"+g)):c=l.slice();let u=yw(n.callbacks,n.yieldEvery),d=n.verbose==null?1:n.verbose,{callbackList:p,history:h}=xw(u,d,n.epochs,null,null,mB(t,n),null,r,c);p.setModel(e),e.history=h,await p.onTrainBegin(),e.stopTraining_=!1;let f=n.initialEpoch==null?0:n.initialEpoch,m=await t.iterator();for(;f=n.batchesPerEpoch:x.done){if(r){let b;Pw(n.validationData)?b=Ct(await e.evaluateDataset(n.validationData,{batches:n.validationBatches})):b=Ct(e.evaluate(a,o,{batchSize:n.validationBatchSize==null?pB:n.validationBatchSize,verbose:0}));for(let w=0;w0)throw new Be("Verbose mode is not implemented yet.");v.assert(!s||n.batches>0&&Number.isInteger(n.batches),()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(n.batches)}`);let o=gB(t)?t:await t.iterator(),i=0,l=0;for(;s?l{if(c.value){let{xs:u,ys:d}=Dw(e,c.value),p=u.concat(d),h=j(()=>r(p));if(Q(p),l===0)for(let m=0;mie(a[m],W(f,g))),l>0&&Q(A)}Q(h),i+=f,++l}return a}),c.done){s&&console.warn(`Your dataset iterator ran out of data during evaluateDataset(). Interrupting evalution. Make sure that your dataset can generate at least \`batches\` batches (in this case, ${n.batches} batches). You may need to use the repeat() function when building your dataset.`);break}}for(let c=0;c0&&Number.isInteger(e),()=>`batchSize is required to be a positive integer, but got ${e}`)}function Ed(e,t,n){return e==null?[null]:Array.isArray(e)?e.map(s=>ol(s,t,n-t)):ol(e,t,n-t)}function j1(e,t){return j(()=>e==null?null:Array.isArray(e)?e.map(n=>j1(n,t)):sw(e,t.dtype==="int32"?t:he(t,"int32")))}function q1(e,t){let n=[],s=0,r=null;for(;s=e&&(r=e),n.push([s,r]),s=r;return n}async function yB(e,t,n,s,r,a,o,i,l,c,u,d,p,h,f){r==null&&(r=32),a==null&&(a=1),u==null&&(u=!0),p==null&&(p=0);let m=!1;if(l!=null&&c!=null&&(m=!0),f!=null&&(m=!0,h==null))throw new q("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");let g=e.checkNumSamples(n,r,h,"steps_per_epoch"),A;g!=null&&(A=pr(0,g)),o==null&&(o=1);let{callbackList:y,history:x}=xw(i,o,a,p,g,h,r,m,d);y.setModel(e),e.history=x,await y.onTrainBegin(),e.stopTraining_=!1;for(let b=p;b{let F=S[E][0],R=S[E][1],P=ol(k,F,R-F);$.batch=E,$.size=R-F;let T=j1(n,P),M=t(T);for(let U=0;U0){if(f=!0,s.validationData.length===2)o=s.validationData[0],i=s.validationData[1];else throw s.validationData.length===3?new Be("validationData including sample weights is not supported yet."):new q(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${s.validationData} is invalid.`);let S=!0,E=await e.standardizeUserData(o,i,null,null,S,d);l=E[0],c=E[1],m=l.concat(c)}else if(s.validationSplit!=null&&s.validationSplit>0&&s.validationSplit<1){f=!0;let S=Math.floor(r[0].shape[0]*(1-s.validationSplit)),E=r[0].shape[0];l=Ed(r,S,E),r=Ed(r,0,S),c=Ed(a,S,E),a=Ed(a,0,S),m=l.concat(c)}else s.validationSteps!=null&&(f=!0);let g=r.concat(a).concat(u);e.checkTrainableWeightsConsistency();let A=e.makeTrainFunction(),y=e.getDedupedMetricsNames(),x,b;f?(e.makeTestFunction(),x=e.testFunction,b=y.slice().concat(y.map(S=>"val_"+S))):(x=null,m=[],b=y.slice());let w=yw(s.callbacks,s.yieldEvery);return await yB(e,A,g,y,d,s.epochs,s.verbose,w,x,m,s.shuffle,b,s.initialEpoch,null,null)}finally{e.isTraining=!1,ul(r,t),ul(a,n),ul(l,o),ul(c,i),u!=null&&Q(u)}}function Fw(e){let t=[];e instanceof Ye&&(e=[e]);for(let n=0;nn.push(r.id));else if(t!=null)for(let r in t){let a=t[r];n.push(a.id)}let s=[];if(e instanceof Ye)n.indexOf(e.id)===-1&&s.push(e);else if(Array.isArray(e))e.forEach(r=>{n.indexOf(r.id)===-1&&s.push(r)});else if(e!=null)for(let r in e){let a=e[r];n.indexOf(a.id)===-1&&s.push(a)}s.forEach(r=>{r.isDisposed||r.dispose()})}function bB(e){return e instanceof Ye}function X1(e){return Array.isArray(e)}function Ow(e){return!bB(e)&&!X1(e)}function Mw(e,t,n,s=!0,r=""){if(t==null||t.length===0){if(e!=null){let o=!1;if(X1(e)&&e.length>0)o=!0;else if(Ow(e)){for(let i in e)if(e.hasOwnProperty(i)){o=!0;break}}else o=!0;if(o)throw new q(`Error when checking model ${r} expected no data, but got ${e}`)}return[]}if(e==null)return t.map(o=>null);let a;if(Ow(e)){e=e,a=[];for(let o of t){if(e[o]==null)throw new q(`No data provided for "${o}". Need data for each key in: ${t}`);a.push(e[o])}}else if(X1(e)){if(e=e,e.length!==t.length)throw new q(`Error when checking model ${r}: the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see ${t.length} Tensor(s), but instead got the following list of Tensor(s): ${e}`);a=e}else{if(e=e,t.length>1)throw new q(`The model ${r} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);a=[e]}if(a=Fw(a),n!=null)for(let o=0;o=0&&c!==u)throw new q(`${r} expected a batch of elements where each example has shape [${n[o].slice(1,n[o].length)}] (i.e.,tensor shape [*,${n[o].slice(1,n[o].length)}]) but the ${r} received an input with ${i.shape[0]} examples, each with shape [${i.shape.slice(1,i.shape.length)}] (tensor shape [${i.shape}])`)}}return a}function vB(e,t,n){let s=Co(e.map(a=>a.shape[0]));s.sort();let r=Co(t.map(a=>a.shape[0]));if(r.sort(),s.length>1)throw new q(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map(a=>a.shape))}`);if(r.length>1)throw new q(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map(a=>a.shape))}`);if(s.length>0&&r.length>0&&!v.arraysEqual(s,r))throw new q(`Input Tensors should have the same number of samples as target Tensors. Found ${s[0]} input sample(s) and ${r[0]} target sample(s).`)}function wB(e,t,n){let s=[il,Lf,Cd];for(let r=0;r1)throw new q(`The model expects ${t.length} ${r} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(e.shape)}.`);a=[e]}if(n!=null)for(let o=0;o[]);let n;if(typeof e=="string"||typeof e=="function")n=[e];else if(Array.isArray(e)||typeof e=="object")n=e;else throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${e}`);if(Array.isArray(n))return t.map(s=>n);{let s=[];for(let r of t){let a=n.hasOwnProperty(r)?n[r]:[];Array.isArray(a)||(a=[a]),s.push(a)}return s}}var IB="layers-model",na=class extends Pr{constructor(e){super(e);this.isTraining=!1}summary(e,t,n=console.log){if(!this.built)throw new q("This model has never been called, thus its weights have not been created yet. So no summary can be displayed. Build the model first (e.g., by calling it on some test data).");tB(this,e,t,n)}compile(e){if(e.loss==null&&(e.loss=[]),this.loss=e.loss,typeof e.optimizer=="string")this.optimizer_=eB(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof Qr))throw new q("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=e.optimizer,this.isOptimizerOwned=!1}let t=[];if(!Array.isArray(e.loss)&&typeof e.loss!="string"&&typeof e.loss!="function"){e.loss=e.loss;for(let a in e.loss)if(this.outputNames.indexOf(a)===-1)throw new q(`Unknown entry in loss dictionary: "${a}". Only expected the following keys: ${this.outputNames}`);for(let a of this.outputNames)e.loss[a]==null&&console.warn(`Output "${a}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${a} during training`),t.push(M1(e.loss[a]))}else if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new q(`When passing an Array as loss, it should have one entry per model output. The model has ${this.outputs.length} output(s), but you passed loss=${e.loss}.`);t=e.loss.map(o=>M1(o))}else{let a=M1(e.loss);this.outputs.forEach(o=>{t.push(a)})}this.lossFunctions=t,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let a=0;a{for(let a=0;a1&&(this.metricsTensors.push([o,a]),this.metricsNames.push(this.outputNames[a]+"_loss"))}});let s=kB(e.metrics,this.outputNames),r=(a,o,i)=>{this.outputNames.length>1&&(o=this.outputNames[a]+"_"+o),this.metricsNames.push(o),this.metricsTensors.push([i,a])};al("metric",()=>{for(let a=0;a{let c="",u,d,p;for(let h of l){if(typeof h=="string"&&["accuracy","acc","crossentropy","ce"].indexOf(h)!==-1){let m=this.internalOutputShapes[a];m[m.length-1]===1||this.lossFunctions[a]===Lf?["accuracy","acc"].indexOf(h)!==-1?d=z1:["crossentropy","ce"].indexOf(h)!==-1&&(d=ww):this.lossFunctions[a]===zf?["accuracy","acc"].indexOf(h)!==-1?d=kw:["crossentropy","ce"].indexOf(h)!==-1&&(d=Iw):["accuracy","acc"].indexOf(h)!==-1?d=L1:["crossentropy","ce"].indexOf(h)!==-1&&(d=B1);let g;["accuracy","acc"].indexOf(h)!==-1?g="acc":["crossentropy","ce"].indexOf(h)!==-1&&(g="ce"),p=d,u=c+g}else p=QL(h),u=c+Vf(h);let f;al(u,()=>{f=p}),r(a,u,f)}})(o)}}),this.collectedTrainableWeights=this.trainableWeights}checkTrainableWeightsConsistency(){this.collectedTrainableWeights!=null&&this.trainableWeights.length!==this.collectedTrainableWeights.length&&console.warn("Discrepancy between trainableweights and collected trainable weights. Did you set `model.trainable` without calling `model.compile()` afterwards?")}evaluate(e,t,n={}){let s=n.batchSize==null?32:n.batchSize;H1(s);let r=!0,a=this.standardizeUserDataXY(e,t,r,s);try{let o=a[0].concat(a[1]);this.makeTestFunction();let i=this.testFunction,l=this.testLoop(i,o,s,n.verbose,n.steps);return os(l)}finally{ul(a[0],e),ul(a[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),AB(this,e,t)}checkNumSamples(e,t,n,s="steps"){let r;if(n!=null){if(r=null,t!=null)throw new q(`If ${s} is set, batchSize must be null or undefined.Got batchSize = ${t}`)}else if(e!=null)Array.isArray(e)?r=e[0].shape[0]:r=e.shape[0];else throw new q(`Either the input data should have a defined shape, or ${s} shoud be specified.`);return r}execute(e,t){if(Array.isArray(t)&&t.length===0)throw new q("`outputs` is an empty Array, which is not allowed.");let n=Array.isArray(t),s=n?t:[t],r=this.retrieveSymbolicTensors(s),a=new ll;if(e instanceof Ye&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new q(`The number of inputs provided (${e.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let i=0;io.name);for(let o=0;o0){let s=[];throw t.forEach((r,a)=>{r==null&&s.push(e[a])}),new q(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(s)}`)}return t}predictLoop(e,t=32,n=!1){return j(()=>{let s=this.checkNumSamples(e);if(n)throw new Be("Verbose predictLoop() is not implemented yet.");let r=q1(s,t),a=this.outputs.map(o=>[]);for(let o=0;o{let l=r[o][0],c=r[o][1],u=Ed(e,l,c),d=[];if(Array.isArray(u))for(let h=0;ha[c].push(l));return os(a.map(o=>It(o,0)))})}predict(e,t={}){let n=Fw(e);zw(n,this.inputNames,this.feedInputShapes,!1);try{let s=t.batchSize==null?32:t.batchSize;return H1(s),this.predictLoop(n,s)}finally{ul(n,e)}}predictOnBatch(e){zw(e,this.inputNames,this.feedInputShapes,!0);let t=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,t)}standardizeUserDataXY(e,t,n=!0,s){if(this.optimizer_==null)throw new dr("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");let r=[];for(let a=0;a0&&e[0].shape[0]%s!=0)throw new q(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${s}. Found: ${e[0].shape[0]} sample(s).`);return[e,t]}async standardizeUserData(e,t,n,s,r=!0,a){let[o,i]=this.standardizeUserDataXY(e,t,r,a);if(n!=null)throw new Error("sample weight is not supported yet.");let l=null;if(s!=null){let c=Rw(s,this.outputNames);l=[];for(let u=0;u{let a=this.checkNumSamples(t,n,r,"steps"),o=[];if(s>0)throw new Be("Verbose mode is not implemented yet.");if(r!=null)throw new Be("steps mode in testLoop() is not implemented yet");{let i=q1(a,n),l=Zt(pr(0,a));for(let c=0;c1&&(r+=`_${Hv(e.slice(0,n),s)}`),t.push(r)}return t}makeTrainFunction(){return e=>{let t=[],n=e.slice(0,this.inputs.length),s=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),r=e.slice(this.inputs.length+this.outputs.length,this.inputs.length+this.outputs.length*2),a=[],o=()=>{let u=[];for(let f=0;f1&&f{h=ie(h,f)}),h},i=this.collectedTrainableWeights.map(u=>u.read()),l=!0;return[this.optimizer_.minimize(o,l,i)].concat(a)}}makeTestFunction(){this.testFunction=e=>j(()=>{let t=[],n,s=e.slice(0,this.inputs.length),r=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),a=[];for(let l=0;lta(t))}else{let t=Object.keys(this.loss);e={};let n=this.loss;for(let s of t)if(typeof n[s]=="string")e[s]=ta(n[s]);else throw new Error("Serialization of non-string loss is not supported.")}return e}getMetricIdentifiers(){if(typeof this.metrics=="string"||typeof this.metrics=="function")return[ta(Vf(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(e=>ta(Vf(e)));{let e={};for(let t in this.metrics)e[t]=ta(Vf(this.metrics[t]));return e}}getTrainingConfig(){return{loss:this.getLossIdentifiers(),metrics:this.getMetricIdentifiers(),optimizer_config:{class_name:this.optimizer.getClassName(),config:this.optimizer.getConfig()}}}loadTrainingConfig(e){if(e.weighted_metrics!=null)throw new Error("Loading weight_metrics is not supported yet.");if(e.loss_weights!=null)throw new Error("Loading loss_weights is not supported yet.");if(e.sample_weight_mode!=null)throw new Error("Loading sample_weight_mode is not supported yet.");let t=Td(e.optimizer_config),n=mr(t),s;if(typeof e.loss=="string")s=sl(e.loss);else if(Array.isArray(e.loss))s=e.loss.map(a=>sl(a));else if(e.loss!=null){s={};for(let a in e.loss)s[a]=sl(e.loss[a])}let r;if(Array.isArray(e.metrics))r=e.metrics.map(a=>sl(a));else if(e.metrics!=null){r={};for(let a in e.metrics)r[a]=sl(e.metrics[a])}this.compile({loss:s,metrics:r,optimizer:n})}async save(e,t){if(typeof e=="string"){let l=ns.getSaveHandlers(e);if(l.length===0)throw new q(`Cannot find any save handlers for URL '${e}'`);if(l.length>1)throw new q(`Found more than one (${l.length}) save handlers for URL '${e}'`);e=l[0]}if(e.save==null)throw new q("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");let n=await ns.encodeWeights(this.getNamedWeights(t)),s=!1,r=null,o={modelTopology:this.toJSON(r,s),format:IB,generatedBy:`TensorFlow.js tfjs-layers v${U1}`,convertedBy:null};if((t==null?!1:t.includeOptimizer)&&this.optimizer!=null){o.trainingConfig=this.getTrainingConfig();let l="optimizer",{data:c,specs:u}=await ns.encodeWeights(await this.optimizer.getWeights(),l);n.specs.push(...u),n.data=ns.concatenateArrayBuffers([n.data,c])}if(this.userDefinedMetadata!=null){let l=!0;Cw(this.userDefinedMetadata,this.name,l),o.userDefinedMetadata=this.userDefinedMetadata}return o.weightData=n.data,o.weightSpecs=n.specs,e.save(o)}setUserDefinedMetadata(e){Cw(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}};na.className="Model";le.registerClass(na);var Lw=class extends na{};Lw.className="Functional";le.registerClass(Lw);async function SB(e,t){"modelTopology"in e||(e={modelTopology:e}),e=e;let n=e.modelTopology;n.model_config!=null&&(n=n.model_config);let s=Td(n),r=mr(s,t);if(e.weightsManifest!=null){let a=await ns.loadWeights(e.weightsManifest,e.pathPrefix,r.weights.map(i=>i.originalName)),o={};for(let i of r.weights)o[i.originalName]=a[i.originalName];r.loadWeights(o),Q(a)}return r}async function CB(e,t){if(t==null&&(t={}),typeof e=="string"){let n=ns.getLoadHandlers(e,t);if(n.length===0)n.push(ns.browserHTTPRequest(e,t));else if(n.length>1)throw new q(`Found more than one (${n.length}) load handlers for URL '${e}'`);e=n[0]}return TB(e,void 0,t)}async function TB(e,t,n){if(n==null&&(n={}),e.load==null)throw new q("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");let s=await e.load(),r=s.modelTopology;r.model_config!=null&&(r=r.model_config);let a=n.strict==null?!0:n.strict,o=s.weightData!=null&&s.weightSpecs!=null&&a,i=mr(Td(r),t,o),l=s.trainingConfig;if(l!=null&&i.loadTrainingConfig(l),s.userDefinedMetadata!=null&&i.setUserDefinedMetadata(s.userDefinedMetadata),s.weightData!=null){if(s.weightSpecs==null)throw new q("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");let{modelWeights:c,optimizerWeights:u}=NB(s.weightData,s.weightSpecs);i.loadWeights(c,a),i.optimizer!=null&&u.length>0&&await i.optimizer.setWeights(u),Q(c),Q(u.map(d=>d.tensor))}return i}function NB(e,t){let n=ns.decodeWeights(e,t),s={},r=[];return t.forEach(a=>{a.group==="optimizer"?r.push({name:a.name,tensor:n[a.name]}):s[a.name]=n[a.name]}),{modelWeights:s,optimizerWeights:r}}var K1=class extends na{constructor(e){super({inputs:[],outputs:[]});if(e=e||{},this.trainable=!0,this.built=!1,this.name=e.name!=null?e.name:Df("sequential_"),e.layers!=null)for(let t of e.layers)this.add(t)}checkShape(e){if(e.inboundNodes[0].outputTensors[0].shape.some(n=>n<0))throw new q(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){let t=e instanceof K1||e instanceof na,n;if(t){if(n=e,n.outputs.length!==1)throw new q("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(n.inputs.length!==1)throw new q("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.")}if(this.outputs.length===0){if(e.inboundNodes.length===0){if(e.batchInputShape==null)throw new q("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");let s=pw({batchShape:e.batchInputShape,dtype:e.dtype,name:e.name+"_input"});e.apply(s)}if(t)this.outputs=n.outputs,this.inputs=n.inputs;else{if(e.inboundNodes.length!==1)throw new q(`A layer added to a Sequential model must not already be connected somewhere else. LayersModel received layer ${e.name} which has ${e.inboundNodes.length} pre-existing inbound connections.`);if(e.inboundNodes[0].outputTensors.length!==1)throw new q("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[e.inboundNodes[0].outputTensors[0]],this.inputs=dw(this.outputs[0])}this.inboundNodes=[],new Ff({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:nl(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(s=>s.shape),outputShapes:this.outputs[0].shape})}else{let s=e.apply(this.outputs[0]);if(Array.isArray(s))throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[s],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(e),this.built=!1}pop(){if(this.layers.length===0)throw new TypeError("There are no layers in the model.");if(this.layers.pop(),this.layers.length===0)this.outputs=[],this.inboundNodes=[],this.outboundNodes=[];else{let e=this.layers.length-1;this.layers[e].outboundNodes=[],this.outputs=[this.layers[e].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}}call(e,t){return this.model==null&&this.build(),this.model.call(e,t)}build(e){if(mt(e),this.inputs.length===0||this.outputs.length===0)throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");this.model=new na({inputs:this.inputs,outputs:this.outputs[0],name:this.name+"_model"}),this.model.trainable=this.trainable,this.supportsMasking=this.model.supportsMasking,this.inputLayers=this.model.inputLayers,this.inputLayersNodeIndices=this.model.inputLayersNodeIndices,this.inputLayersTensorIndices=this.model.inputLayersTensorIndices,this.outputLayers=this.model.outputLayers,this.outputLayersNodeIndices=this.model.outputLayersNodeIndices,this.outputLayersTensorIndices=this.model.outputLayersTensorIndices,this.nodesByDepth=this.model.nodesByDepth,this.containerNodes=this.model.containerNodes,this.outputNames=this.model.outputNames,this.inputNames=this.model.inputNames,this.built=!0}countParams(){return this.built||this.build(),super.countParams()}summary(e,t,n=console.log){this.built||this.build(),super.summary(e,t,n)}setWeights(e){this.model==null&&this.build(),this.model.setWeights(e)}evaluate(e,t,n={}){if(!this.built)throw new dr("The model needs to be compiled before being used.");return this.model.evaluate(e,t,n)}async evaluateDataset(e,t){if(!this.built)throw new dr("The model needs to be compiled before being used.");return this.model.evaluateDataset(e,t)}predict(e,t={}){return this.model==null&&this.build(),this.model.predict(e,t)}predictOnBatch(e){return this.model==null&&this.build(),this.model.predictOnBatch(e)}compile(e){this.build(),this.model.compile(e),this.optimizer_=this.model.optimizer,this.isOptimizerOwned=this.model.isOptimizerOwned,this.loss=this.model.loss,this.metrics=this.model.metrics,this.metricsTensors=this.model.metricsTensors,this.metricsNames=this.model.metricsNames}get optimizer(){return this.model==null?void 0:this.model.optimizer}set optimizer(e){this.model.optimizer=e}async fit(e,t,n={}){if(!this.built)throw new dr("The model needs to be compiled before being used.");return this.model.fit(e,t,n)}async fitDataset(e,t){if(!this.built)throw new dr("The model needs to be compiled before being used.");return this.model.fitDataset(e,t)}async trainOnBatch(e,t){return this.model.trainOnBatch(e,t)}static fromConfig(e,t,n={},s=!1){let r,a={};if(t instanceof Array){if(t[0].className==null||t[0].className==="Merge")throw new q("Legacy serialization format not supported yet.");r=t}else v.assert(t.layers!=null,()=>"When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field."),r=t.layers,delete t.layers,a=t;let o=new e(a);if(!(o instanceof K1))throw new Be(`Sequential.fromConfig called on non-Sequential input: ${o}`);for(let i of r){let c=mr(i,void 0,s);s&&c.setFastWeightInitDuringBuild(!0),o.add(c)}return o}set stopTraining(e){if(this.model==null)throw new q("Cannot set the stopTraining property of a sequential model before it is compiled.");this.model.stopTraining=e}get stopTraining(){if(this.model==null)throw new q("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining}getConfig(){let e=[];for(let t of this.layers){let n={};n.className=t.getClassName(),n.config=t.getConfig(),e.push(n)}return{name:this.name,layers:e}}},Gf=K1;Gf.className="Sequential";le.registerClass(Gf);function EB(e){return new na(e)}function RB(e){return new Gf(e)}function $B(e,t){return t==null&&(t={}),CB(e,t)}function Bw(e){return pw(e)}function DB(e,t){F1.registerCallbackConstructor(e,t)}var ls=class extends le.Serializable{getConfig(){return{}}},Ww=class extends ls{apply(e,t=1){return rL(e,t)}};Ww.className="elu";le.registerClass(Ww);var Vw=class extends ls{apply(e){return Y2(e)}};Vw.className="selu";le.registerClass(Vw);var Uw=class extends ls{apply(e){return Rr(e)}};Uw.className="relu";le.registerClass(Uw);var Gw=class extends ls{apply(e){return j(()=>hd(6,Rr(e)))}};Gw.className="relu6";le.registerClass(Gw);var Hw=class extends ls{apply(e){return e}};Hw.className="linear";le.registerClass(Hw);var jw=class extends ls{apply(e){return hs(e)}};jw.className="sigmoid";le.registerClass(jw);var qw=class extends ls{apply(e){return oL(e)}};qw.className="hardSigmoid";le.registerClass(qw);var Xw=class extends ls{apply(e){return Cu(e)}};Xw.className="softplus";le.registerClass(Xw);var Kw=class extends ls{apply(e){return aL(e)}};Kw.className="softsign";le.registerClass(Kw);var Zw=class extends ls{apply(e){return vu(e)}};Zw.className="tanh";le.registerClass(Zw);var Z1=class extends ls{apply(e,t=-1){return $u(e,t)}};Z1.className="softmax";le.registerClass(Z1);var Yw=class extends ls{apply(e,t=-1){return B2(e,t)}};Yw.className="logSoftmax";le.registerClass(Yw);var Jw=class extends ls{apply(e,t=1){return j(()=>W(hs(W(e,t)),e))}};Jw.className="swish";le.registerClass(Jw);var Qw=class extends ls{apply(e){return j(()=>W(e,vu(Cu(e))))}};Qw.className="mish";le.registerClass(Qw);function Ro(e){return e.getClassName()}function Y1(e,t={}){return bd(e,le.SerializationMap.getMap().classNameMap,t,"activation")}function $o(e){if(e==null){let t={};return t.className="linear",t.config={},Y1(t)}if(typeof e=="string"){let t={};return t.className=e,t.config={},Y1(t)}else return e instanceof ls?e:Y1(e)}function J1(e){if(e!=null&&typeof e!="object")throw new Error(`Argument to L1L2 regularizer's constructor is expected to be an object, but received: ${e}`)}var ek=class extends le.Serializable{},Rd=class extends ek{constructor(e){super();J1(e),this.l1=e==null||e.l1==null?.01:e.l1,this.l2=e==null||e.l2==null?.01:e.l2,this.hasL1=this.l1!==0,this.hasL2=this.l2!==0}apply(e){return j(()=>{let t=Ht([1]);return this.hasL1&&(t=ie(t,Ie(W(this.l1,rn(e))))),this.hasL2&&(t=ie(t,Ie(W(this.l2,Id(e))))),G(t,[])})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}};Rd.className="L1L2";le.registerClass(Rd);function _B(e){return J1(e),new Rd({l1:e!=null?e.l1:null,l2:0})}function PB(e){return J1(e),new Rd({l2:e!=null?e.l2:null,l1:0})}var tk={l1l2:"L1L2"};function bt(e){return h1(e)}function nk(e,t={}){return bd(e,le.SerializationMap.getMap().classNameMap,t,"regularizer")}function Dt(e){if(e==null)return null;if(typeof e=="string"){let n={className:e in tk?tk[e]:e,config:{}};return nk(n)}else return e instanceof ek?e:nk(e)}var Q1=class extends nt{constructor(e){super(e==null?{}:e);this.supportsMasking=!0,e!=null&&(this.maxValue=e.maxValue)}call(e,t){e=Ve(e);let n=Rr(e);return this.maxValue!=null&&(n=fs(n,0,this.maxValue)),n}computeOutputShape(e){return e}getConfig(){let e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}};Q1.className="ReLU";le.registerClass(Q1);var eA=class extends nt{constructor(e){super(e==null?{}:e);this.DEFAULT_ALPHA=.3,e==null&&(e={}),this.alpha=e.alpha==null?this.DEFAULT_ALPHA:e.alpha}call(e,t){let n=Ve(e);return Kh(n,this.alpha)}computeOutputShape(e){return e}getConfig(){let e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};eA.className="LeakyReLU";le.registerClass(eA);var tA=class extends nt{constructor(e){super(e==null?{}:e);if(this.DEFAULT_ALPHA_INITIALIZER="zeros",e==null&&(e={}),this.supportsMasking=!0,this.alphaInitializer=$t(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=Dt(e.alphaRegularizer),this.alphaConstraint=un(e.alphaConstraint),e.sharedAxes==null)this.sharedAxes=null;else if(Array.isArray(e.sharedAxes))this.sharedAxes=e.sharedAxes;else if(typeof e.sharedAxes=="number")this.sharedAxes=[e.sharedAxes];else throw new q(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`)}build(e){e=mt(e);let t=e.slice(1);if(this.sharedAxes!=null)for(let s of this.sharedAxes)t[s-1]=1;this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);let n={};if(this.sharedAxes!=null)for(let s=1;s(jt(t),t==="channelsFirst"?et(e,[0,2,3,1]):e))}function sk(e,t){return j(()=>(jt(t),t==="channelsFirst"?et(e,[0,2,3,4,1]):e))}function FB(e,t,n,s=1,r="valid",a,o=1){return j(()=>{if(a==null&&(a=cr()),jt(a),e.shape.length!==3)throw new q(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(t.shape.length!==3)throw new q(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(n!=null&&n.shape.length!==1)throw new q(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);if(a==="channelsFirst"&&(e=et(e,[0,2,1])),r==="causal")throw new Be("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let i=D2(e,t,s,r==="same"?"same":"valid","NWC",o);return n!=null&&(i=hr(i,n)),i})}function rk(e,t,n,s=[1,1],r="valid",a,o,i=null){return j(()=>{if(a==null&&(a=cr()),jt(a),e.rank!==3&&e.rank!==4)throw new q(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(t.rank!==3&&t.rank!==4)throw new q(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let l=aA(e,a);if(r==="causal")throw new Be("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=So.conv2d({x:l,filter:t,strides:s,pad:r==="same"?"same":"valid",dilations:o,dataFormat:"NHWC",bias:n,activation:i}),a==="channelsFirst"&&(l=et(l,[0,3,1,2])),l})}function OB(e,t,n,s=[1,1,1],r="valid",a,o){return j(()=>{if(a==null&&(a=cr()),jt(a),e.rank!==4&&e.rank!==5)throw new q(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(t.rank!==4&&t.rank!==5)throw new q(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let i=sk(e,a);if(r==="causal")throw new Be("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return i=F2(i,t,s,r==="same"?"same":"valid","NDHWC",o),n!=null&&(i=hr(i,n)),a==="channelsFirst"&&(i=et(i,[0,4,1,2,3])),i})}var oA=class extends nt{constructor(e,t){super(t);if(this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",oA.verifyArgs(t),this.rank=e,xn(this.rank,"rank"),this.rank!==1&&this.rank!==2&&this.rank!==3)throw new Be(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=zu(t.kernelSize,e,"kernelSize"),this.strides=zu(t.strides==null?1:t.strides,e,"strides"),this.padding=t.padding==null?"valid":t.padding,$s(this.padding),this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,jt(this.dataFormat),this.activation=$o(t.activation),this.useBias=t.useBias==null?!0:t.useBias,this.biasInitializer=$t(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=un(t.biasConstraint),this.biasRegularizer=Dt(t.biasRegularizer),this.activityRegularizer=Dt(t.activityRegularizer),this.dilationRate=zu(t.dilationRate==null?1:t.dilationRate,e,"dilationRate"),this.rank===1&&Array.isArray(this.dilationRate)&&this.dilationRate.length!==1)throw new q(`dilationRate must be a number or an array of a single number for 1D convolution, but received ${JSON.stringify(this.dilationRate)}`);if(this.rank===2){if(typeof this.dilationRate=="number")this.dilationRate=[this.dilationRate,this.dilationRate];else if(this.dilationRate.length!==2)throw new q(`dilationRate must be a number or array of two numbers for 2D convolution, but received ${JSON.stringify(this.dilationRate)}`)}else if(this.rank===3){if(typeof this.dilationRate=="number")this.dilationRate=[this.dilationRate,this.dilationRate,this.dilationRate];else if(this.dilationRate.length!==3)throw new q(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}}static verifyArgs(e){if($r("kernelSize"in e,"required key 'kernelSize' not in config"),typeof e.kernelSize!="number"&&!m1(e.kernelSize,"number",1,3))throw new q(`BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received ${JSON.stringify(e.kernelSize)}.`)}getConfig(){let e={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:Ro(this.activation),useBias:this.useBias,biasInitializer:Mt(this.biasInitializer),biasRegularizer:bt(this.biasRegularizer),activityRegularizer:bt(this.activityRegularizer),biasConstraint:ln(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}},$d=class extends oA{constructor(e,t){super(e,t);this.kernel=null,$d.verifyArgs(t),this.filters=t.filters,xn(this.filters,"filters"),this.kernelInitializer=$t(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=un(t.kernelConstraint),this.kernelRegularizer=Dt(t.kernelRegularizer)}build(e){e=mt(e);let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new q(`The channel dimension of the input should be defined. Found ${e[t]}`);let n=e[t],s=this.kernelSize.concat([n,this.filters]);this.kernel=this.addWeight("kernel",s,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[{ndim:this.rank+2,axes:{[t]:n}}],this.built=!0}call(e,t){return j(()=>{e=Ve(e);let n,s=this.bias==null?null:this.bias.read(),r=qv(this.activation.getClassName());if(r!=null&&this.rank===2)n=rk(e,this.kernel.read(),s,this.strides,this.padding,this.dataFormat,this.dilationRate,r);else{if(this.rank===1)n=FB(e,this.kernel.read(),s,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)n=rk(e,this.kernel.read(),s,this.strides,this.padding,this.dataFormat,this.dilationRate);else if(this.rank===3)n=OB(e,this.kernel.read(),s,this.strides,this.padding,this.dataFormat,this.dilationRate);else throw new Be("convolutions greater than 3D are not implemented yet.");this.activation!=null&&(n=this.activation.apply(n))}return n})}computeOutputShape(e){e=mt(e);let t=[],n=this.dataFormat==="channelsLast"?e.slice(1,e.length-1):e.slice(2);for(let r=0;r 0 but got ${JSON.stringify(e.filters)}`)}},ak=class extends $d{constructor(e){super(2,e);ak.verifyArgs(e)}getConfig(){let e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!m1(e.kernelSize,"number",1,2))throw new q(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}},Hf=ak;Hf.className="Conv2D";le.registerClass(Hf);var ok=class extends $d{constructor(e){super(3,e);ok.verifyArgs(e)}getConfig(){let e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!(Array.isArray(e.kernelSize)&&(e.kernelSize.length===1||e.kernelSize.length===3)))throw new q(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}},jf=ok;jf.className="Conv3D";le.registerClass(jf);var iA=class extends Hf{constructor(e){super(e);if(this.inputSpec=[new Yt({ndim:4})],this.padding!=="same"&&this.padding!=="valid")throw new q(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=mt(e),e.length!==4)throw new q("Input should have rank 4; Received input shape: "+JSON.stringify(e));let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new q("The channel dimension of the inputs should be defined. Found `None`.");let n=e[t],s=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",s,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new Yt({ndim:4,axes:{[t]:n}})],this.built=!0}call(e,t){return j(()=>{let n=Ve(e);if(n.shape.length!==4)throw new q(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${n.shape.length}`);let s=n.shape,r=s[0],a,o;this.dataFormat==="channelsFirst"?(a=2,o=3):(a=1,o=2);let i=s[a],l=s[o],c=this.kernelSize[0],u=this.kernelSize[1],d=this.strides[0],p=this.strides[1],h=Fr(i,d,c,this.padding),f=Fr(l,p,u,this.padding),m=[r,h,f,this.filters];this.dataFormat!=="channelsLast"&&(n=et(n,[0,2,3,1]));let g=P2(n,this.kernel.read(),m,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(g=et(g,[0,3,1,2])),this.bias!=null&&(g=hr(g,this.bias.read(),this.dataFormat)),this.activation!=null&&(g=this.activation.apply(g)),g})}computeOutputShape(e){e=mt(e);let t=e.slice(),n,s,r;this.dataFormat==="channelsFirst"?(n=1,s=2,r=3):(n=3,s=1,r=2);let a=this.kernelSize[0],o=this.kernelSize[1],i=this.strides[0],l=this.strides[1];return t[n]=this.filters,t[s]=Fr(t[s],i,a,this.padding),t[r]=Fr(t[r],l,o,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};iA.className="Conv2DTranspose";le.registerClass(iA);var lA=class extends jf{constructor(e){super(e);if(this.inputSpec=[new Yt({ndim:5})],this.padding!=="same"&&this.padding!=="valid")throw new q(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=mt(e),e.length!==5)throw new q("Input should have rank 5; Received input shape: "+JSON.stringify(e));let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new q("The channel dimension of the inputs should be defined. Found `None`.");let n=e[t],s=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",s,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new Yt({ndim:5,axes:{[t]:n}})],this.built=!0}call(e,t){return j(()=>{let n=Ve(e);if(n.shape.length!==5)throw new q(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${n.shape.length}`);let s=n.shape,r=s[0],a,o,i;this.dataFormat==="channelsFirst"?(i=2,a=3,o=4):(i=1,a=2,o=3);let l=s[i],c=s[a],u=s[o],d=this.kernelSize[0],p=this.kernelSize[1],h=this.kernelSize[2],f=this.strides[0],m=this.strides[1],g=this.strides[2],A=Fr(l,f,d,this.padding),y=Fr(c,m,p,this.padding),x=Fr(u,g,h,this.padding),b=[r,A,y,x,this.filters];this.dataFormat!=="channelsLast"&&(n=et(n,[0,2,3,4,1]));let w=M3(n,this.kernel.read(),b,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(w=et(w,[0,4,1,2,3])),this.bias!==null&&(w=hr(w,this.bias.read(),this.dataFormat)),this.activation!==null&&(w=this.activation.apply(w)),w})}computeOutputShape(e){e=mt(e);let t=e.slice(),n,s,r,a;this.dataFormat==="channelsFirst"?(n=1,s=2,r=3,a=4):(n=4,s=1,r=2,a=3);let o=this.kernelSize[0],i=this.kernelSize[1],l=this.kernelSize[2],c=this.strides[0],u=this.strides[1],d=this.strides[2];return t[n]=this.filters,t[s]=Fr(t[s],c,o,this.padding),t[r]=Fr(t[r],u,i,this.padding),t[a]=Fr(t[a],d,l,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};lA.className="Conv3DTranspose";le.registerClass(lA);var ik=class extends $d{constructor(e,t){super(e,t);if(this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,t.filters==null)throw new q("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(t.kernelInitializer!=null||t.kernelRegularizer!=null||t.kernelConstraint!=null)throw new q("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(t.padding!=null&&t.padding!=="same"&&t.padding!=="valid")throw new q(`SeparableConv${this.rank}D supports only padding modes: 'same' and 'valid', but received ${JSON.stringify(t.padding)}`);this.depthMultiplier=t.depthMultiplier==null?1:t.depthMultiplier,this.depthwiseInitializer=$t(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=Dt(t.depthwiseRegularizer),this.depthwiseConstraint=un(t.depthwiseConstraint),this.pointwiseInitializer=$t(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=Dt(t.pointwiseRegularizer),this.pointwiseConstraint=un(t.pointwiseConstraint)}build(e){if(e=mt(e),e.length{e=Ve(e);let n;if(this.rank===1)throw new Be("1D separable convolution is not implemented yet.");return this.rank===2&&(this.dataFormat==="channelsFirst"&&(e=et(e,[0,2,3,1])),n=av(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(n=hr(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),this.dataFormat==="channelsFirst"&&(n=et(n,[0,3,1,2])),n})}getConfig(){let e=super.getConfig();return delete e.rank,delete e.kernelInitializer,delete e.kernelRegularizer,delete e.kernelConstraint,e.depthwiseInitializer=Mt(this.depthwiseInitializer),e.pointwiseInitializer=Mt(this.pointwiseInitializer),e.depthwiseRegularizer=bt(this.depthwiseRegularizer),e.pointwiseRegularizer=bt(this.pointwiseRegularizer),e.depthwiseConstraint=ln(this.depthwiseConstraint),e.pointwiseConstraint=ln(this.pointwiseConstraint),e}};ik.className="SeparableConv";var uA=class extends ik{constructor(e){super(2,e)}};uA.className="SeparableConv2D";le.registerClass(uA);var lk=class extends $d{constructor(e){super(1,e);lk.verifyArgs(e),this.inputSpec=[{ndim:3}]}getConfig(){let e=super.getConfig();return delete e.rank,delete e.dataFormat,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!m1(e.kernelSize,"number",1,1))throw new q(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}},cA=lk;cA.className="Conv1D";le.registerClass(cA);var dA=class extends nt{constructor(e){super(e);typeof e.cropping=="number"?this.cropping=[[e.cropping,e.cropping],[e.cropping,e.cropping]]:typeof e.cropping[0]=="number"?this.cropping=[[e.cropping[0],e.cropping[0]],[e.cropping[1],e.cropping[1]]]:this.cropping=e.cropping,this.dataFormat=e.dataFormat===void 0?"channelsLast":e.dataFormat,this.inputSpec=[{ndim:4}]}computeOutputShape(e){return this.dataFormat==="channelsFirst"?[e[0],e[1],e[2]-this.cropping[0][0]-this.cropping[0][1],e[3]-this.cropping[1][0]-this.cropping[1][1]]:[e[0],e[1]-this.cropping[0][0]-this.cropping[0][1],e[2]-this.cropping[1][0]-this.cropping[1][1],e[3]]}call(e,t){return j(()=>{if(e=Ve(e),this.dataFormat==="channelsLast"){let n=wf(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return wf(n,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}else{let n=wf(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return wf(n,this.cropping[1][0],e.shape[3]-this.cropping[1][1]-this.cropping[1][0],4)}})}getConfig(){let e={cropping:this.cropping,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};dA.className="Cropping2D";le.registerClass(dA);var pA=class extends nt{constructor(e){super(e);this.DEFAULT_SIZE=[2,2],this.inputSpec=[{ndim:4}],this.size=e.size==null?this.DEFAULT_SIZE:e.size,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,jt(this.dataFormat),this.interpolation=e.interpolation==null?"nearest":e.interpolation,Yz(this.interpolation)}computeOutputShape(e){if(this.dataFormat==="channelsFirst"){let t=e[2]==null?null:this.size[0]*e[2],n=e[3]==null?null:this.size[1]*e[3];return[e[0],e[1],t,n]}else{let t=e[1]==null?null:this.size[0]*e[1],n=e[2]==null?null:this.size[1]*e[2];return[e[0],t,n,e[3]]}}call(e,t){return j(()=>{let n=Ve(e),s=n.shape;if(this.dataFormat==="channelsFirst"){n=et(n,[0,2,3,1]);let r=this.size[0]*s[2],a=this.size[1]*s[3],o=this.interpolation==="nearest"?$e.resizeNearestNeighbor(n,[r,a]):$e.resizeBilinear(n,[r,a]);return et(o,[0,3,1,2])}else{let r=this.size[0]*s[1],a=this.size[1]*s[2];return this.interpolation==="nearest"?$e.resizeNearestNeighbor(n,[r,a]):$e.resizeBilinear(n,[r,a])}})}getConfig(){let e={size:this.size,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};pA.className="UpSampling2D";le.registerClass(pA);function MB(e,t,n=[1,1],s="valid",r,a){return j(()=>{r==null&&(r=cr()),jt(r);let o=aA(e,r);if(e.rank!==4)throw new q(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(t.rank!==4)throw new q(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return o=cd(o,t,n,s==="same"?"same":"valid","NHWC",a),r==="channelsFirst"&&(o=et(o,[0,3,1,2])),o})}var hA=class extends oA{constructor(e){super(2,e);this.depthwiseKernel=null,this.depthMultiplier=e.depthMultiplier==null?1:e.depthMultiplier,this.depthwiseInitializer=$t(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=un(e.depthwiseConstraint),this.depthwiseRegularizer=Dt(e.depthwiseRegularizer)}build(e){if(e=mt(e),e.length<4)throw new q(`Inputs to DepthwiseConv2D should have rank 4. Received input shape: ${JSON.stringify(e)}.`);let t=this.dataFormat==="channelsFirst"?1:3;if(e[t]==null||e[t]<0)throw new q(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);let n=e[t],s=[this.kernelSize[0],this.kernelSize[1],n,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",s,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[n*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return j(()=>{e=Ve(e);let n=MB(e,this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(n=hr(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),n})}computeOutputShape(e){e=mt(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2],s=this.dataFormat==="channelsFirst"?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,r=gr(t,this.kernelSize[0],this.padding,this.strides[0]),a=gr(n,this.kernelSize[1],this.padding,this.strides[1]);return this.dataFormat==="channelsFirst"?[e[0],s,r,a]:[e[0],r,a,s]}getConfig(){let e=super.getConfig();return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=Mt(this.depthwiseInitializer),e.depthwiseRegularizer=bt(this.depthwiseRegularizer),e.depthwiseConstraint=ln(this.depthwiseRegularizer),e}};hA.className="DepthwiseConv2D";le.registerClass(hA);function uk(e,t,n,s){if(Array.isArray(e)){if(t!=null||n!=null)throw new q("When inputs is an array, neither initialState or constants should be provided");s!=null&&(n=e.slice(e.length-s,e.length),e=e.slice(0,e.length-s)),e.length>1&&(t=e.slice(1,e.length)),e=e[0]}function r(a){return a==null||Array.isArray(a)?a:[a]}return t=r(t),n=r(n),{inputs:e,initialState:t,constants:n}}function ck(e,t,n,s=!1,r,a,o=!1,i=!1){return j(()=>{let l=t.shape.length;if(l<3)throw new q(`Input should be at least 3D, but is ${l}D.`);let c=[1,0].concat(pr(2,l));if(t=et(t,c),a!=null)throw new Be("The rnn() functoin of the deeplearn.js backend does not support constants yet.");o&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),r!=null&&(r=he(he(r,"bool"),"float32"),r.rank===l-1&&(r=Kt(r,-1)),r=et(r,c)),s&&(t=Rs(t,0),r!=null&&(r=Rs(r,0)));let u=[],d,p=n,h=t.shape[0],f=as(t),m;r!=null&&(m=as(r));for(let A=0;Ae(y,p));if(r==null)d=x[0],p=x[1];else{let b=j(()=>{let w=m[A],k=xe(Es(w),w),S=ie(W(x[0],w),W(p[0],k)),E=p.map(($,F)=>ie(W(x[1][F],w),W($,k)));return{output:S,newStates:E}});d=b.output,p=b.newStates}i&&u.push(d)}let g;return i&&(g=Pn(u,1)),[d,g,p]})}var dk=class extends nt{constructor(e){super(e);let t;if(e.cell==null)throw new q("cell property is missing for the constructor of RNN.");if(Array.isArray(e.cell)?t=new Kf({cells:e.cell}):t=e.cell,t.stateSize==null)throw new q("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");this.cell=t,this.returnSequences=e.returnSequences==null?!1:e.returnSequences,this.returnState=e.returnState==null?!1:e.returnState,this.goBackwards=e.goBackwards==null?!1:e.goBackwards,this._stateful=e.stateful==null?!1:e.stateful,this.unroll=e.unroll==null?!1:e.unroll,this.supportsMasking=!0,this.inputSpec=[new Yt({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){if(this.states_==null){let e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;return pr(0,e).map(t=>null)}else return this.states_}setStates(e){this.states_=e}computeOutputShape(e){D1(e)&&(e=e[0]),e=e;let t=this.cell.stateSize;Array.isArray(t)||(t=[t]);let n=t[0],s;if(this.returnSequences?s=[e[0],e[1],n]:s=[e[0],n],this.returnState){let r=[];for(let a of t)r.push([e[0],a]);return[s].concat(r)}else return s}computeMask(e,t){return j(()=>{Array.isArray(t)&&(t=t[0]);let n=this.returnSequences?t:null;if(this.returnState){let s=this.states.map(r=>null);return[n].concat(s)}else return n})}get states(){if(this.states_==null){let e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,t=[];for(let n=0;no.shape[o.shape.length-1]),a))throw new q(`An initialState was passed that is not compatible with cell.stateSize. Received stateSpec=${this.stateSpec}; However cell.stateSize is ${this.cell.stateSize}`)}else this.stateSpec=a.map(o=>new Yt({shape:[null,o]}));this.stateful&&this.resetStates()}resetStates(e,t=!1){j(()=>{if(!this.stateful)throw new ea("Cannot call resetStates() on an RNN Layer that is not stateful.");let n=this.inputSpec[0].shape[0];if(n==null)throw new q("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(this.states_==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(s=>Ht([n,s])):this.states_=[Ht([n,this.cell.stateSize])];else if(e==null)Q(this.states_),this.keptStates!=null&&(Q(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(s=>Ht([n,s])):this.states_[0]=Ht([n,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new q(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);t===!0?this.keptStates.push(this.states_.slice()):Q(this.states_);for(let s=0;syn(s.clone()))})}apply(e,t){let n=t==null?null:t.initialState,s=t==null?null:t.constants;t==null&&(t={});let r=uk(e,n,s,this.numConstants);e=r.inputs,n=r.initialState,s=r.constants;let a=[],o=[];if(n!=null){t.initialState=n,a=a.concat(n),this.stateSpec=[];for(let l of n)this.stateSpec.push(new Yt({shape:l.shape}));o=o.concat(this.stateSpec)}if(s!=null&&(t.constants=s,a=a.concat(s),this.numConstants=s.length),a[0]instanceof fr){let l=[e].concat(a),c=this.inputSpec.concat(o),u=this.inputSpec;this.inputSpec=c;let d=super.apply(l,t);return this.inputSpec=u,d}else return super.apply(e,t)}call(e,t){return j(()=>{let n=t==null?null:t.mask,s=t==null?null:t.training,r=t==null?null:t.initialState;e=Ve(e),r==null&&(this.stateful?r=this.states_:r=this.getInitialState(e));let a=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(r.length!==a)throw new q(`RNN Layer has ${a} state(s) but was passed ${r.length} initial state(s).`);this.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");let o={training:s},l=ck((h,f)=>{let m=this.cell.call([h].concat(f),o);return[m[0],m.slice(1)]},e,r,this.goBackwards,n,null,this.unroll,this.returnSequences),c=l[0],u=l[1],d=l[2];this.stateful&&this.resetStates(d,s);let p=this.returnSequences?u:c;return this.returnState?[p].concat(d):p})}getInitialState(e){return j(()=>{let t=Ht(e.shape);return t=Ie(t,[1,2]),t=kd(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(n=>n>1?k1(t,[1,n]):t):this.cell.stateSize>1?[k1(t,[1,this.cell.stateSize])]:[t]})}get trainableWeights(){return this.trainable?this.cell.trainableWeights:[]}get nonTrainableWeights(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.cell!=null&&this.cell.setFastWeightInitDuringBuild(e)}getConfig(){let e=super.getConfig(),t={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};this.numConstants!=null&&(t.numConstants=this.numConstants);let n=this.cell.getConfig();return this.getClassName()===dk.className&&(t.cell={className:this.cell.getClassName(),config:n}),{...n,...e,...t}}static fromConfig(e,t,n={}){let s=t.cell,r=mr(s,n);return new e(Object.assign(t,{cell:r}))}},sa=dk;sa.className="RNN";le.registerClass(sa);var Dd=class extends nt{},qf=class extends Dd{constructor(e){super(e);this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,xn(this.units,"units"),this.activation=$o(e.activation==null?this.DEFAULT_ACTIVATION:e.activation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=$t(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=$t(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=$t(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Dt(e.kernelRegularizer),this.recurrentRegularizer=Dt(e.recurrentRegularizer),this.biasRegularizer=Dt(e.biasRegularizer),this.kernelConstraint=un(e.kernelConstraint),this.recurrentConstraint=un(e.recurrentConstraint),this.biasConstraint=un(e.biasConstraint),this.dropout=Pu([1,No([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Pu([1,No([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=mt(e),this.kernel=this.addWeight("kernel",[e[e.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return j(()=>{if(e=e,e.length!==2)throw new q(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let n=e[1];e=e[0];let s=t.training==null?!1:t.training;0Es(e),rate:this.dropout,training:s,dropoutFunc:this.dropoutFunc})),0Es(n),rate:this.recurrentDropout,training:s,dropoutFunc:this.dropoutFunc}));let r,a=this.dropoutMask,o=this.recurrentDropoutMask;a!=null?r=Dr(W(e,a),this.kernel.read()):r=Dr(e,this.kernel.read()),this.bias!=null&&(r=hr(r,this.bias.read())),o!=null&&(n=W(n,o));let i=ie(r,Dr(n,this.recurrentKernel.read()));return this.activation!=null&&(i=this.activation.apply(i)),[i,i]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:Ro(this.activation),useBias:this.useBias,kernelInitializer:Mt(this.kernelInitializer),recurrentInitializer:Mt(this.recurrentInitializer),biasInitializer:Mt(this.biasInitializer),kernelRegularizer:bt(this.kernelRegularizer),recurrentRegularizer:bt(this.recurrentRegularizer),biasRegularizer:bt(this.biasRegularizer),activityRegularizer:bt(this.activityRegularizer),kernelConstraint:ln(this.kernelConstraint),recurrentConstraint:ln(this.recurrentConstraint),biasConstraint:ln(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return{...e,...t}}};qf.className="SimpleRNNCell";le.registerClass(qf);var fA=class extends sa{constructor(e){e.cell=new qf(e);super(e)}call(e,t){return j(()=>{this.cell.dropoutMask!=null&&(Q(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Q(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let n=t==null?null:t.mask,s=t==null?null:t.training,r=t==null?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:r})})}static fromConfig(e,t){return new e(t)}};fA.className="SimpleRNN";le.registerClass(fA);var Xf=class extends Dd{constructor(e){super(e);if(this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.resetAfter)throw new q("GRUCell does not support reset_after parameter set to true.");this.units=e.units,xn(this.units,"units"),this.activation=$o(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=$o(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=$t(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=$t(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=$t(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Dt(e.kernelRegularizer),this.recurrentRegularizer=Dt(e.recurrentRegularizer),this.biasRegularizer=Dt(e.biasRegularizer),this.kernelConstraint=un(e.kernelConstraint),this.recurrentConstraint=un(e.recurrentConstraint),this.biasConstraint=un(e.biasConstraint),this.dropout=Pu([1,No([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Pu([1,No([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=mt(e);let t=e[e.length-1];this.kernel=this.addWeight("kernel",[t,this.units*3],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*3],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units*3],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return j(()=>{if(e=e,e.length!==2)throw new q(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);let n=t.training==null?!1:t.training,s=e[1];e=e[0],0Es(e),rate:this.dropout,training:n,count:3,dropoutFunc:this.dropoutFunc})),0Es(s),rate:this.recurrentDropout,training:n,count:3,dropoutFunc:this.dropoutFunc}));let r=this.dropoutMask,a=this.recurrentDropoutMask,o,i,l;0{this.cell.dropoutMask!=null&&(Q(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Q(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let n=t==null?null:t.mask,s=t==null?null:t.training,r=t==null?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:r})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}};mA.className="GRU";le.registerClass(mA);var _d=class extends Dd{constructor(e){super(e);this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,xn(this.units,"units"),this.activation=$o(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=$o(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=$t(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=$t(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=$t(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=Dt(e.kernelRegularizer),this.recurrentRegularizer=Dt(e.recurrentRegularizer),this.biasRegularizer=Dt(e.biasRegularizer),this.kernelConstraint=un(e.kernelConstraint),this.recurrentConstraint=un(e.recurrentConstraint),this.biasConstraint=un(e.biasConstraint),this.dropout=Pu([1,No([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Pu([1,No([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=[this.units,this.units],this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){var t;e=mt(e);let n=e[e.length-1];this.kernel=this.addWeight("kernel",[n,this.units*4],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*4],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint);let s;if(this.useBias){if(this.unitForgetBias){let r=this.biasInitializer,a=this.units;s=new(t=class extends Zs{apply(o,i){let l=r.apply([a]),c=new If().apply([a]),u=r.apply([a*2]);return nw(nw(l,c),u)}},t.className="CustomInit",t)}else s=this.biasInitializer;this.bias=this.addWeight("bias",[this.units*4],null,s,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,t){return j(()=>{let n=t.training==null?!1:t.training;if(e=e,e.length!==3)throw new q(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let s=e[1],r=e[2];e=e[0],0Es(e),rate:this.dropout,training:n,count:4,dropoutFunc:this.dropoutFunc})),0Es(s),rate:this.recurrentDropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));let a=this.dropoutMask,o=this.recurrentDropoutMask,i,l,c,u;0{this.cell.dropoutMask!=null&&(Q(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Q(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let n=t==null?null:t.mask,s=t==null?null:t.training,r=t==null?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:r})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}};gA.className="LSTM";le.registerClass(gA);var Kf=class extends Dd{constructor(e){super(e);this.cells=e.cells}get stateSize(){let e=[];for(let t of this.cells.slice().reverse())Array.isArray(t.stateSize)?e.push(...t.stateSize):e.push(t.stateSize);return e}call(e,t){return j(()=>{e=e;let n=e.slice(1),s=[];for(let o of this.cells.slice().reverse())Array.isArray(o.stateSize)?s.push(n.splice(0,o.stateSize.length)):s.push(n.splice(0,1));s.reverse();let r=[],a;for(let o=0;o{al(`RNNCell_${s}`,()=>{n.build(e),Array.isArray(n.stateSize)?t=n.stateSize[0]:t=n.stateSize,e=[e[0],t]})}),this.built=!0}getConfig(){let e=super.getConfig(),t=r=>({className:r.getClassName(),config:r.getConfig()}),s={cells:this.cells.map(t)};return{...e,...s}}static fromConfig(e,t,n={}){let s=[];for(let r of t.cells)s.push(mr(r,n));return new e({cells:s})}get trainableWeights(){if(!this.trainable)return[];let e=[];for(let t of this.cells)e.push(...t.trainableWeights);return e}get nonTrainableWeights(){let e=[];for(let t of this.cells)e.push(...t.nonTrainableWeights);if(!this.trainable){let t=[];for(let n of this.cells)t.push(...n.trainableWeights);return t.concat(e)}return e}getWeights(){let e=[];for(let t of this.cells)e.push(...t.weights);return _1(e)}setWeights(e){let t=[];for(let n of this.cells){let s=n.weights.length,r=e.splice(s);for(let a=0;aa!=null?a(t(),n):rw(t(),n),i=()=>Sd(o,t,s);return!r||r<=1?yn(i().clone()):Array(r).fill(void 0).map(i).map(c=>yn(c.clone()))}var pk=class extends sa{constructor(e){if(e.unroll)throw new Be("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new Be("It is not possible at the moment to stack convolutional cells.");super(e);this.inputSpec=[new Yt({ndim:5})]}call(e,t){return j(()=>{if(this.cell.dropoutMask!=null&&(Q(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Q(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new q("ConvRNN2D cell does not support constants");let n=t==null?null:t.mask,s=t==null?null:t.training,r=t==null?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:r})})}computeOutputShape(e){let t=this.computeSingleOutputShape(e);return this.returnSequences||(t=[t[0],...t.slice(2)]),this.returnState&&(t=[t,...Array(2).fill([e[0],...t.slice(-3)])]),t}getInitialState(e){return j(()=>{let{stateSize:t}=this.cell,n=e.shape,s=this.computeSingleOutputShape(n),r=[s[0],...s.slice(2)],a=Ht(r);return Array.isArray(t)?Array(t.length).fill(a):[a]})}resetStates(e,t=!1){j(()=>{if(!this.stateful)throw new ea("Cannot call resetStates() on an RNN Layer that is not stateful.");let n=this.inputSpec[0].shape,s=this.computeSingleOutputShape(n),r=[s[0],...s.slice(2)];if(n[0]==null)throw new q("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(this.getStates()==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>Ht(r)):this.states_=[Ht(r)];else if(e==null)Q(this.states_),this.keptStates!=null&&(Q(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>Ht(r)):this.states_[0]=Ht(r);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new q(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);t?this.keptStates.push(this.states_.slice()):Q(this.states_);for(let o=0;oyn(o.clone()))})}computeSingleOutputShape(e){let{dataFormat:t,filters:n,kernelSize:s,padding:r,strides:a,dilationRate:o}=this.cell,i=t==="channelsFirst",l=e[i?3:2],c=e[i?4:3],u=gr(l,s[0],r,a[0],o[0]),d=gr(c,s[1],r,a[1],o[1]);return[...e.slice(0,2),...i?[n,u,d]:[u,d,n]]}};pk.className="ConvRNN2D";var Zf=class extends _d{constructor(e){let{filters:t,kernelSize:n,strides:s,padding:r,dataFormat:a,dilationRate:o}=e;super({...e,units:t});this.filters=t,xn(this.filters,"filters"),this.kernelSize=zu(n,2,"kernelSize"),this.kernelSize.forEach(i=>xn(i,"kernelSize")),this.strides=zu(s||1,2,"strides"),this.strides.forEach(i=>xn(i,"strides")),this.padding=r||"valid",$s(this.padding),this.dataFormat=a||"channelsLast",jt(this.dataFormat),this.dilationRate=zu(o||1,2,"dilationRate"),this.dilationRate.forEach(i=>xn(i,"dilationRate"))}build(e){var t;e=mt(e);let n=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[n]==null)throw new q(`The channel dimension of the input should be defined. Found ${e[n]}`);let s=e[n],r=4,a=this.kernelSize.concat([s,this.filters*r]);this.kernel=this.addWeight("kernel",a,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);let o=this.kernelSize.concat([this.filters,this.filters*r]);if(this.recurrentKernel=this.addWeight("recurrent_kernel",o,null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){let i;if(this.unitForgetBias){let l=this.biasInitializer,c=this.filters;i=new(t=class extends Zs{apply(u,d){let p=l.apply([c]),h=gs([c]),f=l.apply([c*2]);return w1([p,h,f])}},t.className="CustomInit",t)}else i=this.biasInitializer;this.bias=this.addWeight("bias",[this.filters*r],null,i,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(e,t){return j(()=>{if(e.length!==3)throw new q(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let n=t.training||!1,s=e[0],r=e[1],a=e[2],o=4;0Es(s),rate:this.dropout,training:n,count:o,dropoutFunc:this.dropoutFunc}));let i=this.dropoutMask,l=(ee,Y,ne)=>!Y||!Y[ne]?ee:W(Y[ne],ee),c=l(s,i,0),u=l(s,i,1),d=l(s,i,2),p=l(s,i,3);0Es(r),rate:this.recurrentDropout,training:n,count:o,dropoutFunc:this.dropoutFunc}));let h=this.recurrentDropoutMask,f=l(r,h,0),m=l(r,h,1),g=l(r,h,2),A=l(r,h,3),y=3,[x,b,w,k]=Sn(this.kernel.read(),o,y),[S,E,$,F]=this.useBias?Sn(this.bias.read(),o):[null,null,null,null];c=this.inputConv(c,x,S,this.padding),u=this.inputConv(u,b,E,this.padding),d=this.inputConv(d,w,$,this.padding),p=this.inputConv(p,k,F,this.padding);let[R,P,T,M]=Sn(this.recurrentKernel.read(),o,y);f=this.recurrentConv(f,R),m=this.recurrentConv(m,P),g=this.recurrentConv(g,T),A=this.recurrentConv(A,M);let U=this.recurrentActivation.apply(ie(c,f)),H=this.recurrentActivation.apply(ie(u,m)),z=ie(W(H,a),W(U,this.activation.apply(ie(d,g)))),X=W(this.recurrentActivation.apply(ie(p,A)),this.activation.apply(z));return[X,X,z]})}getConfig(){let{units:e,...t}=super.getConfig(),n={filters:this.filters,kernelSize:this.kernelSize,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,strides:this.strides};return{...t,...n}}inputConv(e,t,n,s){let r=ko(e,t,this.strides,s||"valid",this.dataFormat==="channelsFirst"?"NCHW":"NHWC",this.dilationRate);return n?hr(r,n,this.dataFormat):r}recurrentConv(e,t){return ko(e,t,1,"same",this.dataFormat==="channelsFirst"?"NCHW":"NHWC")}};Zf.className="ConvLSTM2DCell";le.registerClass(Zf);var AA=class extends pk{constructor(e){let t=new Zf(e);super({...e,cell:t})}static fromConfig(e,t){return new e(t)}};AA.className="ConvLSTM2D";le.registerClass(AA);var Yf=class extends nt{constructor(e){super(e);this.rate=Math.max(Math.min(e.rate,1),0),this.noiseShape=e.noiseShape,this.seed=e.seed,this.supportsMasking=!0}getNoiseShape(e){if(this.noiseShape==null)return this.noiseShape;let t=e.shape,n=[];for(let s=0;s{this.invokeCallHook(e,t);let n=Ve(e);if(0rw(n,this.rate,r,this.seed),()=>n,s)}return e})}getConfig(){let e={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},t=super.getConfig();return Object.assign(e,t),e}dispose(){return super.dispose()}};Yf.className="Dropout";le.registerClass(Yf);var yA=class extends Yf{constructor(e){super(e);this.inputSpec=[{ndim:3}]}getNoiseShape(e){let t=e.shape;return[t[0],1,t[2]]}};yA.className="SpatialDropout1D";le.registerClass(yA);var xA=class extends nt{constructor(e){super(e);if(this.activation=null,this.useBias=!0,this.kernel=null,this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.batchInputShape==null&&e.inputShape==null&&e.inputDim!=null){let t=null;e.batchSize!=null&&(t=e.batchSize),this.batchInputShape=[t,e.inputDim]}this.units=e.units,xn(this.units,"units"),this.activation=$o(e.activation),e.useBias!=null&&(this.useBias=e.useBias),this.kernelInitializer=$t(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=$t(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=un(e.kernelConstraint),this.biasConstraint=un(e.biasConstraint),this.kernelRegularizer=Dt(e.kernelRegularizer),this.biasRegularizer=Dt(e.biasRegularizer),this.activityRegularizer=Dt(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){e=mt(e);let t=e[e.length-1];this.kernel==null&&(this.kernel=this.addWeight("kernel",[t,this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint))),this.inputSpec=[{minNDim:2,axes:{[-1]:t}}],this.built=!0}computeOutputShape(e){e=mt(e);let t=e.slice();return t[t.length-1]=this.units,t}call(e,t){return j(()=>{this.invokeCallHook(e,t);let n=Ve(e),s=qv(this.activation.getClassName()),r;return s!=null?r=Dr(n,this.kernel.read(),s,this.bias?this.bias.read():null):(r=Dr(n,this.kernel.read()),this.bias!=null&&(r=hr(r,this.bias.read())),this.activation!=null&&(r=this.activation.apply(r))),r})}getConfig(){let e={units:this.units,activation:Ro(this.activation),useBias:this.useBias,kernelInitializer:Mt(this.kernelInitializer),biasInitializer:Mt(this.biasInitializer),kernelRegularizer:bt(this.kernelRegularizer),biasRegularizer:bt(this.biasRegularizer),activityRegularizer:bt(this.activityRegularizer),kernelConstraint:ln(this.kernelConstraint),biasConstraint:ln(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}};xA.className="Dense";le.registerClass(xA);var bA=class extends nt{constructor(e){e=e||{};super(e);this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=mt(e);for(let t of e.slice(1))if(t==null)throw new q(`The shape of the input to "Flatten" is not fully defined (got ${e.slice(1)}). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.`);return[e[0],To(e,1)]}call(e,t){return j(()=>{this.invokeCallHook(e,t);let n=Ve(e);if(this.dataFormat==="channelsFirst"&&n.rank>1){let s=[0];for(let r=2;r{this.invokeCallHook(e,t);let n=Ve(e);return this.activation.apply(n)})}getConfig(){let e={activation:Ro(this.activation)},t=super.getConfig();return Object.assign(e,t),e}};vA.className="Activation";le.registerClass(vA);var wA=class extends nt{constructor(e){super(e);this.n=e.n,this.inputSpec=[{ndim:2}]}computeOutputShape(e){return[e[0],this.n,e[1]]}call(e,t){return j(()=>(e=Ve(e),tL(e,this.n)))}getConfig(){let e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}};wA.className="RepeatVector";le.registerClass(wA);var kA=class extends nt{constructor(e){super(e);this.targetShape=e.targetShape;for(let t=0;t{this.invokeCallHook(e,t);let n=Ve(e),s=n.shape,r=s.slice(0,1).concat(this.fixUnknownDimension(s.slice(1),this.targetShape));return G(n,r)})}getConfig(){let e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}};kA.className="Reshape";le.registerClass(kA);var IA=class extends nt{constructor(e){super(e);if(e.dims==null)throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if(!Array.isArray(e.dims))throw new Error(`Permute constructor requires \`dims\` to be an Array, but received ${e.dims} instead.`);let t=pr(1,e.dims.length+1);if(!v.arraysEqual(e.dims.slice().sort(),t))throw new Error("Invalid permutation `dims`: "+JSON.stringify(e.dims)+" `dims` must contain consecutive integers starting from 1.");this.dims=e.dims,this.dimsIncludingBatch=[0].concat(this.dims),this.inputSpec=[new Yt({ndim:this.dims.length+1})]}computeOutputShape(e){e=mt(e);let t=e.slice();return this.dims.forEach((n,s)=>{t[s+1]=e[n]}),t}call(e,t){return et(Ve(e),this.dimsIncludingBatch)}getConfig(){let e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}};IA.className="Permute";le.registerClass(IA);var SA=class extends nt{constructor(e){super(e==null?{}:e);this.supportsMasking=!0,e!=null?this.maskValue=e.maskValue==null?0:e.maskValue:this.maskValue=0}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={maskValue:this.maskValue};return Object.assign(t,e),t}computeMask(e,t){let n=Ve(e),s=-1;return Uh(Tu(n,this.maskValue),s)}call(e,t){return j(()=>{this.invokeCallHook(e,t);let n=Ve(e),s=-1,r=!0,a=Uh(Tu(n,this.maskValue),s,r);return W(n,he(a,n.dtype))})}};SA.className="Masking";le.registerClass(SA);var CA=class extends nt{constructor(e){super(e);if(this.embeddings=null,this.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",e.batchInputShape==null&&e.inputShape==null){let t=null;e.batchSize!=null&&(t=e.batchSize),e.inputLength==null?this.batchInputShape=[t,null]:this.batchInputShape=[t].concat(Ct(e.inputLength))}this.inputDim=e.inputDim,xn(this.inputDim,"inputDim"),this.outputDim=e.outputDim,xn(this.outputDim,"outputDim"),this.embeddingsInitializer=$t(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=Dt(e.embeddingsRegularizer),this.activityRegularizer=Dt(e.activityRegularizer),this.embeddingsConstraint=un(e.embeddingsConstraint),this.maskZero=e.maskZero,this.supportsMasking=e.maskZero,this.inputLength=e.inputLength}build(e){this.embeddings=this.addWeight("embeddings",[this.inputDim,this.outputDim],this.dtype,this.embeddingsInitializer,this.embeddingsRegularizer,!0,this.embeddingsConstraint),this.built=!0}warnOnIncompatibleInputShape(e){}computeMask(e,t){return j(()=>this.maskZero?(e=Ve(e),Tu(e,tt(e))):null)}computeOutputShape(e){if(e=mt(e),this.inputLength==null)return[...e,this.outputDim];let t=Ct(this.inputLength);if(t.length!==e.length-1)throw new q(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let n=0;for(let s=0;s{this.invokeCallHook(e,t);let n=Ve(e);n.dtype!=="int32"&&(n=vf(n,"int32"));let s=sw(this.embeddings.read(),G(n,[n.size]));return G(s,mt(this.computeOutputShape(n.shape)))})}getConfig(){let e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:Mt(this.embeddingsInitializer),embeddingsRegularizer:bt(this.embeddingsRegularizer),activityRegularizer:bt(this.activityRegularizer),embeddingsConstraint:ln(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}};CA.className="Embedding";le.registerClass(CA);var cl=class extends nt{constructor(e){super(e||{});this.supportsMasking=!0}mergeFunction(e){throw new Be}computeElementwiseOpOutputShape(e,t){if(e==null||t==null)return null;if(e.length1)throw new q(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(e)}.`);let n=e[0]==null?null:e[0].slice(1);for(let r=1;rr.length);e.indexOf(null)===-1&&Co(s).length===1?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return j(()=>{if(e=e,this.reshapeRequired){let n=[],s=e.map(r=>r.rank);if(s.indexOf(null)===-1){let r=No(s);for(let a of e){let o=a.rank;for(let i=0;i1){let c=pr(1,l).concat([0]);n.push(et(i,c)),r=!0}else n.push(i)}let a=this.mergeFunction(n),o=a.rank;if(r){if(o==null){let i=a.shape,l=i.length,c=i[l-1],u=[c].concat(i.slice(0,i.length-1));a=G(et(G(a,[-1,c]),[1,0]),u)}else if(o>1){let i=[o-1].concat(pr(0,o-1));a=et(a,i)}}return a}}else return this.mergeFunction(e)})}computeOutputShape(e){e=e;let t;e[0]==null?t=null:t=e[0].slice(1);for(let s=1;s{if(t==null)return null;if(!Array.isArray(t))throw new q("`mask` should be an Array");if(!Array.isArray(e))throw new q("`inputs` should be an Array");if(t.length!==e.length)throw new q(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${e.length} vs ${t.length})`);if(t.every(s=>s==null))return null;t=t.map(s=>s==null?s:Kt(s,0));let n=t[0];for(let s=1;s{let t=e[0].clone();for(let n=1;n{let t=e[0].clone();for(let n=1;n{let t=e[0].clone();for(let n=1;n{let t=e[0];for(let n=1;n{let t=e[0];for(let n=1;n1)throw new q("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return j(()=>w1(e,this.axis))}computeOutputShape(e){if(!(Array.isArray(e)&&Array.isArray(e[0])))throw new q("A `Concatenate` layer should be called on a list of inputs.");let t=e,n=t[0].slice(),s=this.axis<0?n.length+this.axis:this.axis;for(let r of t.slice(1)){if(n[s]==null||r[s]==null){n[s]=null;break}n[s]+=r[s]}return n}computeMask(e,t){if(t==null)return null;if(!Array.isArray(t))throw new q("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new q("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new q(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return j(()=>{let n=!0;if(t.forEach(a=>{if(a!=null){n=!1;return}}),n)return null;let s=[];for(let a=0;a3||t.shape.length>3)throw new Be("batchDot is not implemented for tensors of 4D or higher rank yet");if(v.assert(e.shape.length>=2,()=>`batchDot requires the rank of x to be >= 2, but got ${e.shape.length}`),v.assert(e.shape.length>=2,()=>`batchDot requires the rank of y to be >= 2, but got ${t.shape.length}`),typeof n=="number"&&(n=[n,n]),e.dtype==="complex64"||t.dtype==="complex64")throw new Be("batchDot is not implemented for complex64-type Tensors yet.");let s=e.shape.length,r=t.shape.length;n==null&&(n=[s-1,r-2]);let a=n;return j(()=>{let o;if(s>r){o=s-r;let l=[];for(let c=0;cs){o=r-s;let l=[];for(let c=0;c0){let l;s>r?l=s+r-3:l=s-1;let c=[];for(let u=l;u"A `Dot` layer should be called on a list of exactly 2 inputs.");let t=e[0],n=e[1];if(t.length>3||n.length>3)throw new Be("Dot layer does not support tensors of 4D or higher rank yet.");let s=this.interpretAxes(t,n);if(t[s[0]]!==n[s[1]])throw new q(`Dimension incompatibility: ${t[s[0]]} !== ${n[s[1]]}`)}mergeFunction(e){if(e.length!==2)throw new q(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);let t=e[0],n=e[1],s;return Array.isArray(this.axes)?s=this.axes.map((r,a)=>Pd(r,e[a].shape.length)):s=[Pd(this.axes,t.shape.length),Pd(this.axes,n.shape.length)],this.normalize&&(t=Of(t,s[0]),n=Of(n,s[1])),zB(t,n,s)}interpretAxes(e,t){let n;return Array.isArray(this.axes)?n=this.axes:n=[Pd(this.axes,e.length),Pd(this.axes,t.length)],n}computeOutputShape(e){v.assert(Array.isArray(e)&&e.length===2&&Array.isArray(e[0])&&Array.isArray(e[1]),()=>"A `Dot` layer should be called on a list of exactly 2 inputs.");let t=e[0].slice(),n=e[1].slice();if(t.length>3||n.length>3)throw new Be("Dot layer does not support tensors of 4D or higher rank yet.");let s=this.interpretAxes(t,n);t.splice(s[0],1),n.splice(s[1],1),n.splice(0,1);let r=t.concat(n);return r.length===1&&r.push(1),r}computeMask(e,t){return null}getConfig(){let e={axes:this.axes,normalize:this.normalize},t=super.getConfig();return Object.assign(e,t),e}};_A.className="Dot";le.registerClass(_A);var PA=class extends nt{constructor(e){super(e);this.supportsMasking=!0,this.stddev=e.stddev}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={stddev:this.stddev};return Object.assign(t,e),t}call(e,t){return j(()=>{this.invokeCallHook(e,t);let n=Ve(e);return Sd(()=>ie(kf(n.shape,0,this.stddev),n),()=>n,t.training||!1)})}};PA.className="GaussianNoise";le.registerClass(PA);var FA=class extends nt{constructor(e){super(e);this.supportsMasking=!0,this.rate=e.rate}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return j(()=>{this.invokeCallHook(e,t);let n=Ve(e);return this.rate>0&&this.rate<1?Sd(()=>{let r=Math.sqrt(this.rate/(1-this.rate));return W(n,kf(n.shape,1,r))},()=>n,t.training||!1):n})}};FA.className="GaussianDropout";le.registerClass(FA);var OA=class extends nt{constructor(e){super(e);this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||Ve(e).shape}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return j(()=>{if(this.rate<1&&this.rate>0){let n=this._getNoiseShape(e);return Sd(()=>{let r=Ve(e),a=1.6732632423543772,o=1.0507009873554805,i=-a*o,l=Yi(Nu(n),this.rate);l=vf(l,"float32");let c=((1-this.rate)*(1+this.rate*i**2))**-.5,u=-c*i*this.rate,d=ie(W(r,l),W(ie(l,-1),i));return ie(W(d,c),u)},()=>Ve(e),t.training||!1)}return e})}};OA.className="AlphaDropout";le.registerClass(OA);function Fd(e,t,n,s,r,a=.001){let o;if(e.rank===2)o=N3(e,t,n,s,r,a);else if(e.rank===3)o=E3(e,t,n,s,r,a);else if(e.rank===4)o=R3(e,t,n,s,r,a);else throw new Be(`batchNormalization is not implemented for array of rank ${e.rank} yet`);return o}function LB(e,t,n,s,r=.001){return j(()=>{let a=tf(e,s),o=a.mean,i=a.variance;return[Fd(e,o,i,n,t,r),o,i]})}function BB(e,t,n,s,r=.001){return j(()=>{let a=tf(e,s),o=a.mean,i=a.variance,l=[];for(let f of pr(0,e.rank))s.indexOf(f)!==-1?l.push(1):l.push(e.shape[f]);let c=G(o,l),u=G(i,l),d=t==null?null:G(t,l),p=n==null?null:G(n,l);return[Fd(e,c,u,p,d,r),o,i]})}function WB(e,t,n,s,r=.001){return v.arraysEqual(s.slice().sort(),pr(0,e.rank-1))?LB(e,t,n,s,r):BB(e,t,n,s,r)}var MA=class extends nt{constructor(e){e==null&&(e={});super(e);this.supportsMasking=!0,this.axis=e.axis==null?-1:e.axis,this.momentum=e.momentum==null?.99:e.momentum,this.epsilon=e.epsilon==null?.001:e.epsilon,this.center=e.center==null?!0:e.center,this.scale=e.scale==null?!0:e.scale,this.betaInitializer=$t(e.betaInitializer||"zeros"),this.gammaInitializer=$t(e.gammaInitializer||"ones"),this.movingMeanInitializer=$t(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=$t(e.movingVarianceInitializer||"ones"),this.betaConstraint=un(e.betaConstraint),this.gammaConstraint=un(e.gammaConstraint),this.betaRegularizer=Dt(e.betaRegularizer),this.gammaRegularizer=Dt(e.gammaRegularizer)}build(e){e=mt(e);let t=this.axis>=0?this.axis:this.axis+e.length,n=e[t];if(n==null)throw new q(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new Yt({ndim:e.length,axes:{[t]:n}})];let s=[n];this.scale&&(this.gamma=this.addWeight("gamma",s,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",s,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",s,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",s,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(e,t){return j(()=>{let n=t.training==null?!1:t.training,s=Ve(e),r=s.shape,a=r.length,o=pr(0,a),i=this.axis>=0?this.axis:this.axis+a;o.splice(i,1);let l=nl(1,a);l[i]=r[i];let c=o.slice();c.sort();let u=!v.arraysEqual(c,pr(0,a).slice(0,a-1)),d=()=>{if(u){let A=G(this.movingMean.read(),l),y=G(this.movingVariance.read(),l),x=this.center?G(this.beta.read(),l):null,b=this.scale?G(this.gamma.read(),l):null;return Fd(s,A,y,x,b,this.epsilon)}else return Fd(s,this.movingMean.read(),this.movingVariance.read(),this.beta==null?null:this.beta.read(),this.gamma==null?null:this.gamma.read(),this.epsilon)};if(!n)return d();let[p,h,f]=WB(s,this.gamma.read(),this.beta.read(),o,this.epsilon),m=(A,y,x)=>{j(()=>{let b=1-x,w=A.read(),k=W(xe(w,y),b);A.write(xe(w,k))})};return(()=>{m(this.movingMean,h,this.momentum),m(this.movingVariance,f,this.momentum)})(),p})}getConfig(){let e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Mt(this.betaInitializer),gammaInitializer:Mt(this.gammaInitializer),movingMeanInitializer:Mt(this.movingMeanInitializer),movingVarianceInitializer:Mt(this.movingVarianceInitializer),betaRegularizer:bt(this.betaRegularizer),gammaRegularizer:bt(this.gammaRegularizer),betaConstraint:ln(this.betaConstraint),gammaConstraint:ln(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}};MA.className="BatchNormalization";le.registerClass(MA);var zA=class extends nt{constructor(e){e==null&&(e={});super(e);if(this.axis=e.axis==null?-1:e.axis,typeof this.axis=="number"){if(!Number.isInteger(this.axis))throw new Error(`Expected axis to be an integer, but received ${this.axis}`)}else if(Array.isArray(this.axis)){for(let t of this.axis)if(!Number.isInteger(t))throw new Error(`Expected axis to be an array of integers, but received ${JSON.stringify(this.axis)}`)}else throw new Error(`Expected axis to be an integer or an array of integers, but received ${JSON.stringify(this.axis)}`);this.epsilon=e.epsilon==null?.001:e.epsilon,this.center=e.center==null?!0:e.center,this.scale=e.scale==null?!0:e.scale,this.betaInitializer=$t(e.betaInitializer||"zeros"),this.gammaInitializer=$t(e.gammaInitializer||"ones"),this.betaRegularizer=Dt(e.betaRegularizer),this.gammaRegularizer=Dt(e.gammaRegularizer),this.supportsMasking=!0}build(e){e=mt(e);let t=e.length;typeof this.axis=="number"&&(this.axis=[this.axis]);for(let r=0;r=t)throw new Error(`Invalid axis: ${r}`);if(this.axis.length!==Co(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);let n=this.axis.map(r=>e[r]),s=!0;this.scale?this.gamma=this.addWeight("gamma",n,"float32",this.gammaInitializer,this.gammaRegularizer,s):this.gamma=null,this.center?this.beta=this.addWeight("beta",n,"float32",this.betaInitializer,this.betaRegularizer,s):this.beta=null,this.built=!0}call(e,t){let n=Ve(e),s=n.shape,r=s.length;return j(()=>{let a=!0,{mean:o,variance:i}=tf(n,this.axis,a),l=nl(1,r);for(let f of this.axis)l[f]=s[f];let c=f=>f!=null&&f.shape.length!==r?G(f,l):f,u=c(this.gamma.read()),d=c(this.beta.read()),p=[],h=[];for(let f=0;f{if(e.rank!==4)throw new q(`temporalPadding expects input tensor to be 4-D, but received a ${e.rank}-D tensor.`);if(t==null&&(t=[[1,1],[1,1]]),t.length!==2||t[0].length!==2||t[1].length!==2)throw new q("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(n==null&&(n=cr()),n!=="channelsLast"&&n!=="channelsFirst")throw new q(`Unknown data format: ${n}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let s;return n==="channelsFirst"?s=[[0,0],[0,0],t[0],t[1]]:s=[[0,0],t[0],t[1],[0,0]],qs(e,s)})}var LA=class extends nt{constructor(e){e==null&&(e={});super(e);if(this.dataFormat=e.dataFormat==null?cr():e.dataFormat,e.padding==null)this.padding=[[1,1],[1,1]];else if(typeof e.padding=="number")this.padding=[[e.padding,e.padding],[e.padding,e.padding]];else{if(e.padding=e.padding,e.padding.length!==2)throw new q(`ZeroPadding2D expects padding to be a length-2 array, but received a length-${e.padding.length} array.`);let t,n;if(typeof e.padding[0]=="number")t=[e.padding[0],e.padding[0]],n=[e.padding[1],e.padding[1]];else{if(e.padding=e.padding,e.padding[0].length!==2)throw new q(`ZeroPadding2D expects height padding to be a length-2 array, but received a length-${e.padding[0].length} array.`);if(t=e.padding[0],e.padding[1].length!==2)throw new q(`ZeroPadding2D expects width padding to be a length-2 array, but received a length-${e.padding[1].length} array.`);n=e.padding[1]}this.padding=[t,n]}this.inputSpec=[new Yt({ndim:4})]}computeOutputShape(e){e=mt(e);let t,n;return this.dataFormat==="channelsFirst"?(e[2]!=null&&e[2]>=0?t=e[2]+this.padding[0][0]+this.padding[0][1]:t=null,e[3]!=null&&e[3]>=0?n=e[3]+this.padding[1][0]+this.padding[1][1]:n=null,[e[0],e[1],t,n]):(e[1]!=null&&e[1]>=0?t=e[1]+this.padding[0][0]+this.padding[0][1]:t=null,e[2]!=null&&e[2]>=0?n=e[2]+this.padding[1][0]+this.padding[1][1]:n=null,[e[0],t,n,e[3]])}call(e,t){return j(()=>VB(Ve(e),this.padding,this.dataFormat))}getConfig(){let e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};LA.className="ZeroPadding2D";le.registerClass(LA);function Jf(e,t,n,s,r,a){return j(()=>{jt(r),Yv(a),$s(s),n==null&&(n=[1,1]),s==null&&(s="valid"),r==null&&(r=cr()),a==null&&(a="max"),e=aA(e,r);let o,i=s==="same"?"same":"valid";return a==="max"?o=Qh(e,t,n,i):o=Hh(e,t,n,i),r==="channelsFirst"&&(o=et(o,[0,3,1,2])),o})}function hk(e,t,n,s,r,a){return j(()=>{jt(r),Yv(a),$s(s),n==null&&(n=[1,1,1]),s==null&&(s="valid"),r==null&&(r=cr()),a==null&&(a="max"),e=sk(e,r);let o,i=s==="same"?"same":"valid";return a==="max"?o=G2(e,t,n,i):o=R2(e,t,n,i),r==="channelsFirst"&&(o=et(o,[0,4,1,2,3])),o})}var fk=class extends nt{constructor(e){e.poolSize==null&&(e.poolSize=2);super(e);if(typeof e.poolSize=="number")this.poolSize=[e.poolSize];else if(Array.isArray(e.poolSize)&&e.poolSize.length===1&&typeof e.poolSize[0]=="number")this.poolSize=e.poolSize;else throw new q(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);if(xn(this.poolSize,"poolSize"),e.strides==null)this.strides=this.poolSize;else if(typeof e.strides=="number")this.strides=[e.strides];else if(Array.isArray(e.strides)&&e.strides.length===1&&typeof e.strides[0]=="number")this.strides=e.strides;else throw new q(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);xn(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,$s(this.padding),this.inputSpec=[new Yt({ndim:3})]}computeOutputShape(e){e=mt(e);let t=gr(e[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return j(()=>{this.invokeCallHook(e,t),e=kd(Ve(e),2);let n=this.poolingFunction(Ve(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return pt(n,[2])})}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}},BA=class extends fk{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return jt(r),$s(s),Jf(e,t,n,s,r,"max")}};BA.className="MaxPooling1D";le.registerClass(BA);var WA=class extends fk{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return jt(r),$s(s),Jf(e,t,n,s,r,"avg")}};WA.className="AveragePooling1D";le.registerClass(WA);var mk=class extends nt{constructor(e){e.poolSize==null&&(e.poolSize=[2,2]);super(e);if(this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],e.strides==null)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==2)throw new q(`If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides];xn(this.poolSize,"poolSize"),xn(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,jt(this.dataFormat),$s(this.padding),this.inputSpec=[new Yt({ndim:4})]}computeOutputShape(e){e=mt(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2];return t=gr(t,this.poolSize[0],this.padding,this.strides[0]),n=gr(n,this.poolSize[1],this.padding,this.strides[1]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,n]:[e[0],t,n,e[3]]}call(e,t){return j(()=>(this.invokeCallHook(e,t),this.poolingFunction(Ve(e),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},VA=class extends mk{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return jt(r),$s(s),Jf(e,t,n,s,r,"max")}};VA.className="MaxPooling2D";le.registerClass(VA);var UA=class extends mk{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return jt(r),$s(s),Jf(e,t,n,s,r,"avg")}};UA.className="AveragePooling2D";le.registerClass(UA);var gk=class extends nt{constructor(e){e.poolSize==null&&(e.poolSize=[2,2,2]);super(e);if(this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize,e.poolSize],e.strides==null)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==3)throw new q(`If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides,e.strides];xn(this.poolSize,"poolSize"),xn(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,jt(this.dataFormat),$s(this.padding),this.inputSpec=[new Yt({ndim:5})]}computeOutputShape(e){e=mt(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2],s=this.dataFormat==="channelsFirst"?e[4]:e[3];return t=gr(t,this.poolSize[0],this.padding,this.strides[0]),n=gr(n,this.poolSize[1],this.padding,this.strides[1]),s=gr(s,this.poolSize[2],this.padding,this.strides[2]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,n,s]:[e[0],t,n,s,e[4]]}call(e,t){return j(()=>(this.invokeCallHook(e,t),this.poolingFunction(Ve(e),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},GA=class extends gk{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return jt(r),$s(s),hk(e,t,n,s,r,"max")}};GA.className="MaxPooling3D";le.registerClass(GA);var HA=class extends gk{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return jt(r),$s(s),hk(e,t,n,s,r,"avg")}};HA.className="AveragePooling3D";le.registerClass(HA);var Ak=class extends nt{constructor(e){super(e);this.inputSpec=[new Yt({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new Be}},jA=class extends Ak{constructor(e){super(e||{})}call(e,t){return j(()=>{let n=Ve(e);return Wt(n,1)})}};jA.className="GlobalAveragePooling1D";le.registerClass(jA);var qA=class extends Ak{constructor(e){super(e||{})}call(e,t){return j(()=>{let n=Ve(e);return rs(n,1)})}};qA.className="GlobalMaxPooling1D";le.registerClass(qA);var yk=class extends nt{constructor(e){super(e);this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,jt(this.dataFormat),this.inputSpec=[new Yt({ndim:4})]}computeOutputShape(e){return e=e,this.dataFormat==="channelsLast"?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new Be}getConfig(){let e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},XA=class extends yk{call(e,t){return j(()=>{let n=Ve(e);return this.dataFormat==="channelsLast"?Wt(n,[1,2]):Wt(n,[2,3])})}};XA.className="GlobalAveragePooling2D";le.registerClass(XA);var KA=class extends yk{call(e,t){return j(()=>{let n=Ve(e);return this.dataFormat==="channelsLast"?rs(n,[1,2]):rs(n,[2,3])})}};KA.className="GlobalMaxPooling2D";le.registerClass(KA);var xk=class extends nt{constructor(e){super(e);this.layer=e.layer}build(e){this.built=!0}get trainable(){return this.layer!=null?this.layer.trainable:!1}set trainable(e){this.layer!=null&&(this.layer.trainable=e)}get trainableWeights(){return this.layer.trainableWeights}get nonTrainableWeights(){return this.layer.nonTrainableWeights}get updates(){return this.layer._updates}get losses(){return this.layer.losses}getWeights(){return this.layer.getWeights()}setWeights(e){this.layer.setWeights(e)}getConfig(){let e={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},t=super.getConfig();return Object.assign(e,t),e}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.layer!=null&&this.layer.setFastWeightInitDuringBuild(e)}static fromConfig(e,t,n={}){let s=t.layer,r=mr(s,n);delete t.layer;let a={layer:r};return Object.assign(a,t),new e(a)}},ZA=class extends xk{constructor(e){super(e);this.supportsMasking=!0}build(e){if(e=mt(e),e.length<3)throw new q(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(e)}`);this.inputSpec=[{shape:e}];let t=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(t),this.layer.built=!0),super.build(e)}computeOutputShape(e){e=mt(e);let t=[e[0]].concat(e.slice(2)),n=this.layer.computeOutputShape(t),s=e[1];return[n[0],s].concat(n.slice(1))}call(e,t){return j(()=>(e=Ve(e),ck((a,o)=>[Ve(this.layer.call(a,t)),[]],e,[],!1,null,null,!1,!0)[1]))}};ZA.className="TimeDistributed";le.registerClass(ZA);function UB(e){rl(Zz,"BidirectionalMergeMode",e)}var GB="concat",YA=class extends xk{constructor(e){super(e);let t=e.layer.getConfig(),n={};n.className=e.layer.getClassName(),n.config=t,this.forwardLayer=mr(n),t.goBackwards=t.goBackwards!==!0;let s={};if(s.className=e.layer.getClassName(),s.config=t,this.backwardLayer=mr(s),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=e.mergeMode===void 0?GB:e.mergeMode,UB(this.mergeMode),e.weights)throw new Be("weights support is not implemented for Bidirectional layer yet.");this._stateful=e.layer.stateful,this.returnSequences=e.layer.returnSequences,this.returnState=e.layer.returnState,this.supportsMasking=!0,this._trainable=!0,this.inputSpec=e.layer.inputSpec,this.numConstants=null}get trainable(){return this._trainable}set trainable(e){this._trainable=e,this.forwardLayer!=null&&(this.forwardLayer.trainable=e),this.backwardLayer!=null&&(this.backwardLayer.trainable=e)}getWeights(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())}setWeights(e){let t=e.length,n=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,n)),this.backwardLayer.setWeights(e.slice(n))}computeOutputShape(e){let t=this.forwardLayer.computeOutputShape(e);Array.isArray(t)&&Array.isArray(t[0])||(t=[t]),t=t;let n,s,r;return this.returnState&&(r=t.slice(1)),n=t[0],n=n,this.mergeMode==="concat"?(n[n.length-1]*=2,s=[n]):this.mergeMode==null?s=[n,n.slice()]:s=[n],this.returnState?this.mergeMode==null?s.concat(r).concat(r.slice()):[n].concat(r).concat(r.slice()):os(s)}apply(e,t){let n=t==null?null:t.initialState,s=t==null?null:t.constants;t==null&&(t={});let r=uk(e,n,s,this.numConstants);if(e=r.inputs,n=r.initialState,s=r.constants,Array.isArray(e)&&(n=e.slice(1),e=e[0]),(n==null||n.length===0)&&s==null)return super.apply(e,t);let a=[],o=[];if(n!=null){let l=n.length;if(l%2>0)throw new q("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");t.initialState=n,a.push(...n);let c=n.map(u=>new Yt({shape:u.shape}));this.forwardLayer.stateSpec=c.slice(0,l/2),this.backwardLayer.stateSpec=c.slice(l/2),o.push(...c)}if(s!=null)throw new Be("Support for constants in Bidirectional layers is not implemented yet.");let i=a[0]instanceof fr;for(let l of a)if(l instanceof fr!==i)throw new q("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(i){let l=[e].concat(a),c=this.inputSpec.concat(o),u=this.inputSpec;this.inputSpec=c;let d=super.apply(l,t);return this.inputSpec=u,d}else return super.apply(e,t)}call(e,t){return j(()=>{let n=t.initialState,s,r;if(n==null)s=this.forwardLayer.call(e,t),r=this.backwardLayer.call(e,t);else{let i=n.slice(0,n.length/2),l=n.slice(n.length/2);s=this.forwardLayer.call(e,Object.assign(t,{initialState:i})),r=this.backwardLayer.call(e,Object.assign(t,{initialState:l}))}let a;this.returnState&&(Array.isArray(s)&&(a=s.slice(1).concat(r.slice(1))),s=s[0],r=r[0]),this.returnSequences&&(r=Rs(r,1));let o;return this.mergeMode==="concat"?o=w1([s,r]):this.mergeMode==="sum"?o=ie(s,r):this.mergeMode==="ave"?o=W(.5,ie(s,r)):this.mergeMode==="mul"?o=W(s,r):this.mergeMode==null&&(o=[s,r]),this.returnState?this.mergeMode==null?o.concat(a):[o].concat(a):o})}resetStates(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(e){al(this.forwardLayer.name,()=>{this.forwardLayer.build(e)}),al(this.backwardLayer.name,()=>{this.backwardLayer.build(e)}),this.built=!0}computeMask(e,t){Array.isArray(t)&&(t=t[0]);let n;if(this.returnSequences?this.mergeMode==null?n=[t,t]:n=t:this.mergeMode==null?n=[null,null]:n=null,this.returnState){let r=this.forwardLayer.states.map(a=>null);return Array.isArray(n)?n.concat(r).concat(r):[n].concat(r).concat(r)}else return n}get trainableWeights(){return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights)}get nonTrainableWeights(){return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights)}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.forwardLayer!=null&&this.forwardLayer.setFastWeightInitDuringBuild(e),this.backwardLayer!=null&&this.backwardLayer.setFastWeightInitDuringBuild(e)}getConfig(){let e={mergeMode:this.mergeMode},t=super.getConfig();return Object.assign(e,t),e}static fromConfig(e,t){let n=mr(t.layer);if(delete t.layer,t.numConstants!=null)throw new Be("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");let s=t;return s.layer=n,new e(s)}};YA.className="Bidirectional";le.registerClass(YA);function HB(e){return new Fu(e)}function jB(e){return new nA(e)}function qB(e){return new Q1(e)}function XB(e){return new eA(e)}function KB(e){return new tA(e)}function ZB(e){return new rA(e)}function YB(e){return new sA(e)}function JB(e){return new cA(e)}function QB(e){return new Hf(e)}function eW(e){return new iA(e)}function tW(e){return new jf(e)}function nW(e){return new lA(e)}function sW(e){return new uA(e)}function rW(e){return new dA(e)}function aW(e){return new pA(e)}function oW(e){return new hA(e)}function iW(e){return new vA(e)}function lW(e){return new xA(e)}function uW(e){return new Yf(e)}function cW(e){return new yA(e)}function dW(e){return new bA(e)}function pW(e){return new wA(e)}function hW(e){return new kA(e)}function fW(e){return new IA(e)}function mW(e){return new CA(e)}function gW(e){return new TA(e)}function AW(e){return new EA(e)}function yW(e){return new DA(e)}function xW(e){return new RA(e)}function bW(e){return new $A(e)}function vW(e){return new NA(e)}function wW(e){return new _A(e)}function kW(e){return new MA(e)}function IW(e){return new zA(e)}function SW(e){return new LA(e)}function JA(e){return new WA(e)}function CW(e){return JA(e)}function TW(e){return JA(e)}function QA(e){return new UA(e)}function NW(e){return QA(e)}function EW(e){return QA(e)}function ey(e){return new HA(e)}function RW(e){return ey(e)}function $W(e){return ey(e)}function DW(e){return new jA(e)}function _W(e){return new XA(e)}function bk(e){return new qA(e)}function vk(e){return new KA(e)}function wk(e){return new BA(e)}function kk(e){return new VA(e)}function PW(e){return new GA(e)}function FW(e){return new mA(e)}function OW(e){return new Xf(e)}function MW(e){return new gA(e)}function zW(e){return new _d(e)}function LW(e){return new fA(e)}function BW(e){return new qf(e)}function WW(e){return new AA(e)}function VW(e){return new Zf(e)}function UW(e){return new sa(e)}function GW(e){return new Kf(e)}function HW(e){return new YA(e)}function jW(e){return new ZA(e)}var qW=bk,XW=vk,KW=wk,ZW=kk;function YW(e){return new PA(e)}function JW(e){return new FA(e)}function QW(e){return new OA(e)}function eV(e){return new SA(e)}var Ik={};ze(Ik,{MAPE:()=>dV,MSE:()=>fV,binaryAccuracy:()=>tV,binaryCrossentropy:()=>nV,categoricalAccuracy:()=>rV,categoricalCrossentropy:()=>aV,cosineProximity:()=>lV,mape:()=>pV,meanAbsoluteError:()=>uV,meanAbsolutePercentageError:()=>cV,meanSquaredError:()=>hV,mse:()=>mV,precision:()=>oV,recall:()=>iV,sparseCategoricalAccuracy:()=>sV});function tV(e,t){return z1(e,t)}function nV(e,t){return ww(e,t)}function sV(e,t){return kw(e,t)}function rV(e,t){return L1(e,t)}function aV(e,t){return B1(e,t)}function oV(e,t){return vw(e,t)}function iV(e,t){return HL(e,t)}function lV(e,t){return O1(e,t)}function uV(e,t){return Mf(e,t)}function cV(e,t){return Mu(e,t)}function dV(e,t){return Mu(e,t)}function pV(e,t){return Mu(e,t)}function hV(e,t){return il(e,t)}function fV(e,t){return il(e,t)}function mV(e,t){return il(e,t)}var Sk={};ze(Sk,{modelFromJSON:()=>SB});var Ck={};ze(Ck,{l1:()=>AV,l1l2:()=>gV,l2:()=>yV});function gV(e){return new Rd(e)}function AV(e){return _B(e)}function yV(e){return PB(e)}var Tk=class extends Ou{constructor(){super(...arguments);this.model=null}setModel(e){if(!(e instanceof na))throw new Error("model must be a LayersModel, not some other Container");this.model=e}};function Qf(e,t){return et}var Ek=class extends Tk{constructor(e){super();if(e==null&&(e={}),e.restoreBestWeights)throw new Be("restoreBestWeights = True is not implemented in EarlyStopping yet.");this.monitor=e.monitor||"val_loss",this.minDelta=Math.abs(e.minDelta||0),this.patience=e.patience||0,this.verbose=e.verbose||0,this.mode=e.mode||"auto",this.baseline=e.baseline,["auto","min","max"].indexOf(this.mode)===-1&&(console.warn(`EarlyStopping mode '${this.mode}' is invalid. Falling back to mode 'auto'.`),this.mode="auto"),this.mode==="min"?this.monitorFunc=Qf:this.mode==="max"?this.monitorFunc=Nk:this.monitor.indexOf("acc")!==-1?this.monitorFunc=Nk:this.monitorFunc=Qf,this.monitorFunc===Qf&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,this.baseline!=null?this.best=this.baseline:this.best=this.monitorFunc===Qf?1/0:-1/0}async onEpochEnd(e,t){await Eo(t);let n=this.getMonitorValue(t);n!=null&&(this.monitorFunc(n-this.minDelta,this.best)?(this.best=n,this.wait=0):(this.wait++,this.wait>=this.patience&&(this.stoppedEpoch=e,this.model.stopTraining=!0)))}async onTrainEnd(e){this.stoppedEpoch>0&&this.verbose&&console.log(`Epoch ${this.stoppedEpoch}: early stopping.`)}getMonitorValue(e){e==null&&(e={});let t=e[this.monitor];return t==null&&console.warn(`Metric for EarlyStopping ${this.monitor} is not available. Available metrics are: ${Object.keys(e)}`),t}};function xV(e){return new Ek(e)}var bV={earlyStopping:xV},Ar;(function(e){e[e.DT_INVALID=0]="DT_INVALID",e[e.DT_FLOAT=1]="DT_FLOAT",e[e.DT_DOUBLE=2]="DT_DOUBLE",e[e.DT_INT32=3]="DT_INT32",e[e.DT_UINT8=4]="DT_UINT8",e[e.DT_INT16=5]="DT_INT16",e[e.DT_INT8=6]="DT_INT8",e[e.DT_STRING=7]="DT_STRING",e[e.DT_COMPLEX64=8]="DT_COMPLEX64",e[e.DT_INT64=9]="DT_INT64",e[e.DT_BOOL=10]="DT_BOOL",e[e.DT_QINT8=11]="DT_QINT8",e[e.DT_QUINT8=12]="DT_QUINT8",e[e.DT_QINT32=13]="DT_QINT32",e[e.DT_BFLOAT16=14]="DT_BFLOAT16",e[e.DT_FLOAT_REF=101]="DT_FLOAT_REF",e[e.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",e[e.DT_INT32_REF=103]="DT_INT32_REF",e[e.DT_UINT8_REF=104]="DT_UINT8_REF",e[e.DT_INT16_REF=105]="DT_INT16_REF",e[e.DT_INT8_REF=106]="DT_INT8_REF",e[e.DT_STRING_REF=107]="DT_STRING_REF",e[e.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",e[e.DT_INT64_REF=109]="DT_INT64_REF",e[e.DT_BOOL_REF=110]="DT_BOOL_REF",e[e.DT_QINT8_REF=111]="DT_QINT8_REF",e[e.DT_QUINT8_REF=112]="DT_QUINT8_REF",e[e.DT_QINT32_REF=113]="DT_QINT32_REF",e[e.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF"})(Ar||(Ar={}));var Rk;(function(e){let t;(function(n){n[n.LEGACY=0]="LEGACY",n[n.V1=1]="V1",n[n.V2=2]="V2"})(t=e.CheckpointFormatVersion||(e.CheckpointFormatVersion={}))})(Rk||(Rk={}));var ty={};function vV(e,t){let n={tfOpName:e,category:"custom",inputs:[],attrs:[],customExecutor:t};ty[e]=n}function $k(e){return ty[e]}function wV(e){delete ty[e]}function I(e,t,n,s,r){let a=t.inputParams[e];if(a&&a.inputIndexStart!==void 0){let i=a.inputIndexStart,l=a.inputIndexEnd===0?void 0:a.inputIndexEnd===void 0?i+1:a.inputIndexEnd;if(a.type==="tensor")return Un(t.inputNames[a.inputIndexStart],n,s,r);if(a.type==="tensors")return t.inputNames.slice(i,l).map(p=>Un(p,n,s,r));let c=Un(t.inputNames.slice(i)[0],n,s,r),u=c.dataSync();return a.type==="number"?u[0]:v.toNestedArray(c.shape,u)}let o=t.attrParams[e];return o&&o.value}function Un(e,t,n,s){let[r,a]=As(e);if(s!=null){let i=s.getHashTableHandleByName(r);if(i!=null)return i}let o=n.currentContextIds.find(i=>!!t[em(r,i)]);return o!==void 0?t[em(r,o)][a]:void 0}function kV(e,t,n){return t[em(e,n.currentContextId)]}function ra(e,t){let[n,s,r]=As(e);return[em(n,t&&t.currentContextId),s,r]}function em(e,t){return t?`${e}-${t}`:e}function As(e){let t=e.split(":");if(t.length===1)return[e,0,void 0];let n=t[0],s=t.length===3?t[1]:void 0,r=Number(t[t.length-1]);return[n,r,s]}function tm(e,t,n){let s=I("pad",e,t,n);if(s==="explicit"){s=I("explicitPaddings",e,t,n);let r=[[0,0],[0,0],[0,0],[0,0]];for(let a=0;a<4;a++)r[a][0]=s[a*2],r[a][1]=s[a*2+1];return r}return s}function aa(e){return e.kept?e:or(e)}var Dk={};ze(Dk,{json:()=>IV});var IV=[{tfOpName:"Add",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddV2",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddN",category:"arithmetic",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"BiasAdd",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"Sub",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"RealDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Div",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"DivNoNan",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mul",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Maximum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Minimum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Pow",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SquaredDifference",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorMod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],_k={};ze(_k,{json:()=>SV});var SV=[{tfOpName:"Abs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan2",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ceil",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ClipByValue",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"clipValueMin",type:"number"},{start:2,name:"clipValueMax",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Complex",category:"basic_math",inputs:[{start:0,name:"real",type:"tensor"},{start:1,name:"imag",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ComplexAbs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Elu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Exp",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Floor",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Imag",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Neg",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Real",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Prelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"alpha",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu6",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Selu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sigmoid",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Rsqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Square",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sign",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Round",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Expm1",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log1p",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Reciprocal",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Softplus",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Erf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Prod",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axes",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LeakyRelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"alpha",name:"alpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsNan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],Pk={};ze(Pk,{json:()=>CV});var CV=[{tfOpName:"EmptyTensorList",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"maxNumElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"LoopCond",category:"control",inputs:[{start:0,name:"pred",type:"tensor"}]},{tfOpName:"Switch",category:"control",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"pred",type:"tensor"}]},{tfOpName:"Merge",category:"control",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"Enter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"frame_name",name:"frameName",type:"string"},{tfName:"is_constant",name:"isConstant",type:"bool"}]},{tfOpName:"Exit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NextIteration",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayV3",category:"control",inputs:[{start:0,name:"size",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"dynamic_size",name:"dynamicSize",type:"bool"},{tfName:"clear_after_read",name:"clearAfterRead",type:"bool"},{tfName:"identical_element_shapes",name:"identicalElementShapes",type:"bool"},{tfName:"tensor_array_name",name:"name",type:"string"}]},{tfOpName:"TensorArrayWriteV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayReadV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayGatherV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"}]},{tfOpName:"TensorArrayScatterV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArrayConcatV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape_except0",name:"elementShapeExcept0",type:"shape",notSupported:!0}]},{tfOpName:"TensorArraySplitV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"tensor",type:"tensor"},{start:2,name:"lengths",type:"number[]"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArraySizeV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}]},{tfOpName:"TensorArrayCloseV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"}]},{tfOpName:"StatelessIf",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"If",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"StatelessWhile",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"While",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"TensorListScatter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListScatterV2",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"},{start:3,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGather",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListSetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListReserve",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListFromTensor",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListStack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"},{tfName:"num_elements",name:"numElements",type:"dtype"}]},{tfOpName:"TensorListSplit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"},{start:2,name:"lengths",type:"number[]"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcat",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPopBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPushBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]}],Fk={};ze(Fk,{json:()=>TV});var TV=[{tfOpName:"AvgPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[],notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPoolWithArgmax",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"include_batch_in_index",name:"includeBatchInIndex",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AvgPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Conv1D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"stride",name:"stride",type:"number"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NWC"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"dilation",name:"dilation",type:"number",defaultValue:1}]},{tfOpName:"Conv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"useCudnnOnGpu",name:"useCudnnOnGpu",type:"bool"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"_FusedConv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"use_cudnn_on_gpu",name:"useCudnnOnGpu",type:"bool",defaultValue:!0},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number"}]},{tfOpName:"Conv2DBackpropInput",category:"convolution",inputs:[{start:2,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:0,name:"outputShape",type:"number[]"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]",notSupported:!0}]},{tfOpName:"DepthwiseConv2d",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"DepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"FusedDepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]}]},{tfOpName:"Conv3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"Dilation2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"rates",name:"dilations",type:"number[]"},{tfName:"padding",name:"pad",type:"string"}]}],Ok={};ze(Ok,{json:()=>NV});var NV=[{tfOpName:"Fill",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"},{start:1,name:"value",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"LinSpace",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"num",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"OneHot",category:"creation",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"depth",type:"number"},{start:2,name:"onValue",type:"number",defaultValue:1},{start:3,name:"offValue",type:"number",defaultValue:0}],attrs:[{tfName:"axis",name:"axis",type:"number",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ones",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"OnesLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"RandomUniform",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number",defaultValue:0},{tfName:"maxval",name:"maxval",type:"number",defaultValue:1},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Range",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"step",type:"number",defaultValue:0}],attrs:[{tfName:"Tidx",name:"dtype",type:"dtype"}]},{tfOpName:"TruncatedNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"means",name:"mean",type:"number",defaultValue:0},{tfName:"stddev",name:"stdDev",type:"number",defaultValue:1},{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Zeros",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"ZerosLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Multinomial",category:"creation",inputs:[{start:0,name:"logits",type:"tensor"},{start:1,name:"numSamples",type:"number"}],attrs:[{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number"},{tfName:"T",name:"dtype",type:"dtype"},{tfName:"output_dtype",name:"output_dtype",type:"dtype"}]}],Mk={};ze(Mk,{json:()=>EV});var EV=[{tfOpName:"NonMaxSuppressionV2",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV3",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV4",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"T_threshold",name:"threshold",type:"dtype",notSupported:!0},{tfName:"pad_to_max_output_size",name:"padToMaxOutputSize",type:"bool"}]},{tfOpName:"NonMaxSuppressionV5",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"},{start:5,name:"softNmsSigma",type:"number"}]},{tfOpName:"Where",category:"dynamic",inputs:[{start:0,name:"condition",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ListDiff",category:"dynamic",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],zk={};ze(zk,{json:()=>RV});var RV=[{tfOpName:"TopKV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"k",type:"number"}],attrs:[{tfName:"sorted",name:"sorted",type:"bool"}]},{tfOpName:"Unique",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"UniqueV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]}],Lk={};ze(Lk,{json:()=>$V});var $V=[{tfOpName:"PlaceholderWithDefault",category:"graph",inputs:[{start:0,name:"default",type:"tensor"}],attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Placeholder",category:"graph",attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Const",category:"graph"},{tfOpName:"Identity",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IdentityN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Snapshot",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Rank",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Size",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Shape",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"ShapeN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Print",category:"graph",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"data",type:"tensors"}],attrs:[{tfName:"message",name:"message",type:"string"},{tfName:"first_n",name:"firstN",type:"number",notSupported:!0},{tfName:"summarize",name:"summarize",type:"number",defaultValue:3}]},{tfOpName:"NoOp",category:"graph",inputs:[]},{tfOpName:"StopGradient",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"FakeQuantWithMinMaxVars",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"min",name:"min",type:"number"},{tfName:"max",name:"max",type:"number"}]}],Bk={};ze(Bk,{json:()=>DV});var DV=[{tfOpName:"HashTable",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"HashTableV2",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"LookupTableImport",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableImportV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFind",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFindV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableSize",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]},{tfOpName:"LookupTableSizeV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]}],Wk={};ze(Wk,{json:()=>_V});var _V=[{tfOpName:"ResizeBilinear",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ResizeNearestNeighbor",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"CropAndResize",category:"image",inputs:[{start:0,name:"image",type:"tensor"},{start:1,name:"boxes",type:"tensor"},{start:2,name:"boxInd",type:"tensor"},{start:3,name:"cropSize",type:"number[]"}],attrs:[{tfName:"method",name:"method",type:"string"},{tfName:"extrapolation_value",name:"extrapolationValue",type:"number"}]}],Vk={};ze(Vk,{json:()=>PV});var PV=[{tfOpName:"Equal",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NotEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Greater",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"GreaterEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Less",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LessEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalAnd",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalNot",category:"logical",inputs:[{start:0,name:"a",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalOr",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Select",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SelectV2",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],Uk={};ze(Uk,{json:()=>FV});var FV=[{tfOpName:"_FusedMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMulV2",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Transpose",category:"matrices",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"perm",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Einsum",category:"matrices",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"equation",name:"equation",type:"string"},{tfName:"N",name:"n",type:"number",defaultValue:2},{tfName:"T",name:"dtype",type:"dtype"}]}],Gk={};ze(Gk,{json:()=>OV});var OV=[{tfOpName:"FusedBatchNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV2",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV3",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"LRN",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"depth_radius",name:"radius",type:"number",defaultValue:5},{tfName:"bias",name:"bias",type:"number",defaultValue:1},{tfName:"alpha",name:"alpha",type:"number",defaultValue:1},{tfName:"beta",name:"beta",type:"number",defaultValue:.5}]},{tfOpName:"Softmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"LogSoftmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"SparseToDense",category:"normalization",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!0,notSupported:!0}]}],Hk={};ze(Hk,{json:()=>MV});var MV=[{tfOpName:"Bincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}]},{tfOpName:"DenseBincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}],attrs:[{tfName:"binary_output",name:"binaryOutput",type:"bool"}]},{tfOpName:"Max",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Mean",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Min",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Sum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"All",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Any",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"ArgMax",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"ArgMin",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Prod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Cumsum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]}],jk={};ze(jk,{json:()=>zV});var zV=[{tfOpName:"ConcatV2",category:"slice_join",inputs:[{start:0,end:-1,name:"tensors",type:"tensors"},{start:-1,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"Concat",category:"slice_join",inputs:[{start:1,end:0,name:"tensors",type:"tensors"},{start:0,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"GatherV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"axis",type:"number",defaultValue:0}],attrs:[{tfName:"batch_dims",name:"batchDims",type:"number",defaultValue:0}]},{tfOpName:"Gather",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",notSupported:!0}]},{tfOpName:"Reverse",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"dims",type:"bool[]"}]},{tfOpName:"ReverseV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}]},{tfOpName:"Slice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"size",type:"number[]"}]},{tfOpName:"StridedSlice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"end",type:"number[]"},{start:3,name:"strides",type:"number[]"}],attrs:[{tfName:"begin_mask",name:"beginMask",type:"number",defaultValue:0},{tfName:"end_mask",name:"endMask",type:"number",defaultValue:0},{tfName:"new_axis_mask",name:"newAxisMask",type:"number",defaultValue:0},{tfName:"ellipsis_mask",name:"ellipsisMask",type:"number",defaultValue:0},{tfName:"shrink_axis_mask",name:"shrinkAxisMask",type:"number",defaultValue:0}]},{tfOpName:"Pack",category:"slice_join",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Unpack",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"num",name:"num",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Tile",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"reps",type:"number[]"}]},{tfOpName:"Split",category:"slice_join",inputs:[{start:0,name:"axis",type:"number",defaultValue:0},{start:1,name:"x",type:"tensor"}],attrs:[{tfName:"num_split",name:"numOrSizeSplits",type:"number",defaultValue:1}]},{tfOpName:"SplitV",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"numOrSizeSplits",type:"number[]"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"ScatterNd",category:"slice_join",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"shape",type:"number[]"}]},{tfOpName:"GatherNd",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}]},{tfOpName:"SparseToDense",category:"slice_join",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!1,notSupported:!0}]}],qk={};ze(qk,{json:()=>LV});var LV=[{tfOpName:"SparseFillEmptyRows",category:"sparse",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"denseShape",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}]},{tfOpName:"SparseReshape",category:"sparse",inputs:[{start:0,name:"inputIndices",type:"tensor"},{start:1,name:"inputShape",type:"tensor"},{start:2,name:"newShape",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SparseSegmentMean",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]},{tfOpName:"SparseSegmentSum",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]}],Xk={};ze(Xk,{json:()=>BV});var BV=[{tfOpName:"FFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"RFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]},{tfOpName:"IRFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]}],Kk={};ze(Kk,{json:()=>WV});var WV=[{tfOpName:"StringNGrams",category:"string",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"dataSplits",type:"tensor"}],attrs:[{tfName:"separator",name:"separator",type:"string"},{tfName:"ngram_widths",name:"nGramWidths",type:"number[]"},{tfName:"left_pad",name:"leftPad",type:"string"},{tfName:"right_pad",name:"rightPad",type:"string"},{tfName:"pad_width",name:"padWidth",type:"number"},{tfName:"preserve_short_sequences",name:"preserveShortSequences",type:"bool"}],outputs:["ngrams","ngrams_splits"]},{tfOpName:"StringSplit",category:"string",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"delimiter",type:"tensor"}],attrs:[{tfName:"skip_empty",name:"skipEmpty",type:"bool"}],outputs:["indices","values","shape"]},{tfOpName:"StringToHashBucketFast",category:"string",inputs:[{start:0,name:"input",type:"tensor"}],attrs:[{tfName:"num_buckets",name:"numBuckets",type:"number"}]}],Zk={};ze(Zk,{json:()=>VV});var VV=[{tfOpName:"Cast",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"SrcT",name:"sdtype",type:"dtype",notSupported:!0},{tfName:"DstT",name:"dtype",type:"dtype"}]},{tfOpName:"ExpandDims",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"MirrorPad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"mode",name:"mode",type:"string"}]},{tfOpName:"Pad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"constant_value",name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"PadV2",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"},{start:2,name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"Reshape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"Squeeze",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"axis",tfDeprecatedName:"squeeze_dims",name:"axis",type:"number[]"}]},{tfOpName:"SpaceToBatchND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"paddings",type:"number[]"}]},{tfOpName:"BatchToSpaceND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"crops",type:"number[]"}]},{tfOpName:"DepthToSpace",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"block_size",name:"blockSize",type:"number"},{tfName:"data_format",name:"dataFormat",type:"string"}]},{tfOpName:"BroadcastTo",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}],attrs:[]},{tfOpName:"BroadcastArgs",category:"transformation",inputs:[{start:0,name:"s0",type:"tensor"},{start:1,name:"s1",type:"tensor"}],attrs:[]}],Yk=class{static get Instance(){return this._instance||(this._instance=new this)}constructor(){let e=[Dk,_k,Pk,Fk,Ok,Mk,zk,Lk,Bk,Wk,Vk,Uk,Gk,Hk,jk,qk,Xk,Kk,Zk],t=[].concat(...e.map(n=>n.json));this.opMappers=t.reduce((n,s)=>(n[s.tfOpName]=s,n),{})}transformGraph(e,t={}){let n=e.node,s=[],r=[],a=[],o=n.reduce((f,m)=>(f[m.name]=this.mapNode(m),m.op.startsWith("Placeholder")?s.push(f[m.name]):m.op==="Const"?r.push(f[m.name]):(m.input==null||m.input.length===0)&&a.push(f[m.name]),f),{}),i=[],l=[],c={},u={};t!=null&&(c=this.mapSignatureEntries(t.inputs),u=this.mapSignatureEntries(t.outputs));let d=Object.keys(o);d.forEach(f=>{let m=o[f];m.inputNames.forEach((g,A)=>{let[y,,x]=ra(g),b=o[y];if(b.outputs!=null){let w=b.outputs.indexOf(x);if(w!==-1){let k=`${y}:${w}`;m.inputNames[A]=k}}m.inputs.push(b),b.children.push(m)})}),Object.keys(u).length===0?d.forEach(f=>{let m=o[f];m.children.length===0&&l.push(m)}):Object.keys(u).forEach(f=>{let[m]=ra(f),g=o[m];g!=null&&(g.signatureKey=u[f],l.push(g))}),Object.keys(c).length>0?Object.keys(c).forEach(f=>{let[m]=ra(f),g=o[m];g&&(g.signatureKey=c[f],i.push(g))}):i=s;let p={};e.library!=null&&e.library.function!=null&&(p=e.library.function.reduce((f,m)=>(f[m.signature.name]=this.mapFunction(m),f),{}));let h={nodes:o,inputs:i,outputs:l,weights:r,placeholders:s,signature:t,functions:p};return a.length>0&&(h.initNodes=a),h}mapSignatureEntries(e){return Object.keys(e||{}).reduce((t,n)=>(t[e[n].name]=n,t),{})}mapNode(e){let t=$k(e.op)||this.opMappers[e.op]||{};e.attr==null&&(e.attr={});let n={name:e.name,op:e.op,category:t.category,inputNames:(e.input||[]).map(s=>s.startsWith("^")?s.substr(1):s),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:e.attr,outputs:t.outputs};return t.inputs!=null&&(n.inputParams=t.inputs.reduce((s,r)=>(s[r.name]={type:r.type,inputIndexStart:r.start,inputIndexEnd:r.end},s),{})),t.attrs!=null&&(n.attrParams=t.attrs.reduce((s,r)=>{let a=r.type,o;switch(r.type){case"string":o=ny(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=ny(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"string[]":o=cy(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=cy(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"number":o=ry(e.attr,r.tfName,r.defaultValue||0),o===void 0&&!!r.tfDeprecatedName&&(o=ry(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"number[]":o=uy(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=uy(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"bool":o=sy(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=sy(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"bool[]":o=py(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=py(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"shape":o=ly(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=ly(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"shape[]":o=dy(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=dy(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"dtype":o=oy(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=oy(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"dtype[]":o=iy(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=iy(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"func":o=Qk(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=Qk(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error(`Unsupported param type: ${r.type} for op: ${e.op}`)}return s[r.name]={value:o,type:a},s},{})),n}mapFunction(e){let t=e.nodeDef,n=[],s=[],r={};t!=null&&(r=t.reduce((u,d)=>(u[d.name]=this.mapNode(d),d.op==="Const"&&s.push(u[d.name]),u),{}));let a=[],o=[];e.signature.inputArg.forEach(u=>{let[d]=ra(u.name),p={name:d,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:ay(u.type),type:"dtype"}},children:[]};p.signatureKey=u.name,a.push(p),r[d]=p}),Object.keys(r).forEach(u=>{let d=r[u];d.inputNames.forEach((p,h)=>{let[f,,m]=ra(p),g=r[f];if(g.outputs!=null){let A=g.outputs.indexOf(m);if(A!==-1){let y=`${f}:${A}`;d.inputNames[h]=y}}d.inputs.push(g),g.children.push(d)})});let l=e.ret;e.signature.outputArg.forEach(u=>{let[d,p]=ra(l[u.name]),h=r[d];h!=null&&(h.defaultOutput=p,o.push(h))});let c=this.mapArgsToSignature(e);return{nodes:r,inputs:a,outputs:o,weights:s,placeholders:n,signature:c}}mapArgsToSignature(e){return{methodName:e.signature.name,inputs:e.signature.inputArg.reduce((t,n)=>(t[n.name]=this.mapArgToTensorInfo(n),t),{}),outputs:e.signature.outputArg.reduce((t,n)=>(t[n.name]=this.mapArgToTensorInfo(n,e.ret),t),{})}}mapArgToTensorInfo(e,t){let n=e.name;return t!=null&&(n=t[n]),{name:n,dtype:e.type}}};function UV(e){let t=K().global;if(typeof t.atob!="undefined")return t.atob(e);if(typeof Buffer!="undefined")return new Buffer(e,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}function Jk(e,t){let n=Array.isArray(e)?String.fromCharCode.apply(null,e):UV(e);return t?n:n.toLowerCase()}function ny(e,t,n,s=!1){let r=e[t];return r!=null?Jk(r.s,s):n}function sy(e,t,n){let s=e[t];return s?s.b:n}function ry(e,t,n){let s=e[t]||{},r=s.i!=null?s.i:s.f!=null?s.f:n;return typeof r=="number"?r:parseInt(r,10)}function ay(e){switch(typeof e=="string"&&(e=Ar[e]),e){case Ar.DT_FLOAT:return"float32";case Ar.DT_INT32:case Ar.DT_INT64:case Ar.DT_INT8:case Ar.DT_UINT8:return"int32";case Ar.DT_BOOL:return"bool";case Ar.DT_DOUBLE:return"float32";case Ar.DT_STRING:return"string";default:return null}}function Qk(e,t,n){let s=e[t];return s&&s.func?s.func.name:n}function oy(e,t,n){let s=e[t];return s&&s.type?ay(s.type):n}function iy(e,t,n){let s=e[t];return s&&s.list&&s.list.type?s.list.type.map(r=>ay(r)):n}function e7(e){if(!e.unknownRank)return e.dim!=null?e.dim.map(t=>typeof t.size=="number"?t.size:parseInt(t.size,10)):[]}function ly(e,t,n){let s=e[t];return s&&s.shape?e7(s.shape):n}function uy(e,t,n){let s=e[t];return s?((s.list.f&&s.list.f.length?s.list.f:s.list.i)||[]).map(r=>typeof r=="number"?r:parseInt(r,10)):n}function cy(e,t,n,s=!1){let r=e[t];return r&&r.list&&r.list.s?r.list.s.map(a=>Jk(a,s)):n}function dy(e,t,n){let s=e[t];return s&&s.list&&s.list.shape?s.list.shape.map(r=>e7(r)):n}function py(e,t,n){let s=e[t];return s&&s.list&&s.list.b?s.list.b:n}var GV=class{constructor(e,t,n){this.node=e,this.tensorMap=t,this.context=n,this.inputs=[],this.attrs={},this.inputs=e.inputNames.map(s=>this.getInput(s)),e.rawAttrs!=null&&(this.attrs=Object.keys(e.rawAttrs).reduce((s,r)=>(s[r]=this.getAttr(r),s),{}))}getInput(e){return Un(e,this.tensorMap,this.context)}getAttr(e,t){let n=this.node.rawAttrs[e];if(n.tensor!=null)return Un(e,this.tensorMap,this.context);if(n.i!=null||n.f!=null)return ry(this.node.rawAttrs,e,t);if(n.s!=null)return ny(this.node.rawAttrs,e,t);if(n.b!=null)return sy(this.node.rawAttrs,e,t);if(n.shape!=null)return ly(this.node.rawAttrs,e,t);if(n.type!=null)return oy(this.node.rawAttrs,e,t);if(n.list!=null){if(n.list.i!=null||n.list.f!=null)return uy(this.node.rawAttrs,e,t);if(n.list.s!=null)return cy(this.node.rawAttrs,e,t);if(n.list.shape!=null)return dy(this.node.rawAttrs,e,t);if(n.list.b!=null)return py(this.node.rawAttrs,e,t);if(n.list.type!=null)return iy(this.node.rawAttrs,e,t)}return t}},HV=(e,t,n)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[ie(I("a",e,t,n),I("b",e,t,n))];case"AddN":return[Vh(I("tensors",e,t,n))];case"FloorMod":case"Mod":return[tv(I("a",e,t,n),I("b",e,t,n))];case"Mul":return[W(I("a",e,t,n),I("b",e,t,n))];case"RealDiv":case"Div":return[fe(I("a",e,t,n),I("b",e,t,n))];case"DivNoNan":return[W3(I("a",e,t,n),I("b",e,t,n))];case"FloorDiv":return[C2(I("a",e,t,n),I("b",e,t,n))];case"Sub":return[xe(I("a",e,t,n),I("b",e,t,n))];case"Minimum":return[hd(I("a",e,t,n),I("b",e,t,n))];case"Maximum":return[Yr(I("a",e,t,n),I("b",e,t,n))];case"Pow":return[Io(I("a",e,t,n),I("b",e,t,n))];case"SquaredDifference":return[n1(I("a",e,t,n),I("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},jV=(e,t,n)=>{switch(e.op){case"Abs":case"ComplexAbs":return[rn(I("x",e,t,n))];case"Acos":return[A3(I("x",e,t,n))];case"Acosh":return[y3(I("x",e,t,n))];case"Asin":return[b3(I("x",e,t,n))];case"Asinh":return[v3(I("x",e,t,n))];case"Atan":return[w3(I("x",e,t,n))];case"Atan2":return[k3(I("x",e,t,n),I("y",e,t,n))];case"Atanh":return[I3(I("x",e,t,n))];case"Ceil":return[D3(I("x",e,t,n))];case"Complex":return[yo(I("real",e,t,n),I("imag",e,t,n))];case"Cos":return[qh(I("x",e,t,n))];case"Cosh":return[O2(I("x",e,t,n))];case"Elu":return[dd(I("x",e,t,n))];case"Erf":return[U3(I("x",e,t,n))];case"Exp":return[Ts(I("x",e,t,n))];case"Expm1":return[G3(I("x",e,t,n))];case"Floor":return[pd(I("x",e,t,n))];case"Log":return[Ns(I("x",e,t,n))];case"Log1p":return[Zh(I("x",e,t,n))];case"Imag":return[Xh(I("x",e,t,n))];case"Neg":return[Ot(I("x",e,t,n))];case"Reciprocal":return[rv(I("x",e,t,n))];case"Real":return[fd(I("x",e,t,n))];case"Relu":return[Rr(I("x",e,t,n))];case"Round":return[K2(I("x",e,t,n))];case"Selu":return[Y2(I("x",e,t,n))];case"Sigmoid":return[hs(I("x",e,t,n))];case"Sin":return[J2(I("x",e,t,n))];case"Sign":return[iv(I("x",e,t,n))];case"Sinh":return[Q2(I("x",e,t,n))];case"Softplus":return[Cu(I("x",e,t,n))];case"Sqrt":return[_n(I("x",e,t,n))];case"Square":return[xt(I("x",e,t,n))];case"Tanh":return[vu(I("x",e,t,n))];case"Tan":return[uv(I("x",e,t,n))];case"ClipByValue":return[fs(I("x",e,t,n),I("clipValueMin",e,t,n),I("clipValueMax",e,t,n))];case"Relu6":return[X2(I("x",e,t,n))];case"Rsqrt":return[Z2(Un(e.inputNames[0],t,n))];case"Prod":return[H2(I("x",e,t,n),I("axes",e,t,n))];case"LeakyRelu":return[Kh(I("x",e,t,n),I("alpha",e,t,n))];case"Prelu":return[sf(I("x",e,t,n),I("alpha",e,t,n))];case"IsNan":return[H3(Un(e.inputNames[0],t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function Ys(e,t,n=""){if(!(typeof e=="number"||typeof t=="number")){v.assert(e.length===t.length,()=>n+` Shapes ${e} and ${t} must match`);for(let s=0;sn+` Shapes ${e} and ${t} must match`)}}}function t7(e){return!(typeof e=="number"||e.some(t=>t<0))}function Od(e,t,n){let s=hy(e,n),r=!t7(s);if(r&&t.length===0)throw new Error(`Tried to calculate elements of an empty list with non-fully-defined elementShape: ${s}`);if(r&&t.forEach(a=>{s=hy(a.shape,s)}),!t7(s))throw new Error(`Non-fully-defined elementShape: ${s}`);return s}function hy(e,t){if(typeof e=="number")return t;if(typeof t=="number")return e;if(e.length!==t.length)throw new Error(`Incompatible ranks during merge: ${e} vs. ${t}`);let n=[];for(let s=0;s=0&&a>=0&&r!==a)throw new Error(`Incompatible shape during merge: ${e} vs. ${t}`);n[s]=r>=0?r:a}return n}var qV=class{constructor(e,t,n,s,r,a,o){this.name=e,this.dtype=t,this.maxSize=n,this.elementShape=s,this.identicalElementShapes=r,this.dynamicSize=a,this.clearAfterRead=o,this.tensors=[],this.closed_=!1,this.idTensor=Ee(0),yn(this.idTensor)}get id(){return this.idTensor.id}get closed(){return this.closed_}clearAndClose(e){this.tensors.forEach(t=>{(e==null||!e.has(t.tensor.id))&&t.tensor.dispose()}),this.tensors=[],this.closed_=!0,this.idTensor.dispose()}size(){return this.tensors.length}read(e){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||e>=this.size())throw new Error(`Tried to read from index ${e}, but array size is: ${this.size()}`);let t=this.tensors[e];if(t.cleared)throw new Error(`TensorArray ${this.name}: Could not read index ${e} twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).`);return this.clearAfterRead&&(t.cleared=!0),t.read=!0,t.tensor}readMany(e){return e.map(t=>this.read(t))}write(e,t){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||!this.dynamicSize&&e>=this.maxSize)throw new Error(`Tried to write to index ${e}, but array is not resizeable and size is: ${this.maxSize}`);let n=this.tensors[e]||{};if(t.dtype!==this.dtype)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because the value dtype is ${t.dtype}, but TensorArray dtype is ${this.dtype}.`);if(this.size()===0&&(this.elementShape==null||this.elementShape.length===0)&&(this.elementShape=t.shape),Ys(this.elementShape,t.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${e}.`),n.read)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`);if(n.written)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`);n.tensor=t,yn(t),n.written=!0,this.tensors[e]=n}writeMany(e,t){if(e.length!==t.length)throw new Error(`TensorArray ${this.name}: could not write multiple tensors,because the index size: ${e.length} is not the same as tensors size: ${t.length}.`);e.forEach((n,s)=>this.write(n,t[s]))}gather(e,t){if(!!t&&t!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${t}`);if(e)e=e.slice(0,this.size());else{e=[];for(let s=0;s=this.maxSize)throw new Error(`Max index must be < array size (${n} vs. ${this.maxSize})`);this.writeMany(e,as(t,0))}split(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);let n=0,s=e.map(i=>(n+=i,n));if(n!==t.shape[0])throw new Error(`Expected sum of lengths to be equal to tensor.shape[0], but sum of lengths is ${n}, and tensor's shape is: ${t.shape}`);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${e.length}), and the TensorArray is not marked as dynamically resizeable`);let r=n===0?0:t.size/n,a=[];j(()=>{t=G(t,[1,n,r]);for(let i=0;i{if(n!==r.dtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${r.dtype}`);Ys(t,r.shape,"TensorList shape mismatch: "),yn(r)}),this.idTensor=Ee(0),this.maxNumElements=s,yn(this.idTensor)}get id(){return this.idTensor.id}copy(){return new Md([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(e){this.tensors.forEach(t=>{(e==null||!e.has(t.id))&&t.dispose()}),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(e,t,n=-1){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(n!==-1&&this.tensors.length!==n)throw new Error(`Operation expected a list with ${n} elements but got a list with ${this.tensors.length} elements.`);Ys(e,this.elementShape,"TensorList shape mismatch: ");let s=Od(this.elementShape,this.tensors,e);return j(()=>{let r=this.tensors.map(a=>G(a,s));return Pn(r,0)})}popBack(e,t){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(this.size()===0)throw new Error("Trying to pop from an empty list.");let n=Od(this.elementShape,this.tensors,e),s=this.tensors.pop();return Ys(s.shape,e,"TensorList shape mismatch: "),G(s,n)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(Ys(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");yn(e),this.tensors.push(e)}resize(e){if(e<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${e}`);if(this.maxNumElements!==-1&&e>this.maxNumElements)throw new Error(`TensorListResize input size ${e} is greater maxNumElement ${this.maxNumElements}.`);this.tensors.length=e}getItem(e,t,n){if(n!==this.elementDtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${this.elementDtype}`);if(e<0||e>this.tensors.length)throw new Error(`Trying to access element ${e} in a list with ${this.tensors.length} elements.`);if(this.tensors[e]==null)throw new Error(`element at index ${e} is null.`);Ys(this.tensors[e].shape,t,"TensorList shape mismatch: ");let s=Od(this.elementShape,this.tensors,t);return G(this.tensors[e],s)}setItem(e,t){if(t.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);if(e<0||this.maxNumElements!==-1&&e>=this.maxNumElements)throw new Error(`Trying to set element ${e} in a list with max ${this.maxNumElements} elements.`);Ys(this.elementShape,t.shape,"TensorList shape mismatch: "),yn(t),this.tensors[e]=t}gather(e,t,n){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);Ys(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size());let s=Od(this.elementShape,this.tensors,n);return e.length===0?Gt([],[0].concat(s)):j(()=>{let r=e.map(a=>G(this.tensors[a],s));return Pn(r,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);Ys(this.elementShape,t,"TensorList shape mismatch: ");let n=Od(this.elementShape,this.tensors,t);return this.size()===0?Gt([],[0].concat(n)):j(()=>{let s=this.tensors.map(r=>G(r,n));return It(s,0)})}};function XV(e,t,n){let s=e.dtype;if(e.shape.length<1)throw new Error(`Tensor must be at least a vector, but saw shape: ${e.shape}`);if(e.dtype!==n)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${n}`);let r=e.shape.slice(1);Ys(r,t,"TensorList shape mismatch: ");let a=as(e);return new Md(a,t,s)}function KV(e,t,n){return new Md([],e,t,n)}function ZV(e,t,n,s){if(t.length!==e.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${t.length} vs. ${e.shape[0]}`);let r=Math.max(...t);if(s!=null&&s!==-1&&r>=s)throw new Error(`Max index must be < array size (${r} vs. ${s})`);let a=new Md([],n,e.dtype,s),o=as(e,0);return t.forEach((i,l)=>{a.setItem(i,o[l])}),a}function YV(e,t,n){let s=0,r=t.map(u=>(s+=u,s));if(s!==e.shape[0])throw new Error(`Expected sum of lengths to be equal to tensor.shape[0], but sum of lengths is - ${s}, and tensor's shape is: ${e.shape}`);let a=e.shape.slice(1),o=hy(a,n),i=s===0?0:e.size/s,l=j(()=>{let u=[];e=G(e,[1,s,i]);for(let d=0;d{switch(e.op){case"If":case"StatelessIf":{let s=I("thenBranch",e,t,n),r=I("elseBranch",e,t,n),a=I("cond",e,t,n),o=I("args",e,t,n);return(await a.data())[0]?n.functionMap[s].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap):n.functionMap[r].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap)}case"While":case"StatelessWhile":{let s=I("body",e,t,n),r=I("cond",e,t,n),a=I("args",e,t,n),o=await n.functionMap[r].executeFunctionAsync(a,n.tensorArrayMap,n.tensorListMap),i=a.map(u=>u.id),l=await o[0].data();o.forEach(u=>{!u.kept&&i.indexOf(u.id)===-1&&u.dispose()});let c=a;for(;l[0];){let u=c;c=await n.functionMap[s].executeFunctionAsync(c,n.tensorArrayMap,n.tensorListMap);let d=c.map(h=>h.id);u.forEach(h=>{!h.kept&&i.indexOf(h.id)===-1&&d.indexOf(h.id)===-1&&h.dispose()});let p=await n.functionMap[r].executeFunctionAsync(c,n.tensorArrayMap,n.tensorListMap);l=await p[0].data(),p.forEach(h=>{!h.kept&&i.indexOf(h.id)===-1&&d.indexOf(h.id)===-1&&h.dispose()})}return c}case"LoopCond":{let s=I("pred",e,t,n);return[aa(s)]}case"Switch":{let s=I("pred",e,t,n),r=I("data",e,t,n);return r.kept||(r=aa(r)),(await s.data())[0]?[void 0,r]:[r,void 0]}case"Merge":{let s=e.inputNames.find(r=>Un(r,t,n)!==void 0);if(s){let r=Un(s,t,n);return[aa(r)]}return}case"Enter":{let s=I("frameName",e,t,n),r=I("tensor",e,t,n);return n.enterFrame(s),[aa(r)]}case"Exit":{let s=I("tensor",e,t,n);return n.exitFrame(),[aa(s)]}case"NextIteration":{let s=I("tensor",e,t,n);return n.nextIteration(),[aa(s)]}case"TensorArrayV3":{let s=I("size",e,t,n),r=I("dtype",e,t,n),a=I("elementShape",e,t,n),o=I("dynamicSize",e,t,n),i=I("clearAfterRead",e,t,n),l=I("identicalElementShapes",e,t,n),c=I("name",e,t,n),u=new qV(c,r,s,a,l,o,i);return n.addTensorArray(u),[u.idTensor,Ee(1)]}case"TensorArrayWriteV3":{let s=I("tensorArrayId",e,t,n),r=I("index",e,t,n),a=I("tensor",e,t,n),o=n.getTensorArray(s.id);return o.write(r,a),[o.idTensor]}case"TensorArrayReadV3":{let s=I("tensorArrayId",e,t,n),r=I("index",e,t,n);return[n.getTensorArray(s.id).read(r)]}case"TensorArrayGatherV3":{let s=I("tensorArrayId",e,t,n),r=I("indices",e,t,n),a=I("dtype",e,t,n);return[n.getTensorArray(s.id).gather(r,a)]}case"TensorArrayScatterV3":{let s=I("tensorArrayId",e,t,n),r=I("indices",e,t,n),a=I("tensor",e,t,n),o=n.getTensorArray(s.id);return o.scatter(r,a),[o.idTensor]}case"TensorArrayConcatV3":{let s=I("tensorArrayId",e,t,n),r=n.getTensorArray(s.id),a=I("dtype",e,t,n);return[r.concat(a)]}case"TensorArraySplitV3":{let s=I("tensorArrayId",e,t,n),r=I("tensor",e,t,n),a=I("lengths",e,t,n),o=n.getTensorArray(s.id);return o.split(a,r),[o.idTensor]}case"TensorArraySizeV3":{let s=I("tensorArrayId",e,t,n),r=n.getTensorArray(s.id);return[Ee(r.size(),"int32")]}case"TensorArrayCloseV3":{let s=I("tensorArrayId",e,t,n),r=n.getTensorArray(s.id);return r.clearAndClose(),[r.idTensor]}case"TensorListSetItem":{let s=I("tensorListId",e,t,n),r=I("index",e,t,n),a=I("tensor",e,t,n),o=n.getTensorList(s.id);return o.setItem(r,a),[o.idTensor]}case"TensorListGetItem":{let s=I("tensorListId",e,t,n),r=I("index",e,t,n),a=I("elementShape",e,t,n),o=I("elementDType",e,t,n);return[n.getTensorList(s.id).getItem(r,a,o)]}case"TensorListScatterV2":case"TensorListScatter":{let s=I("indices",e,t,n),r=I("tensor",e,t,n),a=I("elementShape",e,t,n),o=I("numElements",e,t,n),i=ZV(r,s,a,o);return n.addTensorList(i),[i.idTensor]}case"TensorListReserve":case"EmptyTensorList":{let s=I("elementShape",e,t,n),r=I("elementDType",e,t,n),a;e.op==="TensorListReserve"?a="numElements":a="maxNumElements";let o=I(a,e,t,n),i=KV(s,r,o);return n.addTensorList(i),[i.idTensor]}case"TensorListGather":{let s=I("tensorListId",e,t,n),r=I("indices",e,t,n),a=I("elementShape",e,t,n),o=I("elementDType",e,t,n);return[n.getTensorList(s.id).gather(r,o,a)]}case"TensorListStack":{let s=I("tensorListId",e,t,n),r=I("elementShape",e,t,n),a=I("elementDType",e,t,n),o=I("numElements",e,t,n);return[n.getTensorList(s.id).stack(r,a,o)]}case"TensorListFromTensor":{let s=I("tensor",e,t,n),r=I("elementShape",e,t,n),a=I("elementDType",e,t,n),o=XV(s,r,a);return n.addTensorList(o),[o.idTensor]}case"TensorListConcat":{let s=I("tensorListId",e,t,n),r=n.getTensorList(s.id),a=I("dtype",e,t,n),o=I("elementShape",e,t,n);return[r.concat(a,o)]}case"TensorListPushBack":{let s=I("tensorListId",e,t,n),r=I("tensor",e,t,n),a=n.getTensorList(s.id);return a.pushBack(r),[a.idTensor]}case"TensorListPopBack":{let s=I("tensorListId",e,t,n),r=I("elementShape",e,t,n),a=I("elementDType",e,t,n);return[n.getTensorList(s.id).popBack(r,a)]}case"TensorListSplit":{let s=I("tensor",e,t,n),r=I("elementShape",e,t,n),a=I("lengths",e,t,n),o=YV(s,a,r);return n.addTensorList(o),[o.idTensor]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};function n7(e,t,n){let[s,r]=I("fusedOps",e,t,n),a=s==="biasadd",o=!a,i=r==="prelu",l=s==="fusedbatchnorm",c=I("numArgs",e,t,n);if(a){if(i&&c!==2)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!i&&a&&c!==1)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.")}if(l)throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported");let u=I("strides",e,t,n),d=tm(e,t,n),p=I("dataFormat",e,t,n).toUpperCase(),h=I("dilations",e,t,n),[f,m]=I("args",e,t,n);o&&(m=f,f=void 0);let g=I("leakyreluAlpha",e,t,n);return{stride:u,pad:d,dataFormat:p,dilations:h,biasArg:f,preluArg:m,activationFunc:r,leakyreluAlpha:g}}var QV=(e,t,n)=>{switch(e.op){case"Conv1D":{let s=I("stride",e,t,n),r=I("pad",e,t,n),a=I("dataFormat",e,t,n).toUpperCase(),o=I("dilation",e,t,n);return[D2(I("x",e,t,n),I("filter",e,t,n),s,r,a,o)]}case"Conv2D":{let s=I("strides",e,t,n),r=tm(e,t,n),a=I("dataFormat",e,t,n).toUpperCase(),o=I("dilations",e,t,n);return[ko(I("x",e,t,n),I("filter",e,t,n),[s[1],s[2]],r,a,[o[1],o[2]])]}case"_FusedConv2D":{let{stride:s,pad:r,dataFormat:a,dilations:o,biasArg:i,preluArg:l,activationFunc:c,leakyreluAlpha:u}=n7(e,t,n);return[So.conv2d({x:I("x",e,t,n),filter:I("filter",e,t,n),strides:[s[1],s[2]],pad:r,dataFormat:a,dilations:[o[1],o[2]],bias:i,activation:c,preluActivationWeights:l,leakyreluAlpha:u})]}case"FusedDepthwiseConv2dNative":{let{stride:s,pad:r,dataFormat:a,dilations:o,biasArg:i,preluArg:l,activationFunc:c,leakyreluAlpha:u}=n7(e,t,n);return[So.depthwiseConv2d({x:I("x",e,t,n),filter:I("filter",e,t,n),strides:[s[1],s[2]],pad:r,dataFormat:a,dilations:[o[1],o[2]],bias:i,activation:c,preluActivationWeights:l,leakyreluAlpha:u})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{let s=I("outputShape",e,t,n),r=I("strides",e,t,n),a=tm(e,t,n);return[P2(I("x",e,t,n),I("filter",e,t,n),s,[r[1],r[2]],a)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{let s=I("strides",e,t,n),r=tm(e,t,n),a=I("dilations",e,t,n),o=I("dataFormat",e,t,n).toUpperCase();return[cd(I("input",e,t,n),I("filter",e,t,n),[s[1],s[2]],r,o,[a[1],a[2]])]}case"Conv3D":{let s=I("strides",e,t,n),r=I("pad",e,t,n),a=I("dataFormat",e,t,n).toUpperCase(),o=I("dilations",e,t,n);return[F2(I("x",e,t,n),I("filter",e,t,n),[s[1],s[2],s[3]],r,a,[o[1],o[2],o[3]])]}case"AvgPool":{let s=I("strides",e,t,n),r=I("pad",e,t,n),a=I("kernelSize",e,t,n);return[Hh(I("x",e,t,n),[a[1],a[2]],[s[1],s[2]],r)]}case"MaxPool":{let s=I("strides",e,t,n),r=I("pad",e,t,n),a=I("kernelSize",e,t,n);return[Qh(I("x",e,t,n),[a[1],a[2]],[s[1],s[2]],r)]}case"MaxPoolWithArgmax":{let s=I("strides",e,t,n),r=I("pad",e,t,n),a=I("kernelSize",e,t,n),o=I("includeBatchInIndex",e,t,n),{result:i,indexes:l}=Q3(I("x",e,t,n),[a[1],a[2]],[s[1],s[2]],r,o);return[i,l]}case"AvgPool3D":{let s=I("strides",e,t,n),r=I("pad",e,t,n),a=I("kernelSize",e,t,n);return[R2(I("x",e,t,n),[a[1],a[2],a[3]],[s[1],s[2],s[3]],r)]}case"MaxPool3D":{let s=I("strides",e,t,n),r=I("pad",e,t,n),a=I("kernelSize",e,t,n);return[G2(I("x",e,t,n),[a[1],a[2],a[3]],[s[1],s[2],s[3]],r)]}case"Dilation2D":{let s=I("strides",e,t,n),r=I("pad",e,t,n),a=I("dilations",e,t,n),o=s[1],i=s[2],l=a[1],c=a[2];return[B3(I("x",e,t,n),I("filter",e,t,n),[o,i],r,[l,c],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},eU=(e,t,n)=>{switch(e.op){case"Fill":{let s=I("shape",e,t,n),r=I("dtype",e,t,n),a=I("value",e,t,n);return[Iu(s,a,r)]}case"LinSpace":{let s=I("start",e,t,n),r=I("stop",e,t,n),a=I("num",e,t,n);return[j3(s,r,a)]}case"Multinomial":{let s=I("logits",e,t,n),r=I("numSamples",e,t,n),a=I("seed",e,t,n);return[nv(s,r,a)]}case"OneHot":{let s=I("indices",e,t,n),r=I("depth",e,t,n),a=I("onValue",e,t,n),o=I("offValue",e,t,n);return[id(s,r,a,o)]}case"Ones":return[gs(I("shape",e,t,n),I("dtype",e,t,n))];case"OnesLike":return[Es(I("x",e,t,n))];case"RandomUniform":return[Nu(I("shape",e,t,n),I("minval",e,t,n),I("maxval",e,t,n),I("dtype",e,t,n))];case"Range":{let s=I("start",e,t,n),r=I("stop",e,t,n),a=I("step",e,t,n);return[Eu(s,r,a,I("dtype",e,t,n))]}case"TruncatedNormal":{let s=I("shape",e,t,n),r=I("mean",e,t,n),a=I("stdDev",e,t,n),o=I("seed",e,t,n);return[lf(s,r,a,I("dtype",e,t,n),o)]}case"Zeros":return[Ht(I("shape",e,t,n),I("dtype",e,t,n))];case"ZerosLike":return[tt(I("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function fy(e,t,n){let s=I("boxes",e,t,n),r=I("scores",e,t,n),a=I("maxOutputSize",e,t,n),o=I("iouThreshold",e,t,n),i=I("scoreThreshold",e,t,n),l=I("softNmsSigma",e,t,n);return{boxes:s,scores:r,maxOutputSize:a,iouThreshold:o,scoreThreshold:i,softNmsSigma:l}}var tU=async(e,t,n)=>{switch(e.op){case"NonMaxSuppressionV5":{let{boxes:s,scores:r,maxOutputSize:a,iouThreshold:o,scoreThreshold:i,softNmsSigma:l}=fy(e,t,n),c=await $e.nonMaxSuppressionWithScoreAsync(s,r,a,o,i,l);return[c.selectedIndices,c.selectedScores]}case"NonMaxSuppressionV4":{let{boxes:s,scores:r,maxOutputSize:a,iouThreshold:o,scoreThreshold:i}=fy(e,t,n),l=I("padToMaxOutputSize",e,t,n),c=await $e.nonMaxSuppressionPaddedAsync(s,r,a,o,i,l);return[c.selectedIndices,c.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{let{boxes:s,scores:r,maxOutputSize:a,iouThreshold:o,scoreThreshold:i}=fy(e,t,n);return[await $e.nonMaxSuppressionAsync(s,r,a,o,i)]}case"Where":{let s=de(I("condition",e,t,n),"bool"),r=[await r1(s)];return s.dispose(),r}case"ListDiff":return ov(I("x",e,t,n),I("y",e,t,n));default:throw TypeError(`Node type ${e.op} is not implemented`)}},nU=(e,t,n)=>{switch(e.op){case"TopKV2":{let s=I("x",e,t,n),r=I("k",e,t,n),a=I("sorted",e,t,n),o=cv(s,r,a);return[o.values,o.indices]}case"Unique":{let s=I("x",e,t,n),r=s1(s);return[r.values,r.indices]}case"UniqueV2":{let s=I("x",e,t,n),r=I("axis",e,t,n),a=s1(s,r);return[a.values,a.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},sU=(e,t,n)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":let s=I("default",e,t,n);return[Un(e.name,t,n)||s];case"Placeholder":return[Un(e.name,t,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":{let c=I("x",e,t,n);return[aa(c)]}case"IdentityN":return I("x",e,t,n).map(c=>aa(c));case"Snapshot":let r=I("x",e,t,n);return[aa(r)];case"Shape":return[Zt(I("x",e,t,n).shape,"int32")];case"ShapeN":return I("x",e,t,n).map(c=>Zt(c.shape));case"Size":return[Ee(I("x",e,t,n).size,"int32")];case"Rank":return[Ee(I("x",e,t,n).rank,"int32")];case"NoOp":return[Ee(1)];case"Print":let a=I("x",e,t,n),o=I("data",e,t,n),i=I("message",e,t,n),l=I("summarize",e,t,n);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(i);for(let c=0;ce.dispose()),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}tensorSize(){return Ee(this.size(),"int32")}async import(e,t){this.checkKeyAndValueTensor(e,t);let n=await e.data();return this.tensorMap.forEach(s=>s.dispose()),this.tensorMap.clear(),j(()=>{let s=as(t),r=n.length,a=s.length;v.assert(r===a,()=>`The number of elements doesn't match, keys has ${r} elements, the values has ${a} elements.`);for(let o=0;o{let s=[];for(let r=0;r{switch(e.op){case"HashTable":case"HashTableV2":{let r=I("keyDType",e,t,n),a=I("valueDType",e,t,n),o=new rU(r,a);return s.addHashTable(e.name,o),[o.handle]}case"LookupTableImport":case"LookupTableImportV2":{let r=I("tableHandle",e,t,n,s),a=I("keys",e,t,n),o=I("values",e,t,n);return[await s.getHashTableById(r.id).import(a,o)]}case"LookupTableFind":case"LookupTableFindV2":{let r=I("tableHandle",e,t,n,s),a=I("keys",e,t,n),o=I("defaultValue",e,t,n);return[await s.getHashTableById(r.id).find(a,o)]}case"LookupTableSize":case"LookupTableSizeV2":{let r=I("tableHandle",e,t,n,s);return[s.getHashTableById(r.id).tensorSize()]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},oU=(e,t,n)=>{switch(e.op){case"ResizeBilinear":{let s=I("images",e,t,n),r=I("size",e,t,n),a=I("alignCorners",e,t,n),o=I("halfPixelCenters",e,t,n);return[$e.resizeBilinear(s,[r[0],r[1]],a,o)]}case"ResizeNearestNeighbor":{let s=I("images",e,t,n),r=I("size",e,t,n),a=I("alignCorners",e,t,n),o=I("halfPixelCenters",e,t,n);return[$e.resizeNearestNeighbor(s,[r[0],r[1]],a,o)]}case"CropAndResize":{let s=I("image",e,t,n),r=I("boxes",e,t,n),a=I("boxInd",e,t,n),o=I("cropSize",e,t,n),i=I("method",e,t,n),l=I("extrapolationValue",e,t,n);return[$e.cropAndResize(s,r,a,o,i,l)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},iU=(e,t,n)=>{switch(e.op){case"Equal":return[Cs(I("a",e,t,n),I("b",e,t,n))];case"NotEqual":return[Tu(I("a",e,t,n),I("b",e,t,n))];case"Greater":return[ms(I("a",e,t,n),I("b",e,t,n))];case"GreaterEqual":return[Yi(I("a",e,t,n),I("b",e,t,n))];case"Less":return[L2(I("a",e,t,n),I("b",e,t,n))];case"LessEqual":return[Ji(I("a",e,t,n),I("b",e,t,n))];case"LogicalAnd":return[lr(I("a",e,t,n),I("b",e,t,n))];case"LogicalNot":return[Jh(I("a",e,t,n))];case"LogicalOr":return[U2(I("a",e,t,n),I("b",e,t,n))];case"Select":case"SelectV2":return[Wn(I("condition",e,t,n),I("a",e,t,n),I("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},lU=(e,t,n)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[He(I("a",e,t,n),I("b",e,t,n),I("transposeA",e,t,n),I("transposeB",e,t,n))];case"Einsum":return[V3(I("equation",e,t,n),...I("tensors",e,t,n))];case"Transpose":return[et(I("x",e,t,n),I("perm",e,t,n))];case"_FusedMatMul":let[s,r]=I("fusedOps",e,t,n),a=s==="biasadd",o=r==="prelu",i=I("numArgs",e,t,n),l=I("leakyreluAlpha",e,t,n);if(a){if(o&&i!==2)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&i!==1)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}let[c,u]=I("args",e,t,n);return[So.matMul({a:I("a",e,t,n),b:I("b",e,t,n),transposeA:I("transposeA",e,t,n),transposeB:I("transposeB",e,t,n),bias:c,activation:r,preluActivationWeights:u,leakyreluAlpha:l})];default:throw TypeError(`Node type ${e.op} is not implemented`)}},uU=(e,t,n)=>{switch(e.op){case"FusedBatchNorm":case"FusedBatchNormV2":return[wu(I("x",e,t,n),I("mean",e,t,n),I("variance",e,t,n),I("offset",e,t,n),I("scale",e,t,n),I("epsilon",e,t,n))];case"FusedBatchNormV3":return[wu(I("x",e,t,n),I("mean",e,t,n),I("variance",e,t,n),I("offset",e,t,n),I("scale",e,t,n),I("epsilon",e,t,n))];case"LRN":return[q3(I("x",e,t,n),I("radius",e,t,n),I("bias",e,t,n),I("alpha",e,t,n),I("beta",e,t,n))];case"Softmax":return[$u(I("x",e,t,n))];case"LogSoftmax":return[B2(I("x",e,t,n))];case"SparseToDense":return[o1(I("sparseIndices",e,t,n),I("outputShape",e,t,n),I("sparseValues",e,t,n),I("defaultValue",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},cU=(e,t,n)=>{switch(e.op){case"Max":{let o=I("axis",e,t,n),i=I("keepDims",e,t,n);return[rs(I("x",e,t,n),o,i)]}case"Mean":{let o=I("axis",e,t,n),i=I("keepDims",e,t,n);return[Wt(I("x",e,t,n),o,i)]}case"Min":{let o=I("axis",e,t,n),i=I("keepDims",e,t,n);return[ef(I("x",e,t,n),o,i)]}case"Sum":{let o=I("axis",e,t,n),i=I("keepDims",e,t,n);return[Ie(I("x",e,t,n),o,i)]}case"All":{let o=I("axis",e,t,n),i=I("keepDims",e,t,n);return[T2(I("x",e,t,n),o,i)]}case"Any":{let o=I("axis",e,t,n),i=I("keepDims",e,t,n);return[Uh(I("x",e,t,n),o,i)]}case"ArgMax":{let o=I("axis",e,t,n);return[Hs(I("x",e,t,n),o)]}case"ArgMin":{let o=I("axis",e,t,n);return[x3(I("x",e,t,n),o)]}case"Prod":{let o=I("axis",e,t,n),i=I("keepDims",e,t,n);return[H2(I("x",e,t,n),o,i)]}case"Cumsum":{let o=I("axis",e,t,n),i=I("exclusive",e,t,n),l=I("reverse",e,t,n);return[M2(I("x",e,t,n),o,i,l)]}case"Bincount":let s=I("x",e,t,n),r=I("weights",e,t,n),a=I("size",e,t,n);return[$2(s,r,a)];case"DenseBincount":{let o=I("x",e,t,n),i=I("weights",e,t,n),l=I("size",e,t,n),c=I("binaryOutput",e,t,n);return[z3(o,i,l,c)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},dU=(e,t,n)=>{switch(e.op){case"ConcatV2":case"Concat":{let s=I("n",e,t,n),r=I("axis",e,t,n),a=I("tensors",e,t,n);return a=a.slice(0,s),[It(a,r)]}case"Gather":{let s=I("x",e,t,n),r=I("indices",e,t,n);return[Su(s,de(r,"int32"),0)]}case"GatherV2":{let s=I("axis",e,t,n),r=I("batchDims",e,t,n),a=I("x",e,t,n),o=I("indices",e,t,n);return[Su(a,de(o,"int32"),s,r)]}case"Reverse":{let s=I("dims",e,t,n),r=[];for(let o=0;o{let s=I("axis",e,t,n),r=I("tensors",e,t,n),a=r[0].shape,o=pt(r[0]).shape,i=r.map(l=>{let c=v.arraysEqual(l.shape,a);if(!c&&!v.arraysEqual(pt(l).shape,o))throw new Error("the input tensors shape does not match");return c?l:G(l,a)});return[Pn(i,s)]});case"Unpack":{let s=I("axis",e,t,n),r=I("tensor",e,t,n);return as(r,s)}case"Tile":{let s=I("reps",e,t,n);return[js(I("x",e,t,n),s)]}case"Split":case"SplitV":{let s=I("axis",e,t,n),r=I("numOrSizeSplits",e,t,n),a=I("x",e,t,n);return Sn(a,r,s)}case"ScatterNd":{let s=I("indices",e,t,n),r=I("values",e,t,n),a=I("shape",e,t,n);return[mv(s,r,a)]}case"GatherNd":{let s=I("x",e,t,n),r=I("indices",e,t,n);return[gv(s,r)]}case"SparseToDense":{let s=I("sparseIndices",e,t,n),r=I("outputShape",e,t,n),a=I("sparseValues",e,t,n),o=I("defaultValue",e,t,n);return[o1(s,a,r,a.dtype===o.dtype?o:de(o,a.dtype))]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},pU=(e,t,n)=>{switch(e.op){case"SparseFillEmptyRows":{let{outputIndices:s,outputValues:r,emptyRowIndicator:a,reverseIndexMap:o}=yd.sparseFillEmptyRows(I("indices",e,t,n),I("values",e,t,n),I("denseShape",e,t,n),I("defaultValue",e,t,n));return[s,r,a,o]}case"SparseReshape":{let{outputIndices:s,outputShape:r}=yd.sparseReshape(I("inputIndices",e,t,n),I("inputShape",e,t,n),I("newShape",e,t,n));return[s,r]}case"SparseSegmentMean":return[yd.sparseSegmentMean(I("data",e,t,n),I("indices",e,t,n),I("segmentIds",e,t,n))];case"SparseSegmentSum":return[yd.sparseSegmentSum(I("data",e,t,n),I("indices",e,t,n),I("segmentIds",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},hU=(e,t,n)=>{switch(e.op){case"FFT":return[af(I("x",e,t,n))];case"IFFT":return[gd(I("x",e,t,n))];case"RFFT":return[of(I("x",e,t,n))];case"IRFFT":return[t1(I("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},fU=(e,t,n)=>{switch(e.op){case"StringNGrams":{let{nGrams:s,nGramsSplits:r}=hf.stringNGrams(I("data",e,t,n),I("dataSplits",e,t,n),I("separator",e,t,n),I("nGramWidths",e,t,n),I("leftPad",e,t,n),I("rightPad",e,t,n),I("padWidth",e,t,n),I("preserveShortSequences",e,t,n));return[s,r]}case"StringSplit":{let{indices:s,values:r,shape:a}=hf.stringSplit(I("input",e,t,n),I("delimiter",e,t,n),I("skipEmpty",e,t,n));return[s,r,a]}case"StringToHashBucketFast":return[hf.stringToHashBucketFast(I("input",e,t,n),I("numBuckets",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},mU=(e,t,n)=>{switch(e.op){case"Cast":return[de(I("x",e,t,n),I("dtype",e,t,n))];case"ExpandDims":{let s=I("axis",e,t,n);return[Kt(I("x",e,t,n),s)]}case"Squeeze":{let s=I("axis",e,t,n);return[pt(I("x",e,t,n),s)]}case"Reshape":return[G(I("x",e,t,n),I("shape",e,t,n))];case"MirrorPad":return[ev(I("x",e,t,n),I("padding",e,t,n),I("mode",e,t,n))];case"PadV2":case"Pad":return[qs(I("x",e,t,n),I("padding",e,t,n),I("constantValue",e,t,n))];case"SpaceToBatchND":{let s=I("blockShape",e,t,n),r=I("paddings",e,t,n);return[nf(I("x",e,t,n),s,r)]}case"BatchToSpaceND":{let s=I("blockShape",e,t,n),r=I("crops",e,t,n);return[jh(I("x",e,t,n),s,r)]}case"DepthToSpace":{let s=I("blockSize",e,t,n),r=I("dataFormat",e,t,n).toUpperCase();return[L3(I("x",e,t,n),s,r)]}case"BroadcastTo":return[ud(I("x",e,t,n),I("shape",e,t,n))];case"BroadcastArgs":return[$3(I("s0",e,t,n),I("s1",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function s7(e,t,n,s){let r=((a,o,i)=>{switch(a.category){case"arithmetic":return j(()=>HV(a,o,i));case"basic_math":return j(()=>jV(a,o,i));case"control":return JV(a,o,i);case"convolution":return j(()=>QV(a,o,i));case"creation":return j(()=>eU(a,o,i));case"dynamic":return tU(a,o,i);case"evaluation":return j(()=>nU(a,o,i));case"image":return j(()=>oU(a,o,i));case"graph":return j(()=>sU(a,o,i));case"logical":return j(()=>iU(a,o,i));case"matrices":return j(()=>lU(a,o,i));case"normalization":return j(()=>uU(a,o,i));case"reduction":return j(()=>cU(a,o,i));case"slice_join":return j(()=>dU(a,o,i));case"sparse":return j(()=>pU(a,o,i));case"spectral":return j(()=>hU(a,o,i));case"string":return j(()=>fU(a,o,i));case"transformation":return j(()=>mU(a,o,i));case"hash_table":return aU(a,o,i,s);case"custom":let l=$k(a.op);if(l&&l.customExecutor)return l.customExecutor(new GV(a,o,i));throw TypeError(`Custom op ${a.op} is not registered.`);default:throw TypeError(`Unknown op '${a.op}'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()`)}})(e,t,n);return v.isPromise(r)?r.then(a=>[].concat(a)):[].concat(r)}var r7=class{constructor(e={},t={},n={},s={}){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=n,this.functionMap=s,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds()}newFrame(e,t){return{id:e,frameName:t,iterationId:0}}set currentContext(e){this.contexts!==e&&(this.contexts=e,this.generateCurrentContextIds())}get currentContext(){return this.contexts}get currentContextId(){return this._currentContextIds[0]}get currentContextIds(){return this._currentContextIds}generateCurrentContextIds(){let e=[];for(let t=0;tt.id===0&&t.iterationId===0?"":`${t.frameName}-${t.iterationId}`).join("/"):""}enterFrame(e){this.contexts&&(this.lastId++,this.contexts=this.contexts.slice(),this.contexts.push(this.newFrame(this.lastId,e)),this._currentContextIds.unshift(this.contextIdforContexts(this.contexts)))}exitFrame(){if(this.contexts&&this.contexts.length>1)this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift();else throw new Error("Cannot exit frame, the context is empty")}nextIteration(){if(this.contexts&&this.contexts.length>0){this.contexts=this.contexts.slice(),this.lastId++;let e=Object.assign({},this.contexts[this.contexts.length-1]);e.iterationId+=1,e.id=this.lastId,this.contexts.splice(-1,1,e),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))}else throw new Error("Cannot increase frame iteration, the context is empty")}getWeight(e){return this.weightMap[e]}addTensorArray(e){this.tensorArrayMap[e.id]=e}getTensorArray(e){return this.tensorArrayMap[e]}addTensorList(e){this.tensorListMap[e.id]=e}getTensorList(e){return this.tensorListMap[e]}dispose(e){for(let t in this.tensorArrayMap)this.tensorArrayMap[t].clearAndClose(e);for(let t in this.tensorListMap)this.tensorListMap[t].clearAndClose(e)}};function a7(e,t,n,s){let r=new Set,a=[],o=null,i=null,l=new Set,c=Object.keys(e).map(p=>As(p)[0]),u=[];s!=null&&(u=s.map(p=>As(p.name)[0]));let d=[...t];for(;d.length>0;){let p=d.pop();if((o7(p)||bU(p)||vU(p))&&o==null&&(o=p,i=o.children.map(h=>h.name).filter(h=>r.has(h))),r.add(p.name),n[p.name]==null&&c.indexOf(p.name)===-1&&u.indexOf(p.name)===-1){if(p.inputs.length===0){a.push(p.name);continue}p.inputs.forEach(h=>{l.has(h.name)||(l.add(h.name),d.push(h))})}}return{inputs:e,outputs:t,usedNodes:r,missingInputs:a,dynamicNode:o,syncInputs:i}}function gU(e,t,n){let{usedNodes:s,inputs:r}=n,a=[],o=Object.keys(r).map(u=>As(u)[0]).map(u=>e.nodes[u]),i=e.initNodes;o.forEach(u=>{s.has(u.name)&&a.push(u)}),e.weights.forEach(u=>{s.has(u.name)&&a.push(u)}),i!=null&&i.forEach(u=>{s.has(u.name)&&a.push(u)});let l=new Set,c=[];for(;a.length>0;){let u=a.pop();l.add(u.name),t[u.name]||c.push(u),u.children.forEach(d=>{!l.has(d.name)&&s.has(d.name)&&d.inputs.every(p=>l.has(p.name))&&a.push(d)})}return c}var AU=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"],yU=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"],xU=["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"];function o7(e){return AU.indexOf(e.op)>=0}function bU(e){return yU.indexOf(e.op)>=0}function vU(e){return xU.indexOf(e.op)>=0}var my=class{constructor(e,t){this.graph=e,this.parent=t,this.compiledMap=new Map,this._weightMap={},this.SEPERATOR=",",this._functions={},this._functionExecutorMap={},this._outputs=e.outputs,this._inputs=e.inputs,this._initNodes=e.initNodes,this._signature=e.signature,this._functions=e.functions,e.functions!=null&&Object.keys(e.functions).forEach(n=>{this._functionExecutorMap[n]=new my(e.functions[n],this)})}get weightIds(){return this.parent?this.parent.weightIds:this._weightIds}get functionExecutorMap(){return this.parent?this.parent.functionExecutorMap:this._functionExecutorMap}get weightMap(){return this.parent?this.parent.weightMap:this._weightMap}set weightMap(e){let t=Object.keys(e).map(n=>e[n].map(s=>s.id));this._weightIds=[].concat(...t),this._weightMap=e}set resourceManager(e){this._resourceManager=e}get inputs(){return this._inputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get outputs(){return this._outputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get inputNodes(){return this._inputs.map(e=>e.signatureKey||e.name)}get outputNodes(){return this._outputs.map(e=>{let t=e.signatureKey||e.name;return e.defaultOutput?`${t}:${e.defaultOutput}`:t})}get functions(){return Object.keys(this._functions).reduce((e,t)=>(e[t]=this._functions[t].signature,e),{})}getCompilationKey(e,t){let n=e.map(r=>r.name).sort(),s=t.map(r=>r.name).sort();return n.join(this.SEPERATOR)+"--"+s.join(this.SEPERATOR)}compile(e,t){let n=a7(e,t,this.weightMap,this._initNodes),{missingInputs:s,dynamicNode:r,syncInputs:a}=n;if(r!=null)throw new Error(`This execution contains the node '${r.name}', which has the dynamic op '${r.op}'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs [${a}]`);if(s.length>0){let o=t.map(l=>l.name),i=Object.keys(e);throw new Error(`Cannot compute the outputs [${o}] from the provided inputs [${i}]. Missing the following inputs: [${s}]`)}return gU(this.graph,this.weightMap,n)}execute(e,t){e=this.mapInputs(e);let n=Object.keys(e).sort();this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t);let s=n.map(u=>this.graph.nodes[As(u)[0]]),r=t.map(u=>As(u)[0]),a=r.map(u=>this.graph.nodes[u]);a.length===0&&(a=this._outputs);let o=this.getCompilationKey(s,a),i=this.compiledMap.get(o);i==null&&(i=this.compile(e,a),this.compiledMap.set(o,i));let l={},c={};return j(()=>{let u=new r7(this.weightMap,l,c,this.functionExecutorMap),d={...this.weightMap};Object.keys(e).forEach(f=>{let[m,g]=As(f),A=[];A[g]=e[f],d[m]=A});let p=this.getFrozenTensorIds(d),h={};for(let f=0;fUn(f,d,u))})}getFrozenTensorIds(e){let t=[].concat.apply([],Object.keys(e).map(n=>e[n]).map(n=>n.map(s=>s.id)));return new Set(t)}checkTensorForDisposal(e,t,n,s,r,a,o){t.category==="control"||a.indexOf(e)!==-1||(n[e].forEach(i=>{i!=null&&(o[i.id]=(o[i.id]||0)+t.children.length)}),t.inputs.forEach(i=>{if(i.category!=="control"){let l=kV(i.name,n,s);l!=null&&l.forEach(c=>{if(c&&!c.kept&&!r.has(c.id)){let u=o[c.id];u===1?(c.dispose(),delete o[c.id]):u!=null&&o[c.id]--}})}}))}async executeAsync(e,t){return this._executeAsync(e,t)}async _executeAsync(e,t,n=!1,s={},r={}){n||(e=this.mapInputs(e),this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t));let a=new r7(this.weightMap,s,r,this.functionExecutorMap),o=await this.executeWithControlFlow(e,a,t,n),i=t.map(d=>Un(d,o,a)),l=i.map(d=>d.id),c=Object.keys(e).map(d=>e[d].id),u=new Set([...l,...c,...this.weightIds]);return Object.keys(o).forEach(d=>{o[d].forEach(h=>{h&&!h.kept&&!h.isDisposed&&!u.has(h.id)&&h.dispose()})}),this.parent==null&&a.dispose(u),i}async executeFunctionAsync(e,t,n){let s=e.reduce((r,a,o)=>(r[this.inputs[o].name]=a,r),{});return this._executeAsync(s,this.outputNodes,!0,t,n)}async executeWithControlFlow(e,t,n,s){let r=Object.keys(e),a=r.map(y=>this.graph.nodes[As(y)[0]]),o=n.map(y=>As(y)[0]),i=o.map(y=>this.graph.nodes[y]);i.length===0&&(i=this._outputs);let{usedNodes:l,missingInputs:c,dynamicNode:u,syncInputs:d}=a7(e,i,this.weightMap,this._initNodes),p=[...a,...this.graph.weights,...this._initNodes||[]].map(y=>({node:y,contexts:t.currentContext})),h={...this.weightMap};Object.keys(e).forEach(y=>{let[x,b]=As(y),w=[];w[b]=e[y],h[x]=w});let f={},m=this.getFrozenTensorIds(h),g={};for(;p.length>0;){let y=this.processStack(a,p,t,h,g,m,o,f,l);await Promise.all(y)}u==null&&!s&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");let A=i.filter(y=>!o7(y)&&!Un(y.name,h,t)).map(y=>y.name);if(A.length>0){let y="";throw u!=null&&(y=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${d}]`),new Error(`Cannot compute the outputs [${A}] from the provided inputs [${r}]. Consider providing the following inputs: [${c}]. ${y}`)}return h}processStack(e,t,n,s,r,a,o,i,l){let c=[];for(;t.length>0;){let u=t.pop();n.currentContext=u.contexts;let d="";if(u.node.op==="Enter"&&I("isConstant",u.node,s,n)&&([d]=ra(u.node.name,n)),s[u.node.name]==null){let p=s7(u.node,s,n,this._resourceManager);d||([d]=ra(u.node.name,n));let h=n.currentContext;v.isPromise(p)?c.push(p.then(f=>(s[d]=f,n.currentContext=h,this.checkTensorForDisposal(d,u.node,s,n,a,o,i),this.processChildNodes(u.node,t,n,s,r,l),f))):(s[d]=p,this.checkTensorForDisposal(d,u.node,s,n,a,o,i),this.processChildNodes(u.node,t,n,s,r,l))}else this.processChildNodes(u.node,t,n,s,r,l)}return c}processChildNodes(e,t,n,s,r,a){e.children.forEach(o=>{let[i]=ra(o.name,n);r[i]||!a.has(o.name)||(o.op==="Merge"?o.inputNames.some(l=>!!Un(l,s,n))&&(r[i]=!0,t.push({contexts:n.currentContext,node:o})):o.inputNames.every(l=>!!Un(l,s,n))&&(r[i]=!0,t.push({contexts:n.currentContext,node:o})))})}dispose(){Object.keys(this.weightMap).forEach(e=>this.weightMap[e].forEach(t=>t.dispose()))}checkInputShapeAndType(e){Object.keys(e).forEach(t=>{let n=e[t],[s]=As(t),r=this.graph.nodes[s];if(r.attrParams.shape&&r.attrParams.shape.value){let a=r.attrParams.shape.value,o=a.length===n.shape.length&&n.shape.every((i,l)=>a[l]===-1||a[l]===i);v.assert(o,()=>`The shape of dict['${r.name}'] provided in model.execute(dict) must be [${a}], but was [${n.shape}]`)}r.attrParams.dtype&&r.attrParams.dtype.value&&v.assert(n.dtype===r.attrParams.dtype.value,()=>`The dtype of dict['${r.name}'] provided in model.execute(dict) must be ${r.attrParams.dtype.value}, but was ${n.dtype}`)})}mapInputs(e){let t={};for(let n in e)if(this._signature!=null&&this._signature.inputs!=null&&this._signature.inputs[n]!=null){let s=this._signature.inputs[n];t[s.name]=e[n]}else t[n]=e[n];return t}checkInputs(e){let t=Object.keys(e).filter(n=>{let[s]=As(n);return this.graph.nodes[s]==null});if(t.length>0)throw new Error(`The dict provided in model.execute(dict) has keys: [${t}] that are not part of graph`)}mapOutputs(e){return e.map(t=>this._signature!=null&&this._signature.outputs!=null&&this._signature.outputs[t]!=null?this._signature.outputs[t].name:t,{})}checkOutputs(e){e.forEach(t=>{let[n]=As(t);if(!this.graph.nodes[n])throw new Error(`The output '${t}' is not found in the graph`)})}},wU=class{constructor(e={},t={}){this.hashTableNameToHandle=e,this.hashTableMap=t}addHashTable(e,t){this.hashTableNameToHandle[e]=t.handle,this.hashTableMap[t.id]=t}getHashTableHandleByName(e){return this.hashTableNameToHandle[e]}getHashTableById(e){return this.hashTableMap[e]}dispose(){for(let e in this.hashTableMap)this.hashTableMap[e].clearAndClose(),delete this.hashTableMap[e];for(let e in this.hashTableNameToHandle)this.hashTableNameToHandle[e].dispose(),delete this.hashTableNameToHandle[e]}},kU="?tfjs-format=file",IU="model.json",i7=class{constructor(e,t={}){this.modelUrl=e,this.loadOptions=t,this.version="n/a",t==null&&(this.loadOptions={}),this.resourceManager=new wU}get modelVersion(){return this.version}get inputNodes(){return this.executor.inputNodes}get outputNodes(){return this.executor.outputNodes}get inputs(){return this.executor.inputs}get outputs(){return this.executor.outputs}get weights(){return this.executor.weightMap}get metadata(){return this.artifacts.userDefinedMetadata}get modelSignature(){return this.signature}findIOHandler(){let e=this.modelUrl;if(e.load!=null)this.handler=e;else if(this.loadOptions.requestInit!=null)this.handler=ns.browserHTTPRequest(e,this.loadOptions);else{let t=ns.getLoadHandlers(e,this.loadOptions);if(t.length===0)t.push(ns.browserHTTPRequest(e,this.loadOptions));else if(t.length>1)throw new Error(`Found more than one (${t.length}) load handlers for URL '${[e]}'`);this.handler=t[0]}}async load(){if(this.findIOHandler(),this.handler.load==null)throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");let e=await this.handler.load();return this.loadSync(e)}loadSync(e){this.artifacts=e;let t=this.artifacts.modelTopology,n;this.artifacts.userDefinedMetadata!=null&&this.artifacts.userDefinedMetadata.signature!=null?n=this.artifacts.userDefinedMetadata.signature:n=this.artifacts.signature,this.signature=n,this.version=`${t.versions.producer}.${t.versions.minConsumer}`;let s=ns.decodeWeights(this.artifacts.weightData,this.artifacts.weightSpecs);if(this.executor=new my(Yk.Instance.transformGraph(t,this.signature)),this.executor.weightMap=this.convertTensorMapToTensorsMap(s),this.executor.resourceManager=this.resourceManager,e.modelInitializer!=null&&e.modelInitializer.node!=null){let r=Yk.Instance.transformGraph(e.modelInitializer);this.initializer=new my(r),this.initializer.weightMap=this.executor.weightMap,this.initializer.resourceManager=this.resourceManager,this.initializer.executeAsync({},[])}return!0}async save(e,t){if(typeof e=="string"){let n=ns.getSaveHandlers(e);if(n.length===0)throw new Error(`Cannot find any save handlers for URL '${e}'`);if(n.length>1)throw new Error(`Found more than one (${n.length}) save handlers for URL '${e}'`);e=n[0]}if(e.save==null)throw new Error("GraphModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return e.save(this.artifacts)}predict(e,t){return this.execute(e,this.outputNodes)}normalizeInputs(e){if(!(e instanceof Ye)&&!Array.isArray(e))return e;if(e=Array.isArray(e)?e:[e],e.length!==this.inputNodes.length)throw new Error(`Input tensor count mismatch,the graph model has ${this.inputNodes.length} placeholders, while there are ${e.length} input tensors.`);return this.inputNodes.reduce((t,n,s)=>(t[n]=e[s],t),{})}normalizeOutputs(e){return e=e||this.outputNodes,Array.isArray(e)?e:[e]}execute(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);let n=this.executor.execute(e,t);return n.length>1?n:n[0]}async executeAsync(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);let n=await this.executor.executeAsync(e,t);return n.length>1?n:n[0]}convertTensorMapToTensorsMap(e){return Object.keys(e).reduce((t,n)=>(t[n]=[e[n]],t),{})}dispose(){this.executor.dispose(),this.initializer&&this.initializer.dispose(),this.resourceManager.dispose()}};async function st(e,t={}){if(e==null)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");t==null&&(t={}),t.fromTFHub&&e.load==null&&(e.endsWith("/")||(e=e+"/"),e=`${e}${IU}${kU}`);let n=new i7(e,t);return await n.load(),n}var SU="0.0.0",l7={};ze(l7,{CSVDataset:()=>w7,Dataset:()=>Bu,FileDataSource:()=>E7,TextLineDataset:()=>x7,URLDataSource:()=>R7,array:()=>XU,csv:()=>aG,func:()=>oG,generator:()=>iG,microphone:()=>uG,version_data:()=>cG,webcam:()=>lG,zip:()=>KU});function CU(e,t){return nm(e,t)}function nm(e,t,n=new Map,s=new Set){if(e==null)return null;if(typeof Blob=="function"&&e instanceof Blob)return e.slice();if(s.has(e))throw new Error("Circular references are not supported.");if(n.has(e))return n.get(e);let r=t(e);if(r.recurse&&r.value!==null)throw new Error("A deep map function may not return both a value and recurse=true.");if(r.recurse)if(Lu(e)){let a=Array.isArray(e)?[]:{};s.add(e);for(let o in e){let i=e[o],l=nm(i,t,n,s);a[o]=l}return s.delete(e),e.__proto__&&(a.__proto__=e.__proto__),a}else throw new Error(`Can't recurse into non-iterable type: ${e}`);else return n.set(e,r.value),r.value}function TU(e,t=c7){return u7(e,t)}function u7(e,t,n=new Set){let s=e[0];if(n.has(s))throw new Error("Circular references are not supported.");let r=t(e);if(r.recurse&&r.value!==null)throw new Error("A deep zip function may not return both a value and recurse=true.");if(r.recurse)if(Lu(s)){let a=Array.isArray(s)?[]:{};n.add(s);for(let o in s){let i=e.map(c=>c[o]),l=u7(i,t,n);a[o]=l}return n.delete(s),a}else throw new Error(`Can't recurse into non-iterable type: ${s}`);else return r.value}function c7(e){return e===null?null:Lu(e[0])?{value:null,recurse:!0}:{value:e,recurse:!1}}async function d7(e,t){let n=new Map;nm(e,t,n);for(let r of Array.from(n.keys())){let a=n.get(r);if(v.isPromise(a)){let o=await a;n.set(r,o)}}return nm(e,t,n)}function Lu(e){let t=!1;if(K().get("IS_BROWSER"))t=e instanceof TextDecoder;else{let{StringDecoder:n}=t5();t=e instanceof n}return e!=null&&!ArrayBuffer.isView(e)&&(Array.isArray(e)||typeof e=="object"&&!(e instanceof Ye)&&!(e instanceof Promise)&&!t)}function NU(e){return e==null||EU(e)||Array.isArray(e)||typeof e=="object"&&e instanceof Ye||v.isTypedArray(e)}function EU(e){return e===null||typeof e!="object"&&typeof e!="function"}function RU(e){return CU(e,$U)}function $U(e){return e instanceof Ye?{value:e.clone(),recurse:!1}:Lu(e)?{value:null,recurse:!0}:{value:e,recurse:!1}}var p7=class{constructor(e){if(this.capacity=e,this.begin=0,this.end=0,e==null)throw new RangeError("Can't create a ring buffer of unknown capacity.");if(e<1)throw new RangeError("Can't create ring buffer of capacity < 1.");this.data=new Array(e),this.doubledCapacity=2*e}wrap(e){for(;e<0;)e+=this.doubledCapacity;return e%this.doubledCapacity}get(e){if(e<0)throw new RangeError("Can't get item at a negative index.");return this.data[e%this.capacity]}set(e,t){if(e<0)throw new RangeError("Can't set item at a negative index.");this.data[e%this.capacity]=t}length(){let e=this.end-this.begin;return e<0&&(e=this.doubledCapacity+e),e}isFull(){return this.length()===this.capacity}isEmpty(){return this.length()===0}push(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.set(this.end,e),this.end=this.wrap(this.end+1)}pushAll(e){for(let t of e)this.push(t)}pop(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");this.end=this.wrap(this.end-1);let e=this.get(this.end);return this.set(this.end,void 0),e}unshift(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.begin=this.wrap(this.begin-1),this.set(this.begin,e)}shift(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");let e=this.get(this.begin);return this.set(this.begin,void 0),this.begin=this.wrap(this.begin+1),e}shuffleExcise(e){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");let t=this.wrap(this.begin+e),n=this.get(t);return this.set(t,this.pop()),n}},h7=class extends p7{constructor(){super(h7.INITIAL_CAPACITY)}isFull(){return!1}push(e){super.isFull()&&this.expand(),super.push(e)}unshift(e){super.isFull()&&this.expand(),super.unshift(e)}expand(){let e=this.capacity*2,t=new Array(e),n=this.length();for(let s=0;st===!0)}rowMajorBatch(e,t=!0){return new BU(this,e,t)}columnMajorBatch(e,t=!0,n=c7){return this.rowMajorBatch(e,t).map(r=>TU(r,n))}concatenate(e,t){return new A7(m7([this,e]),t)}take(e){return e<0||e==null?this:new LU(this,e)}skip(e){return e<0||e==null?this:new zU(this,e)}prefetch(e){return new y7(this,e)}shuffle(e,t){return new jU(this,e,t)}serial(){return new MU(this)}},FU=class extends bn{constructor(e){super();this.items=e,this.trav=0}summary(){return`Array of ${this.items.length} items`}async next(){if(this.trav>=this.items.length)return{value:null,done:!0};let e=this.items[this.trav];return this.trav++,{value:RU(e),done:!1}}},OU=class extends bn{constructor(e){super();this.nextFn=e}summary(){return"Function call"}async next(){try{return this.nextFn()}catch(e){throw e.message=`Error thrown while iterating through a dataset: ${e.message}`,e}}},MU=class extends bn{constructor(e){super();this.upstream=e,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Serial`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){return this.upstream.next()}},zU=class extends bn{constructor(e,t){super();this.upstream=e,this.maxCount=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Skip`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;this.count++ Take`}async next(){return this.count++>=this.maxCount?{value:null,done:!0}:this.upstream.next()}},BU=class extends bn{constructor(e,t,n=!0){super();this.upstream=e,this.batchSize=t,this.enableSmallLastBatch=n,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> RowMajorBatch`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){let e=[];for(;e.length0?{value:e,done:!1}:{value:null,done:!0};e.push(t.value)}return{value:e,done:!1}}},WU=class extends bn{constructor(e,t){super();this.upstream=e,this.predicate=t,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Filter`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;;){let e=await this.upstream.next();if(e.done||this.predicate(e.value))return e;Q(e.value)}}},VU=class extends bn{constructor(e,t){super();this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Map`}async next(){let e=await this.upstream.next();if(e.done)return{value:null,done:!0};let t=rr.getTensorsInContainer(e.value),n=this.transform(e.value),s=rr.getTensorsInContainer(n);for(let r of t)rr.isTensorInList(r,s)||r.dispose();return{value:n,done:!1}}},UU=class extends bn{constructor(e,t){super();this.upstream=e,this.handler=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> handleErrors`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;;)try{return await this.upstream.next()}catch(e){if(!this.handler(e))return{value:null,done:!0}}}},g7=class extends bn{constructor(e,t){super();this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> AsyncMap`}async next(){let e=await this.upstream.next();if(e.done)return{value:null,done:!0};let t=rr.getTensorsInContainer(e.value),n=await this.transform(e.value),s=rr.getTensorsInContainer(n);for(let r of t)rr.isTensorInList(r,s)||r.dispose();return{value:n,done:!1}}},Ay=class extends bn{constructor(){super();this.outputQueue=new f7,this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;this.outputQueue.length()===0;)if(!await this.pump())return{value:null,done:!0};return{value:this.outputQueue.shift(),done:!1}}},GU=class extends Ay{constructor(e,t){super();this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Flatmap`}async pump(){let e=await this.upstream.next();if(e.done)return!1;let t=rr.getTensorsInContainer(e.value),n=this.transform(e.value),s=rr.getTensorsInContainer(n);this.outputQueue.pushAll(n);for(let r of t)rr.isTensorInList(r,s)||r.dispose();return!0}},A7=class extends bn{constructor(e,t){super();this.baseErrorHandler=t,this.lastRead=null,this.iterator=null,this.moreIterators=e}summary(){return"TODO: fill in upstream of chained summaries -> Chained"}async next(){return this.lastRead=this.readFromChain(this.lastRead),this.lastRead}async readFromChain(e){if(await e,this.iterator==null){let n=await this.moreIterators.next();if(n.done)return{value:null,done:!0};this.iterator=n.value,this.baseErrorHandler!=null&&(this.iterator=this.iterator.handleErrors(this.baseErrorHandler))}let t=await this.iterator.next();return t.done?(this.iterator=null,this.readFromChain(e)):t}},sm;(function(e){e[e.FAIL=0]="FAIL",e[e.SHORTEST=1]="SHORTEST",e[e.LONGEST=2]="LONGEST"})(sm||(sm={}));var HU=class extends bn{constructor(e,t=0){super();this.iterators=e,this.mismatchMode=t,this.count=0,this.currentPromise=null}summary(){return"{TODO: fill in upstream of zip summaries} -> Zip"}async nextState(e){await e;let t=0,n=0;function s(a){return a instanceof bn?{value:a.next().then(i=>(t++,i.done&&n++,i.value)),recurse:!1}:{value:null,recurse:!0}}let r=await d7(this.iterators,s);if(t===n)return{value:null,done:!0};if(n>0)switch(this.mismatchMode){case 0:throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);case 1:return{value:null,done:!0};case 2:default:}return this.count++,{value:r,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}},y7=class extends bn{constructor(e,t){super();this.upstream=e,this.bufferSize=t,this.buffer=new p7(t)}summary(){return`${this.upstream.summary()} -> Prefetch`}refill(){for(;!this.buffer.isFull();){let e=this.upstream.next();this.buffer.push(e)}}next(){return this.refill(),this.buffer.shift()}},jU=class extends y7{constructor(e,t,n){super(e,t);this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=DU.alea(n||v.now().toString()),this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}randomInt(e){return Math.floor(this.random()*e)}chooseIndex(){return this.randomInt(this.buffer.length())}async serialNext(){for(this.upstreamExhausted||this.refill();!this.buffer.isEmpty();){let e=this.chooseIndex(),t=await this.buffer.shuffleExcise(e);if(t.done)this.upstreamExhausted=!0;else return this.refill(),t}return{value:null,done:!0}}},qU=Qo(Kp()),Bu=class{constructor(){this.size=null}batch(e,t=!0){let n=this;v.assert(e>0,()=>`batchSize needs to be positive, but it is + ${s}, and tensor's shape is: ${e.shape}`);let a=e.shape.slice(1),o=hy(a,n),i=s===0?0:e.size/s,l=j(()=>{let u=[];e=G(e,[1,s,i]);for(let d=0;d{switch(e.op){case"If":case"StatelessIf":{let s=I("thenBranch",e,t,n),r=I("elseBranch",e,t,n),a=I("cond",e,t,n),o=I("args",e,t,n);return(await a.data())[0]?n.functionMap[s].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap):n.functionMap[r].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap)}case"While":case"StatelessWhile":{let s=I("body",e,t,n),r=I("cond",e,t,n),a=I("args",e,t,n),o=await n.functionMap[r].executeFunctionAsync(a,n.tensorArrayMap,n.tensorListMap),i=a.map(u=>u.id),l=await o[0].data();o.forEach(u=>{!u.kept&&i.indexOf(u.id)===-1&&u.dispose()});let c=a;for(;l[0];){let u=c;c=await n.functionMap[s].executeFunctionAsync(c,n.tensorArrayMap,n.tensorListMap);let d=c.map(h=>h.id);u.forEach(h=>{!h.kept&&i.indexOf(h.id)===-1&&d.indexOf(h.id)===-1&&h.dispose()});let p=await n.functionMap[r].executeFunctionAsync(c,n.tensorArrayMap,n.tensorListMap);l=await p[0].data(),p.forEach(h=>{!h.kept&&i.indexOf(h.id)===-1&&d.indexOf(h.id)===-1&&h.dispose()})}return c}case"LoopCond":{let s=I("pred",e,t,n);return[aa(s)]}case"Switch":{let s=I("pred",e,t,n),r=I("data",e,t,n);return r.kept||(r=aa(r)),(await s.data())[0]?[void 0,r]:[r,void 0]}case"Merge":{let s=e.inputNames.find(r=>Un(r,t,n)!==void 0);if(s){let r=Un(s,t,n);return[aa(r)]}return}case"Enter":{let s=I("frameName",e,t,n),r=I("tensor",e,t,n);return n.enterFrame(s),[aa(r)]}case"Exit":{let s=I("tensor",e,t,n);return n.exitFrame(),[aa(s)]}case"NextIteration":{let s=I("tensor",e,t,n);return n.nextIteration(),[aa(s)]}case"TensorArrayV3":{let s=I("size",e,t,n),r=I("dtype",e,t,n),a=I("elementShape",e,t,n),o=I("dynamicSize",e,t,n),i=I("clearAfterRead",e,t,n),l=I("identicalElementShapes",e,t,n),c=I("name",e,t,n),u=new qV(c,r,s,a,l,o,i);return n.addTensorArray(u),[u.idTensor,Ee(1)]}case"TensorArrayWriteV3":{let s=I("tensorArrayId",e,t,n),r=I("index",e,t,n),a=I("tensor",e,t,n),o=n.getTensorArray(s.id);return o.write(r,a),[o.idTensor]}case"TensorArrayReadV3":{let s=I("tensorArrayId",e,t,n),r=I("index",e,t,n);return[n.getTensorArray(s.id).read(r)]}case"TensorArrayGatherV3":{let s=I("tensorArrayId",e,t,n),r=I("indices",e,t,n),a=I("dtype",e,t,n);return[n.getTensorArray(s.id).gather(r,a)]}case"TensorArrayScatterV3":{let s=I("tensorArrayId",e,t,n),r=I("indices",e,t,n),a=I("tensor",e,t,n),o=n.getTensorArray(s.id);return o.scatter(r,a),[o.idTensor]}case"TensorArrayConcatV3":{let s=I("tensorArrayId",e,t,n),r=n.getTensorArray(s.id),a=I("dtype",e,t,n);return[r.concat(a)]}case"TensorArraySplitV3":{let s=I("tensorArrayId",e,t,n),r=I("tensor",e,t,n),a=I("lengths",e,t,n),o=n.getTensorArray(s.id);return o.split(a,r),[o.idTensor]}case"TensorArraySizeV3":{let s=I("tensorArrayId",e,t,n),r=n.getTensorArray(s.id);return[Ee(r.size(),"int32")]}case"TensorArrayCloseV3":{let s=I("tensorArrayId",e,t,n),r=n.getTensorArray(s.id);return r.clearAndClose(),[r.idTensor]}case"TensorListSetItem":{let s=I("tensorListId",e,t,n),r=I("index",e,t,n),a=I("tensor",e,t,n),o=n.getTensorList(s.id);return o.setItem(r,a),[o.idTensor]}case"TensorListGetItem":{let s=I("tensorListId",e,t,n),r=I("index",e,t,n),a=I("elementShape",e,t,n),o=I("elementDType",e,t,n);return[n.getTensorList(s.id).getItem(r,a,o)]}case"TensorListScatterV2":case"TensorListScatter":{let s=I("indices",e,t,n),r=I("tensor",e,t,n),a=I("elementShape",e,t,n),o=I("numElements",e,t,n),i=ZV(r,s,a,o);return n.addTensorList(i),[i.idTensor]}case"TensorListReserve":case"EmptyTensorList":{let s=I("elementShape",e,t,n),r=I("elementDType",e,t,n),a;e.op==="TensorListReserve"?a="numElements":a="maxNumElements";let o=I(a,e,t,n),i=KV(s,r,o);return n.addTensorList(i),[i.idTensor]}case"TensorListGather":{let s=I("tensorListId",e,t,n),r=I("indices",e,t,n),a=I("elementShape",e,t,n),o=I("elementDType",e,t,n);return[n.getTensorList(s.id).gather(r,o,a)]}case"TensorListStack":{let s=I("tensorListId",e,t,n),r=I("elementShape",e,t,n),a=I("elementDType",e,t,n),o=I("numElements",e,t,n);return[n.getTensorList(s.id).stack(r,a,o)]}case"TensorListFromTensor":{let s=I("tensor",e,t,n),r=I("elementShape",e,t,n),a=I("elementDType",e,t,n),o=XV(s,r,a);return n.addTensorList(o),[o.idTensor]}case"TensorListConcat":{let s=I("tensorListId",e,t,n),r=n.getTensorList(s.id),a=I("dtype",e,t,n),o=I("elementShape",e,t,n);return[r.concat(a,o)]}case"TensorListPushBack":{let s=I("tensorListId",e,t,n),r=I("tensor",e,t,n),a=n.getTensorList(s.id);return a.pushBack(r),[a.idTensor]}case"TensorListPopBack":{let s=I("tensorListId",e,t,n),r=I("elementShape",e,t,n),a=I("elementDType",e,t,n);return[n.getTensorList(s.id).popBack(r,a)]}case"TensorListSplit":{let s=I("tensor",e,t,n),r=I("elementShape",e,t,n),a=I("lengths",e,t,n),o=YV(s,a,r);return n.addTensorList(o),[o.idTensor]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};function n7(e,t,n){let[s,r]=I("fusedOps",e,t,n),a=s==="biasadd",o=!a,i=r==="prelu",l=s==="fusedbatchnorm",c=I("numArgs",e,t,n);if(a){if(i&&c!==2)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!i&&a&&c!==1)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.")}if(l)throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported");let u=I("strides",e,t,n),d=tm(e,t,n),p=I("dataFormat",e,t,n).toUpperCase(),h=I("dilations",e,t,n),[f,m]=I("args",e,t,n);o&&(m=f,f=void 0);let g=I("leakyreluAlpha",e,t,n);return{stride:u,pad:d,dataFormat:p,dilations:h,biasArg:f,preluArg:m,activationFunc:r,leakyreluAlpha:g}}var QV=(e,t,n)=>{switch(e.op){case"Conv1D":{let s=I("stride",e,t,n),r=I("pad",e,t,n),a=I("dataFormat",e,t,n).toUpperCase(),o=I("dilation",e,t,n);return[D2(I("x",e,t,n),I("filter",e,t,n),s,r,a,o)]}case"Conv2D":{let s=I("strides",e,t,n),r=tm(e,t,n),a=I("dataFormat",e,t,n).toUpperCase(),o=I("dilations",e,t,n);return[ko(I("x",e,t,n),I("filter",e,t,n),[s[1],s[2]],r,a,[o[1],o[2]])]}case"_FusedConv2D":{let{stride:s,pad:r,dataFormat:a,dilations:o,biasArg:i,preluArg:l,activationFunc:c,leakyreluAlpha:u}=n7(e,t,n);return[So.conv2d({x:I("x",e,t,n),filter:I("filter",e,t,n),strides:[s[1],s[2]],pad:r,dataFormat:a,dilations:[o[1],o[2]],bias:i,activation:c,preluActivationWeights:l,leakyreluAlpha:u})]}case"FusedDepthwiseConv2dNative":{let{stride:s,pad:r,dataFormat:a,dilations:o,biasArg:i,preluArg:l,activationFunc:c,leakyreluAlpha:u}=n7(e,t,n);return[So.depthwiseConv2d({x:I("x",e,t,n),filter:I("filter",e,t,n),strides:[s[1],s[2]],pad:r,dataFormat:a,dilations:[o[1],o[2]],bias:i,activation:c,preluActivationWeights:l,leakyreluAlpha:u})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{let s=I("outputShape",e,t,n),r=I("strides",e,t,n),a=tm(e,t,n);return[P2(I("x",e,t,n),I("filter",e,t,n),s,[r[1],r[2]],a)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{let s=I("strides",e,t,n),r=tm(e,t,n),a=I("dilations",e,t,n),o=I("dataFormat",e,t,n).toUpperCase();return[cd(I("input",e,t,n),I("filter",e,t,n),[s[1],s[2]],r,o,[a[1],a[2]])]}case"Conv3D":{let s=I("strides",e,t,n),r=I("pad",e,t,n),a=I("dataFormat",e,t,n).toUpperCase(),o=I("dilations",e,t,n);return[F2(I("x",e,t,n),I("filter",e,t,n),[s[1],s[2],s[3]],r,a,[o[1],o[2],o[3]])]}case"AvgPool":{let s=I("strides",e,t,n),r=I("pad",e,t,n),a=I("kernelSize",e,t,n);return[Hh(I("x",e,t,n),[a[1],a[2]],[s[1],s[2]],r)]}case"MaxPool":{let s=I("strides",e,t,n),r=I("pad",e,t,n),a=I("kernelSize",e,t,n);return[Qh(I("x",e,t,n),[a[1],a[2]],[s[1],s[2]],r)]}case"MaxPoolWithArgmax":{let s=I("strides",e,t,n),r=I("pad",e,t,n),a=I("kernelSize",e,t,n),o=I("includeBatchInIndex",e,t,n),{result:i,indexes:l}=Q3(I("x",e,t,n),[a[1],a[2]],[s[1],s[2]],r,o);return[i,l]}case"AvgPool3D":{let s=I("strides",e,t,n),r=I("pad",e,t,n),a=I("kernelSize",e,t,n);return[R2(I("x",e,t,n),[a[1],a[2],a[3]],[s[1],s[2],s[3]],r)]}case"MaxPool3D":{let s=I("strides",e,t,n),r=I("pad",e,t,n),a=I("kernelSize",e,t,n);return[G2(I("x",e,t,n),[a[1],a[2],a[3]],[s[1],s[2],s[3]],r)]}case"Dilation2D":{let s=I("strides",e,t,n),r=I("pad",e,t,n),a=I("dilations",e,t,n),o=s[1],i=s[2],l=a[1],c=a[2];return[B3(I("x",e,t,n),I("filter",e,t,n),[o,i],r,[l,c],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},eU=(e,t,n)=>{switch(e.op){case"Fill":{let s=I("shape",e,t,n),r=I("dtype",e,t,n),a=I("value",e,t,n);return[Iu(s,a,r)]}case"LinSpace":{let s=I("start",e,t,n),r=I("stop",e,t,n),a=I("num",e,t,n);return[j3(s,r,a)]}case"Multinomial":{let s=I("logits",e,t,n),r=I("numSamples",e,t,n),a=I("seed",e,t,n);return[nv(s,r,a)]}case"OneHot":{let s=I("indices",e,t,n),r=I("depth",e,t,n),a=I("onValue",e,t,n),o=I("offValue",e,t,n);return[id(s,r,a,o)]}case"Ones":return[gs(I("shape",e,t,n),I("dtype",e,t,n))];case"OnesLike":return[Es(I("x",e,t,n))];case"RandomUniform":return[Nu(I("shape",e,t,n),I("minval",e,t,n),I("maxval",e,t,n),I("dtype",e,t,n))];case"Range":{let s=I("start",e,t,n),r=I("stop",e,t,n),a=I("step",e,t,n);return[Eu(s,r,a,I("dtype",e,t,n))]}case"TruncatedNormal":{let s=I("shape",e,t,n),r=I("mean",e,t,n),a=I("stdDev",e,t,n),o=I("seed",e,t,n);return[lf(s,r,a,I("dtype",e,t,n),o)]}case"Zeros":return[Ht(I("shape",e,t,n),I("dtype",e,t,n))];case"ZerosLike":return[tt(I("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function fy(e,t,n){let s=I("boxes",e,t,n),r=I("scores",e,t,n),a=I("maxOutputSize",e,t,n),o=I("iouThreshold",e,t,n),i=I("scoreThreshold",e,t,n),l=I("softNmsSigma",e,t,n);return{boxes:s,scores:r,maxOutputSize:a,iouThreshold:o,scoreThreshold:i,softNmsSigma:l}}var tU=async(e,t,n)=>{switch(e.op){case"NonMaxSuppressionV5":{let{boxes:s,scores:r,maxOutputSize:a,iouThreshold:o,scoreThreshold:i,softNmsSigma:l}=fy(e,t,n),c=await $e.nonMaxSuppressionWithScoreAsync(s,r,a,o,i,l);return[c.selectedIndices,c.selectedScores]}case"NonMaxSuppressionV4":{let{boxes:s,scores:r,maxOutputSize:a,iouThreshold:o,scoreThreshold:i}=fy(e,t,n),l=I("padToMaxOutputSize",e,t,n),c=await $e.nonMaxSuppressionPaddedAsync(s,r,a,o,i,l);return[c.selectedIndices,c.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{let{boxes:s,scores:r,maxOutputSize:a,iouThreshold:o,scoreThreshold:i}=fy(e,t,n);return[await $e.nonMaxSuppressionAsync(s,r,a,o,i)]}case"Where":{let s=he(I("condition",e,t,n),"bool"),r=[await r1(s)];return s.dispose(),r}case"ListDiff":return ov(I("x",e,t,n),I("y",e,t,n));default:throw TypeError(`Node type ${e.op} is not implemented`)}},nU=(e,t,n)=>{switch(e.op){case"TopKV2":{let s=I("x",e,t,n),r=I("k",e,t,n),a=I("sorted",e,t,n),o=cv(s,r,a);return[o.values,o.indices]}case"Unique":{let s=I("x",e,t,n),r=s1(s);return[r.values,r.indices]}case"UniqueV2":{let s=I("x",e,t,n),r=I("axis",e,t,n),a=s1(s,r);return[a.values,a.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},sU=(e,t,n)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":let s=I("default",e,t,n);return[Un(e.name,t,n)||s];case"Placeholder":return[Un(e.name,t,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":{let c=I("x",e,t,n);return[aa(c)]}case"IdentityN":return I("x",e,t,n).map(c=>aa(c));case"Snapshot":let r=I("x",e,t,n);return[aa(r)];case"Shape":return[Zt(I("x",e,t,n).shape,"int32")];case"ShapeN":return I("x",e,t,n).map(c=>Zt(c.shape));case"Size":return[Ee(I("x",e,t,n).size,"int32")];case"Rank":return[Ee(I("x",e,t,n).rank,"int32")];case"NoOp":return[Ee(1)];case"Print":let a=I("x",e,t,n),o=I("data",e,t,n),i=I("message",e,t,n),l=I("summarize",e,t,n);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(i);for(let c=0;ce.dispose()),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}tensorSize(){return Ee(this.size(),"int32")}async import(e,t){this.checkKeyAndValueTensor(e,t);let n=await e.data();return this.tensorMap.forEach(s=>s.dispose()),this.tensorMap.clear(),j(()=>{let s=as(t),r=n.length,a=s.length;v.assert(r===a,()=>`The number of elements doesn't match, keys has ${r} elements, the values has ${a} elements.`);for(let o=0;o{let s=[];for(let r=0;r{switch(e.op){case"HashTable":case"HashTableV2":{let r=I("keyDType",e,t,n),a=I("valueDType",e,t,n),o=new rU(r,a);return s.addHashTable(e.name,o),[o.handle]}case"LookupTableImport":case"LookupTableImportV2":{let r=I("tableHandle",e,t,n,s),a=I("keys",e,t,n),o=I("values",e,t,n);return[await s.getHashTableById(r.id).import(a,o)]}case"LookupTableFind":case"LookupTableFindV2":{let r=I("tableHandle",e,t,n,s),a=I("keys",e,t,n),o=I("defaultValue",e,t,n);return[await s.getHashTableById(r.id).find(a,o)]}case"LookupTableSize":case"LookupTableSizeV2":{let r=I("tableHandle",e,t,n,s);return[s.getHashTableById(r.id).tensorSize()]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},oU=(e,t,n)=>{switch(e.op){case"ResizeBilinear":{let s=I("images",e,t,n),r=I("size",e,t,n),a=I("alignCorners",e,t,n),o=I("halfPixelCenters",e,t,n);return[$e.resizeBilinear(s,[r[0],r[1]],a,o)]}case"ResizeNearestNeighbor":{let s=I("images",e,t,n),r=I("size",e,t,n),a=I("alignCorners",e,t,n),o=I("halfPixelCenters",e,t,n);return[$e.resizeNearestNeighbor(s,[r[0],r[1]],a,o)]}case"CropAndResize":{let s=I("image",e,t,n),r=I("boxes",e,t,n),a=I("boxInd",e,t,n),o=I("cropSize",e,t,n),i=I("method",e,t,n),l=I("extrapolationValue",e,t,n);return[$e.cropAndResize(s,r,a,o,i,l)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},iU=(e,t,n)=>{switch(e.op){case"Equal":return[Cs(I("a",e,t,n),I("b",e,t,n))];case"NotEqual":return[Tu(I("a",e,t,n),I("b",e,t,n))];case"Greater":return[ms(I("a",e,t,n),I("b",e,t,n))];case"GreaterEqual":return[Yi(I("a",e,t,n),I("b",e,t,n))];case"Less":return[L2(I("a",e,t,n),I("b",e,t,n))];case"LessEqual":return[Ji(I("a",e,t,n),I("b",e,t,n))];case"LogicalAnd":return[lr(I("a",e,t,n),I("b",e,t,n))];case"LogicalNot":return[Jh(I("a",e,t,n))];case"LogicalOr":return[U2(I("a",e,t,n),I("b",e,t,n))];case"Select":case"SelectV2":return[Wn(I("condition",e,t,n),I("a",e,t,n),I("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},lU=(e,t,n)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[He(I("a",e,t,n),I("b",e,t,n),I("transposeA",e,t,n),I("transposeB",e,t,n))];case"Einsum":return[V3(I("equation",e,t,n),...I("tensors",e,t,n))];case"Transpose":return[et(I("x",e,t,n),I("perm",e,t,n))];case"_FusedMatMul":let[s,r]=I("fusedOps",e,t,n),a=s==="biasadd",o=r==="prelu",i=I("numArgs",e,t,n),l=I("leakyreluAlpha",e,t,n);if(a){if(o&&i!==2)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&i!==1)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}let[c,u]=I("args",e,t,n);return[So.matMul({a:I("a",e,t,n),b:I("b",e,t,n),transposeA:I("transposeA",e,t,n),transposeB:I("transposeB",e,t,n),bias:c,activation:r,preluActivationWeights:u,leakyreluAlpha:l})];default:throw TypeError(`Node type ${e.op} is not implemented`)}},uU=(e,t,n)=>{switch(e.op){case"FusedBatchNorm":case"FusedBatchNormV2":return[wu(I("x",e,t,n),I("mean",e,t,n),I("variance",e,t,n),I("offset",e,t,n),I("scale",e,t,n),I("epsilon",e,t,n))];case"FusedBatchNormV3":return[wu(I("x",e,t,n),I("mean",e,t,n),I("variance",e,t,n),I("offset",e,t,n),I("scale",e,t,n),I("epsilon",e,t,n))];case"LRN":return[q3(I("x",e,t,n),I("radius",e,t,n),I("bias",e,t,n),I("alpha",e,t,n),I("beta",e,t,n))];case"Softmax":return[$u(I("x",e,t,n))];case"LogSoftmax":return[B2(I("x",e,t,n))];case"SparseToDense":return[o1(I("sparseIndices",e,t,n),I("outputShape",e,t,n),I("sparseValues",e,t,n),I("defaultValue",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},cU=(e,t,n)=>{switch(e.op){case"Max":{let o=I("axis",e,t,n),i=I("keepDims",e,t,n);return[rs(I("x",e,t,n),o,i)]}case"Mean":{let o=I("axis",e,t,n),i=I("keepDims",e,t,n);return[Wt(I("x",e,t,n),o,i)]}case"Min":{let o=I("axis",e,t,n),i=I("keepDims",e,t,n);return[ef(I("x",e,t,n),o,i)]}case"Sum":{let o=I("axis",e,t,n),i=I("keepDims",e,t,n);return[Ie(I("x",e,t,n),o,i)]}case"All":{let o=I("axis",e,t,n),i=I("keepDims",e,t,n);return[T2(I("x",e,t,n),o,i)]}case"Any":{let o=I("axis",e,t,n),i=I("keepDims",e,t,n);return[Uh(I("x",e,t,n),o,i)]}case"ArgMax":{let o=I("axis",e,t,n);return[Hs(I("x",e,t,n),o)]}case"ArgMin":{let o=I("axis",e,t,n);return[x3(I("x",e,t,n),o)]}case"Prod":{let o=I("axis",e,t,n),i=I("keepDims",e,t,n);return[H2(I("x",e,t,n),o,i)]}case"Cumsum":{let o=I("axis",e,t,n),i=I("exclusive",e,t,n),l=I("reverse",e,t,n);return[M2(I("x",e,t,n),o,i,l)]}case"Bincount":let s=I("x",e,t,n),r=I("weights",e,t,n),a=I("size",e,t,n);return[$2(s,r,a)];case"DenseBincount":{let o=I("x",e,t,n),i=I("weights",e,t,n),l=I("size",e,t,n),c=I("binaryOutput",e,t,n);return[z3(o,i,l,c)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},dU=(e,t,n)=>{switch(e.op){case"ConcatV2":case"Concat":{let s=I("n",e,t,n),r=I("axis",e,t,n),a=I("tensors",e,t,n);return a=a.slice(0,s),[It(a,r)]}case"Gather":{let s=I("x",e,t,n),r=I("indices",e,t,n);return[Su(s,he(r,"int32"),0)]}case"GatherV2":{let s=I("axis",e,t,n),r=I("batchDims",e,t,n),a=I("x",e,t,n),o=I("indices",e,t,n);return[Su(a,he(o,"int32"),s,r)]}case"Reverse":{let s=I("dims",e,t,n),r=[];for(let o=0;o{let s=I("axis",e,t,n),r=I("tensors",e,t,n),a=r[0].shape,o=pt(r[0]).shape,i=r.map(l=>{let c=v.arraysEqual(l.shape,a);if(!c&&!v.arraysEqual(pt(l).shape,o))throw new Error("the input tensors shape does not match");return c?l:G(l,a)});return[Pn(i,s)]});case"Unpack":{let s=I("axis",e,t,n),r=I("tensor",e,t,n);return as(r,s)}case"Tile":{let s=I("reps",e,t,n);return[js(I("x",e,t,n),s)]}case"Split":case"SplitV":{let s=I("axis",e,t,n),r=I("numOrSizeSplits",e,t,n),a=I("x",e,t,n);return Sn(a,r,s)}case"ScatterNd":{let s=I("indices",e,t,n),r=I("values",e,t,n),a=I("shape",e,t,n);return[mv(s,r,a)]}case"GatherNd":{let s=I("x",e,t,n),r=I("indices",e,t,n);return[gv(s,r)]}case"SparseToDense":{let s=I("sparseIndices",e,t,n),r=I("outputShape",e,t,n),a=I("sparseValues",e,t,n),o=I("defaultValue",e,t,n);return[o1(s,a,r,a.dtype===o.dtype?o:he(o,a.dtype))]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},pU=(e,t,n)=>{switch(e.op){case"SparseFillEmptyRows":{let{outputIndices:s,outputValues:r,emptyRowIndicator:a,reverseIndexMap:o}=yd.sparseFillEmptyRows(I("indices",e,t,n),I("values",e,t,n),I("denseShape",e,t,n),I("defaultValue",e,t,n));return[s,r,a,o]}case"SparseReshape":{let{outputIndices:s,outputShape:r}=yd.sparseReshape(I("inputIndices",e,t,n),I("inputShape",e,t,n),I("newShape",e,t,n));return[s,r]}case"SparseSegmentMean":return[yd.sparseSegmentMean(I("data",e,t,n),I("indices",e,t,n),I("segmentIds",e,t,n))];case"SparseSegmentSum":return[yd.sparseSegmentSum(I("data",e,t,n),I("indices",e,t,n),I("segmentIds",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},hU=(e,t,n)=>{switch(e.op){case"FFT":return[af(I("x",e,t,n))];case"IFFT":return[gd(I("x",e,t,n))];case"RFFT":return[of(I("x",e,t,n))];case"IRFFT":return[t1(I("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},fU=(e,t,n)=>{switch(e.op){case"StringNGrams":{let{nGrams:s,nGramsSplits:r}=hf.stringNGrams(I("data",e,t,n),I("dataSplits",e,t,n),I("separator",e,t,n),I("nGramWidths",e,t,n),I("leftPad",e,t,n),I("rightPad",e,t,n),I("padWidth",e,t,n),I("preserveShortSequences",e,t,n));return[s,r]}case"StringSplit":{let{indices:s,values:r,shape:a}=hf.stringSplit(I("input",e,t,n),I("delimiter",e,t,n),I("skipEmpty",e,t,n));return[s,r,a]}case"StringToHashBucketFast":return[hf.stringToHashBucketFast(I("input",e,t,n),I("numBuckets",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},mU=(e,t,n)=>{switch(e.op){case"Cast":return[he(I("x",e,t,n),I("dtype",e,t,n))];case"ExpandDims":{let s=I("axis",e,t,n);return[Kt(I("x",e,t,n),s)]}case"Squeeze":{let s=I("axis",e,t,n);return[pt(I("x",e,t,n),s)]}case"Reshape":return[G(I("x",e,t,n),I("shape",e,t,n))];case"MirrorPad":return[ev(I("x",e,t,n),I("padding",e,t,n),I("mode",e,t,n))];case"PadV2":case"Pad":return[qs(I("x",e,t,n),I("padding",e,t,n),I("constantValue",e,t,n))];case"SpaceToBatchND":{let s=I("blockShape",e,t,n),r=I("paddings",e,t,n);return[nf(I("x",e,t,n),s,r)]}case"BatchToSpaceND":{let s=I("blockShape",e,t,n),r=I("crops",e,t,n);return[jh(I("x",e,t,n),s,r)]}case"DepthToSpace":{let s=I("blockSize",e,t,n),r=I("dataFormat",e,t,n).toUpperCase();return[L3(I("x",e,t,n),s,r)]}case"BroadcastTo":return[ud(I("x",e,t,n),I("shape",e,t,n))];case"BroadcastArgs":return[$3(I("s0",e,t,n),I("s1",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function s7(e,t,n,s){let r=((a,o,i)=>{switch(a.category){case"arithmetic":return j(()=>HV(a,o,i));case"basic_math":return j(()=>jV(a,o,i));case"control":return JV(a,o,i);case"convolution":return j(()=>QV(a,o,i));case"creation":return j(()=>eU(a,o,i));case"dynamic":return tU(a,o,i);case"evaluation":return j(()=>nU(a,o,i));case"image":return j(()=>oU(a,o,i));case"graph":return j(()=>sU(a,o,i));case"logical":return j(()=>iU(a,o,i));case"matrices":return j(()=>lU(a,o,i));case"normalization":return j(()=>uU(a,o,i));case"reduction":return j(()=>cU(a,o,i));case"slice_join":return j(()=>dU(a,o,i));case"sparse":return j(()=>pU(a,o,i));case"spectral":return j(()=>hU(a,o,i));case"string":return j(()=>fU(a,o,i));case"transformation":return j(()=>mU(a,o,i));case"hash_table":return aU(a,o,i,s);case"custom":let l=$k(a.op);if(l&&l.customExecutor)return l.customExecutor(new GV(a,o,i));throw TypeError(`Custom op ${a.op} is not registered.`);default:throw TypeError(`Unknown op '${a.op}'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()`)}})(e,t,n);return v.isPromise(r)?r.then(a=>[].concat(a)):[].concat(r)}var r7=class{constructor(e={},t={},n={},s={}){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=n,this.functionMap=s,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds()}newFrame(e,t){return{id:e,frameName:t,iterationId:0}}set currentContext(e){this.contexts!==e&&(this.contexts=e,this.generateCurrentContextIds())}get currentContext(){return this.contexts}get currentContextId(){return this._currentContextIds[0]}get currentContextIds(){return this._currentContextIds}generateCurrentContextIds(){let e=[];for(let t=0;tt.id===0&&t.iterationId===0?"":`${t.frameName}-${t.iterationId}`).join("/"):""}enterFrame(e){this.contexts&&(this.lastId++,this.contexts=this.contexts.slice(),this.contexts.push(this.newFrame(this.lastId,e)),this._currentContextIds.unshift(this.contextIdforContexts(this.contexts)))}exitFrame(){if(this.contexts&&this.contexts.length>1)this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift();else throw new Error("Cannot exit frame, the context is empty")}nextIteration(){if(this.contexts&&this.contexts.length>0){this.contexts=this.contexts.slice(),this.lastId++;let e=Object.assign({},this.contexts[this.contexts.length-1]);e.iterationId+=1,e.id=this.lastId,this.contexts.splice(-1,1,e),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))}else throw new Error("Cannot increase frame iteration, the context is empty")}getWeight(e){return this.weightMap[e]}addTensorArray(e){this.tensorArrayMap[e.id]=e}getTensorArray(e){return this.tensorArrayMap[e]}addTensorList(e){this.tensorListMap[e.id]=e}getTensorList(e){return this.tensorListMap[e]}dispose(e){for(let t in this.tensorArrayMap)this.tensorArrayMap[t].clearAndClose(e);for(let t in this.tensorListMap)this.tensorListMap[t].clearAndClose(e)}};function a7(e,t,n,s){let r=new Set,a=[],o=null,i=null,l=new Set,c=Object.keys(e).map(p=>As(p)[0]),u=[];s!=null&&(u=s.map(p=>As(p.name)[0]));let d=[...t];for(;d.length>0;){let p=d.pop();if((o7(p)||bU(p)||vU(p))&&o==null&&(o=p,i=o.children.map(h=>h.name).filter(h=>r.has(h))),r.add(p.name),n[p.name]==null&&c.indexOf(p.name)===-1&&u.indexOf(p.name)===-1){if(p.inputs.length===0){a.push(p.name);continue}p.inputs.forEach(h=>{l.has(h.name)||(l.add(h.name),d.push(h))})}}return{inputs:e,outputs:t,usedNodes:r,missingInputs:a,dynamicNode:o,syncInputs:i}}function gU(e,t,n){let{usedNodes:s,inputs:r}=n,a=[],o=Object.keys(r).map(u=>As(u)[0]).map(u=>e.nodes[u]),i=e.initNodes;o.forEach(u=>{s.has(u.name)&&a.push(u)}),e.weights.forEach(u=>{s.has(u.name)&&a.push(u)}),i!=null&&i.forEach(u=>{s.has(u.name)&&a.push(u)});let l=new Set,c=[];for(;a.length>0;){let u=a.pop();l.add(u.name),t[u.name]||c.push(u),u.children.forEach(d=>{!l.has(d.name)&&s.has(d.name)&&d.inputs.every(p=>l.has(p.name))&&a.push(d)})}return c}var AU=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"],yU=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"],xU=["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"];function o7(e){return AU.indexOf(e.op)>=0}function bU(e){return yU.indexOf(e.op)>=0}function vU(e){return xU.indexOf(e.op)>=0}var my=class{constructor(e,t){this.graph=e,this.parent=t,this.compiledMap=new Map,this._weightMap={},this.SEPERATOR=",",this._functions={},this._functionExecutorMap={},this._outputs=e.outputs,this._inputs=e.inputs,this._initNodes=e.initNodes,this._signature=e.signature,this._functions=e.functions,e.functions!=null&&Object.keys(e.functions).forEach(n=>{this._functionExecutorMap[n]=new my(e.functions[n],this)})}get weightIds(){return this.parent?this.parent.weightIds:this._weightIds}get functionExecutorMap(){return this.parent?this.parent.functionExecutorMap:this._functionExecutorMap}get weightMap(){return this.parent?this.parent.weightMap:this._weightMap}set weightMap(e){let t=Object.keys(e).map(n=>e[n].map(s=>s.id));this._weightIds=[].concat(...t),this._weightMap=e}set resourceManager(e){this._resourceManager=e}get inputs(){return this._inputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get outputs(){return this._outputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get inputNodes(){return this._inputs.map(e=>e.signatureKey||e.name)}get outputNodes(){return this._outputs.map(e=>{let t=e.signatureKey||e.name;return e.defaultOutput?`${t}:${e.defaultOutput}`:t})}get functions(){return Object.keys(this._functions).reduce((e,t)=>(e[t]=this._functions[t].signature,e),{})}getCompilationKey(e,t){let n=e.map(r=>r.name).sort(),s=t.map(r=>r.name).sort();return n.join(this.SEPERATOR)+"--"+s.join(this.SEPERATOR)}compile(e,t){let n=a7(e,t,this.weightMap,this._initNodes),{missingInputs:s,dynamicNode:r,syncInputs:a}=n;if(r!=null)throw new Error(`This execution contains the node '${r.name}', which has the dynamic op '${r.op}'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs [${a}]`);if(s.length>0){let o=t.map(l=>l.name),i=Object.keys(e);throw new Error(`Cannot compute the outputs [${o}] from the provided inputs [${i}]. Missing the following inputs: [${s}]`)}return gU(this.graph,this.weightMap,n)}execute(e,t){e=this.mapInputs(e);let n=Object.keys(e).sort();this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t);let s=n.map(u=>this.graph.nodes[As(u)[0]]),r=t.map(u=>As(u)[0]),a=r.map(u=>this.graph.nodes[u]);a.length===0&&(a=this._outputs);let o=this.getCompilationKey(s,a),i=this.compiledMap.get(o);i==null&&(i=this.compile(e,a),this.compiledMap.set(o,i));let l={},c={};return j(()=>{let u=new r7(this.weightMap,l,c,this.functionExecutorMap),d={...this.weightMap};Object.keys(e).forEach(f=>{let[m,g]=As(f),A=[];A[g]=e[f],d[m]=A});let p=this.getFrozenTensorIds(d),h={};for(let f=0;fUn(f,d,u))})}getFrozenTensorIds(e){let t=[].concat.apply([],Object.keys(e).map(n=>e[n]).map(n=>n.map(s=>s.id)));return new Set(t)}checkTensorForDisposal(e,t,n,s,r,a,o){t.category==="control"||a.indexOf(e)!==-1||(n[e].forEach(i=>{i!=null&&(o[i.id]=(o[i.id]||0)+t.children.length)}),t.inputs.forEach(i=>{if(i.category!=="control"){let l=kV(i.name,n,s);l!=null&&l.forEach(c=>{if(c&&!c.kept&&!r.has(c.id)){let u=o[c.id];u===1?(c.dispose(),delete o[c.id]):u!=null&&o[c.id]--}})}}))}async executeAsync(e,t){return this._executeAsync(e,t)}async _executeAsync(e,t,n=!1,s={},r={}){n||(e=this.mapInputs(e),this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t));let a=new r7(this.weightMap,s,r,this.functionExecutorMap),o=await this.executeWithControlFlow(e,a,t,n),i=t.map(d=>Un(d,o,a)),l=i.map(d=>d.id),c=Object.keys(e).map(d=>e[d].id),u=new Set([...l,...c,...this.weightIds]);return Object.keys(o).forEach(d=>{o[d].forEach(h=>{h&&!h.kept&&!h.isDisposed&&!u.has(h.id)&&h.dispose()})}),this.parent==null&&a.dispose(u),i}async executeFunctionAsync(e,t,n){let s=e.reduce((r,a,o)=>(r[this.inputs[o].name]=a,r),{});return this._executeAsync(s,this.outputNodes,!0,t,n)}async executeWithControlFlow(e,t,n,s){let r=Object.keys(e),a=r.map(y=>this.graph.nodes[As(y)[0]]),o=n.map(y=>As(y)[0]),i=o.map(y=>this.graph.nodes[y]);i.length===0&&(i=this._outputs);let{usedNodes:l,missingInputs:c,dynamicNode:u,syncInputs:d}=a7(e,i,this.weightMap,this._initNodes),p=[...a,...this.graph.weights,...this._initNodes||[]].map(y=>({node:y,contexts:t.currentContext})),h={...this.weightMap};Object.keys(e).forEach(y=>{let[x,b]=As(y),w=[];w[b]=e[y],h[x]=w});let f={},m=this.getFrozenTensorIds(h),g={};for(;p.length>0;){let y=this.processStack(a,p,t,h,g,m,o,f,l);await Promise.all(y)}u==null&&!s&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");let A=i.filter(y=>!o7(y)&&!Un(y.name,h,t)).map(y=>y.name);if(A.length>0){let y="";throw u!=null&&(y=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${d}]`),new Error(`Cannot compute the outputs [${A}] from the provided inputs [${r}]. Consider providing the following inputs: [${c}]. ${y}`)}return h}processStack(e,t,n,s,r,a,o,i,l){let c=[];for(;t.length>0;){let u=t.pop();n.currentContext=u.contexts;let d="";if(u.node.op==="Enter"&&I("isConstant",u.node,s,n)&&([d]=ra(u.node.name,n)),s[u.node.name]==null){let p=s7(u.node,s,n,this._resourceManager);d||([d]=ra(u.node.name,n));let h=n.currentContext;v.isPromise(p)?c.push(p.then(f=>(s[d]=f,n.currentContext=h,this.checkTensorForDisposal(d,u.node,s,n,a,o,i),this.processChildNodes(u.node,t,n,s,r,l),f))):(s[d]=p,this.checkTensorForDisposal(d,u.node,s,n,a,o,i),this.processChildNodes(u.node,t,n,s,r,l))}else this.processChildNodes(u.node,t,n,s,r,l)}return c}processChildNodes(e,t,n,s,r,a){e.children.forEach(o=>{let[i]=ra(o.name,n);r[i]||!a.has(o.name)||(o.op==="Merge"?o.inputNames.some(l=>!!Un(l,s,n))&&(r[i]=!0,t.push({contexts:n.currentContext,node:o})):o.inputNames.every(l=>!!Un(l,s,n))&&(r[i]=!0,t.push({contexts:n.currentContext,node:o})))})}dispose(){Object.keys(this.weightMap).forEach(e=>this.weightMap[e].forEach(t=>t.dispose()))}checkInputShapeAndType(e){Object.keys(e).forEach(t=>{let n=e[t],[s]=As(t),r=this.graph.nodes[s];if(r.attrParams.shape&&r.attrParams.shape.value){let a=r.attrParams.shape.value,o=a.length===n.shape.length&&n.shape.every((i,l)=>a[l]===-1||a[l]===i);v.assert(o,()=>`The shape of dict['${r.name}'] provided in model.execute(dict) must be [${a}], but was [${n.shape}]`)}r.attrParams.dtype&&r.attrParams.dtype.value&&v.assert(n.dtype===r.attrParams.dtype.value,()=>`The dtype of dict['${r.name}'] provided in model.execute(dict) must be ${r.attrParams.dtype.value}, but was ${n.dtype}`)})}mapInputs(e){let t={};for(let n in e)if(this._signature!=null&&this._signature.inputs!=null&&this._signature.inputs[n]!=null){let s=this._signature.inputs[n];t[s.name]=e[n]}else t[n]=e[n];return t}checkInputs(e){let t=Object.keys(e).filter(n=>{let[s]=As(n);return this.graph.nodes[s]==null});if(t.length>0)throw new Error(`The dict provided in model.execute(dict) has keys: [${t}] that are not part of graph`)}mapOutputs(e){return e.map(t=>this._signature!=null&&this._signature.outputs!=null&&this._signature.outputs[t]!=null?this._signature.outputs[t].name:t,{})}checkOutputs(e){e.forEach(t=>{let[n]=As(t);if(!this.graph.nodes[n])throw new Error(`The output '${t}' is not found in the graph`)})}},wU=class{constructor(e={},t={}){this.hashTableNameToHandle=e,this.hashTableMap=t}addHashTable(e,t){this.hashTableNameToHandle[e]=t.handle,this.hashTableMap[t.id]=t}getHashTableHandleByName(e){return this.hashTableNameToHandle[e]}getHashTableById(e){return this.hashTableMap[e]}dispose(){for(let e in this.hashTableMap)this.hashTableMap[e].clearAndClose(),delete this.hashTableMap[e];for(let e in this.hashTableNameToHandle)this.hashTableNameToHandle[e].dispose(),delete this.hashTableNameToHandle[e]}},kU="?tfjs-format=file",IU="model.json",i7=class{constructor(e,t={}){this.modelUrl=e,this.loadOptions=t,this.version="n/a",t==null&&(this.loadOptions={}),this.resourceManager=new wU}get modelVersion(){return this.version}get inputNodes(){return this.executor.inputNodes}get outputNodes(){return this.executor.outputNodes}get inputs(){return this.executor.inputs}get outputs(){return this.executor.outputs}get weights(){return this.executor.weightMap}get metadata(){return this.artifacts.userDefinedMetadata}get modelSignature(){return this.signature}findIOHandler(){let e=this.modelUrl;if(e.load!=null)this.handler=e;else if(this.loadOptions.requestInit!=null)this.handler=ns.browserHTTPRequest(e,this.loadOptions);else{let t=ns.getLoadHandlers(e,this.loadOptions);if(t.length===0)t.push(ns.browserHTTPRequest(e,this.loadOptions));else if(t.length>1)throw new Error(`Found more than one (${t.length}) load handlers for URL '${[e]}'`);this.handler=t[0]}}async load(){if(this.findIOHandler(),this.handler.load==null)throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");let e=await this.handler.load();return this.loadSync(e)}loadSync(e){this.artifacts=e;let t=this.artifacts.modelTopology,n;this.artifacts.userDefinedMetadata!=null&&this.artifacts.userDefinedMetadata.signature!=null?n=this.artifacts.userDefinedMetadata.signature:n=this.artifacts.signature,this.signature=n,this.version=`${t.versions.producer}.${t.versions.minConsumer}`;let s=ns.decodeWeights(this.artifacts.weightData,this.artifacts.weightSpecs);if(this.executor=new my(Yk.Instance.transformGraph(t,this.signature)),this.executor.weightMap=this.convertTensorMapToTensorsMap(s),this.executor.resourceManager=this.resourceManager,e.modelInitializer!=null&&e.modelInitializer.node!=null){let r=Yk.Instance.transformGraph(e.modelInitializer);this.initializer=new my(r),this.initializer.weightMap=this.executor.weightMap,this.initializer.resourceManager=this.resourceManager,this.initializer.executeAsync({},[])}return!0}async save(e,t){if(typeof e=="string"){let n=ns.getSaveHandlers(e);if(n.length===0)throw new Error(`Cannot find any save handlers for URL '${e}'`);if(n.length>1)throw new Error(`Found more than one (${n.length}) save handlers for URL '${e}'`);e=n[0]}if(e.save==null)throw new Error("GraphModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return e.save(this.artifacts)}predict(e,t){return this.execute(e,this.outputNodes)}normalizeInputs(e){if(!(e instanceof Ye)&&!Array.isArray(e))return e;if(e=Array.isArray(e)?e:[e],e.length!==this.inputNodes.length)throw new Error(`Input tensor count mismatch,the graph model has ${this.inputNodes.length} placeholders, while there are ${e.length} input tensors.`);return this.inputNodes.reduce((t,n,s)=>(t[n]=e[s],t),{})}normalizeOutputs(e){return e=e||this.outputNodes,Array.isArray(e)?e:[e]}execute(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);let n=this.executor.execute(e,t);return n.length>1?n:n[0]}async executeAsync(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);let n=await this.executor.executeAsync(e,t);return n.length>1?n:n[0]}convertTensorMapToTensorsMap(e){return Object.keys(e).reduce((t,n)=>(t[n]=[e[n]],t),{})}dispose(){this.executor.dispose(),this.initializer&&this.initializer.dispose(),this.resourceManager.dispose()}};async function st(e,t={}){if(e==null)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");t==null&&(t={}),t.fromTFHub&&e.load==null&&(e.endsWith("/")||(e=e+"/"),e=`${e}${IU}${kU}`);let n=new i7(e,t);return await n.load(),n}var SU="0.0.0",l7={};ze(l7,{CSVDataset:()=>w7,Dataset:()=>Bu,FileDataSource:()=>E7,TextLineDataset:()=>x7,URLDataSource:()=>R7,array:()=>XU,csv:()=>aG,func:()=>oG,generator:()=>iG,microphone:()=>uG,version_data:()=>cG,webcam:()=>lG,zip:()=>KU});function CU(e,t){return nm(e,t)}function nm(e,t,n=new Map,s=new Set){if(e==null)return null;if(typeof Blob=="function"&&e instanceof Blob)return e.slice();if(s.has(e))throw new Error("Circular references are not supported.");if(n.has(e))return n.get(e);let r=t(e);if(r.recurse&&r.value!==null)throw new Error("A deep map function may not return both a value and recurse=true.");if(r.recurse)if(Lu(e)){let a=Array.isArray(e)?[]:{};s.add(e);for(let o in e){let i=e[o],l=nm(i,t,n,s);a[o]=l}return s.delete(e),e.__proto__&&(a.__proto__=e.__proto__),a}else throw new Error(`Can't recurse into non-iterable type: ${e}`);else return n.set(e,r.value),r.value}function TU(e,t=c7){return u7(e,t)}function u7(e,t,n=new Set){let s=e[0];if(n.has(s))throw new Error("Circular references are not supported.");let r=t(e);if(r.recurse&&r.value!==null)throw new Error("A deep zip function may not return both a value and recurse=true.");if(r.recurse)if(Lu(s)){let a=Array.isArray(s)?[]:{};n.add(s);for(let o in s){let i=e.map(c=>c[o]),l=u7(i,t,n);a[o]=l}return n.delete(s),a}else throw new Error(`Can't recurse into non-iterable type: ${s}`);else return r.value}function c7(e){return e===null?null:Lu(e[0])?{value:null,recurse:!0}:{value:e,recurse:!1}}async function d7(e,t){let n=new Map;nm(e,t,n);for(let r of Array.from(n.keys())){let a=n.get(r);if(v.isPromise(a)){let o=await a;n.set(r,o)}}return nm(e,t,n)}function Lu(e){let t=!1;if(K().get("IS_BROWSER"))t=e instanceof TextDecoder;else{let{StringDecoder:n}=t5();t=e instanceof n}return e!=null&&!ArrayBuffer.isView(e)&&(Array.isArray(e)||typeof e=="object"&&!(e instanceof Ye)&&!(e instanceof Promise)&&!t)}function NU(e){return e==null||EU(e)||Array.isArray(e)||typeof e=="object"&&e instanceof Ye||v.isTypedArray(e)}function EU(e){return e===null||typeof e!="object"&&typeof e!="function"}function RU(e){return CU(e,$U)}function $U(e){return e instanceof Ye?{value:e.clone(),recurse:!1}:Lu(e)?{value:null,recurse:!0}:{value:e,recurse:!1}}var p7=class{constructor(e){if(this.capacity=e,this.begin=0,this.end=0,e==null)throw new RangeError("Can't create a ring buffer of unknown capacity.");if(e<1)throw new RangeError("Can't create ring buffer of capacity < 1.");this.data=new Array(e),this.doubledCapacity=2*e}wrap(e){for(;e<0;)e+=this.doubledCapacity;return e%this.doubledCapacity}get(e){if(e<0)throw new RangeError("Can't get item at a negative index.");return this.data[e%this.capacity]}set(e,t){if(e<0)throw new RangeError("Can't set item at a negative index.");this.data[e%this.capacity]=t}length(){let e=this.end-this.begin;return e<0&&(e=this.doubledCapacity+e),e}isFull(){return this.length()===this.capacity}isEmpty(){return this.length()===0}push(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.set(this.end,e),this.end=this.wrap(this.end+1)}pushAll(e){for(let t of e)this.push(t)}pop(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");this.end=this.wrap(this.end-1);let e=this.get(this.end);return this.set(this.end,void 0),e}unshift(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.begin=this.wrap(this.begin-1),this.set(this.begin,e)}shift(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");let e=this.get(this.begin);return this.set(this.begin,void 0),this.begin=this.wrap(this.begin+1),e}shuffleExcise(e){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");let t=this.wrap(this.begin+e),n=this.get(t);return this.set(t,this.pop()),n}},h7=class extends p7{constructor(){super(h7.INITIAL_CAPACITY)}isFull(){return!1}push(e){super.isFull()&&this.expand(),super.push(e)}unshift(e){super.isFull()&&this.expand(),super.unshift(e)}expand(){let e=this.capacity*2,t=new Array(e),n=this.length();for(let s=0;st===!0)}rowMajorBatch(e,t=!0){return new BU(this,e,t)}columnMajorBatch(e,t=!0,n=c7){return this.rowMajorBatch(e,t).map(r=>TU(r,n))}concatenate(e,t){return new A7(m7([this,e]),t)}take(e){return e<0||e==null?this:new LU(this,e)}skip(e){return e<0||e==null?this:new zU(this,e)}prefetch(e){return new y7(this,e)}shuffle(e,t){return new jU(this,e,t)}serial(){return new MU(this)}},FU=class extends bn{constructor(e){super();this.items=e,this.trav=0}summary(){return`Array of ${this.items.length} items`}async next(){if(this.trav>=this.items.length)return{value:null,done:!0};let e=this.items[this.trav];return this.trav++,{value:RU(e),done:!1}}},OU=class extends bn{constructor(e){super();this.nextFn=e}summary(){return"Function call"}async next(){try{return this.nextFn()}catch(e){throw e.message=`Error thrown while iterating through a dataset: ${e.message}`,e}}},MU=class extends bn{constructor(e){super();this.upstream=e,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Serial`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){return this.upstream.next()}},zU=class extends bn{constructor(e,t){super();this.upstream=e,this.maxCount=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Skip`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;this.count++ Take`}async next(){return this.count++>=this.maxCount?{value:null,done:!0}:this.upstream.next()}},BU=class extends bn{constructor(e,t,n=!0){super();this.upstream=e,this.batchSize=t,this.enableSmallLastBatch=n,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> RowMajorBatch`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){let e=[];for(;e.length0?{value:e,done:!1}:{value:null,done:!0};e.push(t.value)}return{value:e,done:!1}}},WU=class extends bn{constructor(e,t){super();this.upstream=e,this.predicate=t,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Filter`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;;){let e=await this.upstream.next();if(e.done||this.predicate(e.value))return e;Q(e.value)}}},VU=class extends bn{constructor(e,t){super();this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Map`}async next(){let e=await this.upstream.next();if(e.done)return{value:null,done:!0};let t=rr.getTensorsInContainer(e.value),n=this.transform(e.value),s=rr.getTensorsInContainer(n);for(let r of t)rr.isTensorInList(r,s)||r.dispose();return{value:n,done:!1}}},UU=class extends bn{constructor(e,t){super();this.upstream=e,this.handler=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> handleErrors`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;;)try{return await this.upstream.next()}catch(e){if(!this.handler(e))return{value:null,done:!0}}}},g7=class extends bn{constructor(e,t){super();this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> AsyncMap`}async next(){let e=await this.upstream.next();if(e.done)return{value:null,done:!0};let t=rr.getTensorsInContainer(e.value),n=await this.transform(e.value),s=rr.getTensorsInContainer(n);for(let r of t)rr.isTensorInList(r,s)||r.dispose();return{value:n,done:!1}}},Ay=class extends bn{constructor(){super();this.outputQueue=new f7,this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;this.outputQueue.length()===0;)if(!await this.pump())return{value:null,done:!0};return{value:this.outputQueue.shift(),done:!1}}},GU=class extends Ay{constructor(e,t){super();this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Flatmap`}async pump(){let e=await this.upstream.next();if(e.done)return!1;let t=rr.getTensorsInContainer(e.value),n=this.transform(e.value),s=rr.getTensorsInContainer(n);this.outputQueue.pushAll(n);for(let r of t)rr.isTensorInList(r,s)||r.dispose();return!0}},A7=class extends bn{constructor(e,t){super();this.baseErrorHandler=t,this.lastRead=null,this.iterator=null,this.moreIterators=e}summary(){return"TODO: fill in upstream of chained summaries -> Chained"}async next(){return this.lastRead=this.readFromChain(this.lastRead),this.lastRead}async readFromChain(e){if(await e,this.iterator==null){let n=await this.moreIterators.next();if(n.done)return{value:null,done:!0};this.iterator=n.value,this.baseErrorHandler!=null&&(this.iterator=this.iterator.handleErrors(this.baseErrorHandler))}let t=await this.iterator.next();return t.done?(this.iterator=null,this.readFromChain(e)):t}},sm;(function(e){e[e.FAIL=0]="FAIL",e[e.SHORTEST=1]="SHORTEST",e[e.LONGEST=2]="LONGEST"})(sm||(sm={}));var HU=class extends bn{constructor(e,t=0){super();this.iterators=e,this.mismatchMode=t,this.count=0,this.currentPromise=null}summary(){return"{TODO: fill in upstream of zip summaries} -> Zip"}async nextState(e){await e;let t=0,n=0;function s(a){return a instanceof bn?{value:a.next().then(i=>(t++,i.done&&n++,i.value)),recurse:!1}:{value:null,recurse:!0}}let r=await d7(this.iterators,s);if(t===n)return{value:null,done:!0};if(n>0)switch(this.mismatchMode){case 0:throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);case 1:return{value:null,done:!0};case 2:default:}return this.count++,{value:r,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}},y7=class extends bn{constructor(e,t){super();this.upstream=e,this.bufferSize=t,this.buffer=new p7(t)}summary(){return`${this.upstream.summary()} -> Prefetch`}refill(){for(;!this.buffer.isFull();){let e=this.upstream.next();this.buffer.push(e)}}next(){return this.refill(),this.buffer.shift()}},jU=class extends y7{constructor(e,t,n){super(e,t);this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=DU.alea(n||v.now().toString()),this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}randomInt(e){return Math.floor(this.random()*e)}chooseIndex(){return this.randomInt(this.buffer.length())}async serialNext(){for(this.upstreamExhausted||this.refill();!this.buffer.isEmpty();){let e=this.chooseIndex(),t=await this.buffer.shuffleExcise(e);if(t.done)this.upstreamExhausted=!0;else return this.refill(),t}return{value:null,done:!0}}},qU=Qo(Kp()),Bu=class{constructor(){this.size=null}batch(e,t=!0){let n=this;v.assert(e>0,()=>`batchSize needs to be positive, but it is ${e}`);let s;return this.size===1/0||this.size==null?s=this.size:t?s=Math.ceil(this.size/e):s=Math.floor(this.size/e),ys(async()=>(await n.iterator()).columnMajorBatch(e,t,ZU),s)}concatenate(e){let t=this,n;return this.size===1/0||e.size===1/0?n=1/0:this.size!=null&&e.size!=null?n=this.size+e.size:n=null,ys(async()=>(await t.iterator()).concatenate(await e.iterator()),n)}filter(e){let t=this,n;return this.size===1/0?n=1/0:n=null,ys(async()=>(await t.iterator()).filter(s=>j(()=>e(s))),n)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){let t=this;return ys(async()=>(await t.iterator()).map(n=>j(()=>e(n))),this.size)}mapAsync(e){let t=this;return ys(async()=>(await t.iterator()).mapAsync(e),this.size)}prefetch(e){if(e==null)throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");let t=this;return ys(async()=>(await t.iterator()).prefetch(e),this.size)}repeat(e){let t=this,n;return this.size!=null&&e>0?n=this.size*e:e===0?n=0:this.size!=null&&(e===void 0||e<0)?n=1/0:n=null,ys(async()=>{let s=gy(async()=>({value:await t.iterator(),done:!1}));return _U(s.take(e))},n)}skip(e){let t=this,n;return this.size!=null&&e>=0&&this.size>=e?n=this.size-e:this.size!=null&&(this.size(await t.iterator()).skip(e),n)}shuffle(e,t,n=!0){if(e==null||e<0)throw this.size==null?new RangeError("`Dataset.shuffle()` requires bufferSize to be specified."):new RangeError(`\`Dataset.shuffle()\` requires bufferSize to be specified. If your data fits in main memory (for regular JS objects), and/or GPU memory (for \`tf.Tensor\`s), consider setting bufferSize to the dataset size (${this.size} elements)`);let s=this,r=qU.alea(t||v.now().toString());return ys(async()=>{let a=r.int32();return n&&(a+=r.int32()),(await s.iterator()).shuffle(e,a.toString())},this.size)}take(e){let t=this,n;return this.size!=null&&this.size>e?n=e:this.size!=null&&this.size<=e?n=this.size:n=null,ys(async()=>(await t.iterator()).take(e),n)}async toArray(){if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArray()}async toArrayForTest(){if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArrayForTest()}};Bu.MAX_BUFFER_SIZE=1e4;function ys(e,t=null){return new class extends Bu{constructor(){super(...arguments);this.size=t}async iterator(){return e()}}}function XU(e){return ys(async()=>m7(e),e.length)}function KU(e){if(!Lu(e))throw new Error("The argument to zip() must be an object or array.");let t;if(Array.isArray(e))for(let n=0;n{let n=await d7(e,s=>{if(s instanceof Bu)return{value:s.iterator(),recurse:!1};if(Lu(s))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return PU(n,sm.SHORTEST)},t)}function ZU(e){if(e===null)return null;let t=e[0];return NU(t)?{value:YU(e),recurse:!1}:{value:null,recurse:!0}}function YU(e){if(e.length===0)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof Ye?Pn(e):Gt(e)}var x7=class extends Bu{constructor(e){super();this.input=e}async iterator(){return(await this.input.iterator()).decodeUTF8().split(` -`).map(s=>(s.endsWith("\r")&&(s=s.slice(0,-1)),s))}},rm='"',zd=Symbol("out"),b7=Symbol("field"),am=Symbol("quote"),yy=Symbol("quoteafterquote"),v7=Symbol("quoteinquote"),w7=class extends Bu{constructor(e,t){super();this.input=e,this.hasHeader=!0,this.fullColumnNames=null,this.columnNamesValidated=!1,this.columnConfigs=null,this.configuredColumnsOnly=!1,this.delimiter=",",this.delimWhitespace=!1,this.base=new x7(e),t||(t={}),this.hasHeader=t.hasHeader!==!1,this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(v.assert(t.delimiter==null,()=>"Delimiter should not be provided when delimWhitespace is true."),this.delimWhitespace=!0,this.delimiter=" "):this.delimiter=t.delimiter?t.delimiter:","}async columnNames(){return this.columnNamesValidated||await this.setColumnNames(),this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames}async setColumnNames(){let e=await this.maybeReadHeaderLine();if(!this.fullColumnNames&&!e)throw new Error("Column names must be provided if there is no header line.");this.fullColumnNames&&e&&v.assert(e.length===this.fullColumnNames.length,()=>"The length of provided columnNames ("+this.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+e.length.toString()+")."),this.fullColumnNames||(this.fullColumnNames=e);let t=this.fullColumnNames.reduce((s,r)=>(s[r]=s[r]+1||1,s),{}),n=Object.keys(t).filter(s=>t[s]>1);if(v.assert(n.length===0,()=>"Duplicate column names found: "+n.toString()),this.columnConfigs){for(let s of Object.keys(this.columnConfigs))if(this.fullColumnNames.indexOf(s)===-1)throw new Error('The key "'+s+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){let t=await(await this.base.iterator()).next();if(t.done)throw new Error("No data was found for CSV parsing.");let n=t.value;return this.parseRow(n,!1)}else return null}async iterator(){this.columnNamesValidated||await this.setColumnNames();let e=await this.base.iterator();return this.hasHeader&&(e=e.skip(1)),e.map(t=>this.makeDataElement(t))}makeDataElement(e){let t=this.parseRow(e),n={},s={};for(let r=0;r14||!Number.isInteger(t))throw new Error(`Invalid fftSize: it must be a power of 2 between 2 to 4 and 2 to 14, but got ${this.fftSize}`);if(this.numFrames=e.numFramesPerSpectrogram||43,this.sampleRateHz=e.sampleRateHz,this.columnTruncateLength=e.columnTruncateLength||this.fftSize,this.audioTrackConstraints=e.audioTrackConstraints,this.smoothingTimeConstant=e.smoothingTimeConstant||0,this.includeSpectrogram=e.includeSpectrogram!==!1,this.includeWaveform=e.includeWaveform===!0,!this.includeSpectrogram&&!this.includeWaveform)throw new Error("Both includeSpectrogram and includeWaveform are false. At least one type of data should be returned.")}summary(){return"microphone"}static async create(e={}){if(K().get("IS_NODE"))throw new Error("microphone API is only supported in browser environment.");let t=new k7(e);return await t.start(),t}async start(){try{this.stream=await navigator.mediaDevices.getUserMedia({audio:this.audioTrackConstraints==null?!0:this.audioTrackConstraints,video:!1})}catch(n){throw new Error(`Error thrown while initializing video stream: ${n.message}`)}if(!this.stream)throw new Error("Could not obtain audio from microphone.");let e=window.AudioContext||window.webkitAudioContext;if(this.audioContext=new e,!this.sampleRateHz)this.sampleRateHz=this.audioContext.sampleRate;else if(this.audioContext.sampleRate!==this.sampleRateHz)throw new Error(`Mismatch in sampling rate: Expected: ${this.sampleRateHz}; Actual: ${this.audioContext.sampleRate}`);let t=this.audioContext.createMediaStreamSource(this.stream);this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=this.fftSize*2,this.analyser.smoothingTimeConstant=this.smoothingTimeConstant,t.connect(this.analyser),this.freqData=new Float32Array(this.fftSize),this.timeData=new Float32Array(this.fftSize)}async next(){if(this.isClosed)return{value:null,done:!0};let e,t,n=await this.getAudioData();if(this.includeSpectrogram){let s=this.flattenQueue(n.freqDataQueue);e=this.getTensorFromAudioDataArray(s,[this.numFrames,this.columnTruncateLength,1])}if(this.includeWaveform){let s=this.flattenQueue(n.timeDataQueue);t=this.getTensorFromAudioDataArray(s,[this.numFrames*this.fftSize,1])}return{value:{spectrogram:e,waveform:t},done:!1}}async capture(){return(await this.next()).value}async getAudioData(){let e=[],t=[],n=0;return new Promise(s=>{let r=setInterval(()=>{this.includeSpectrogram&&(this.analyser.getFloatFrequencyData(this.freqData),this.freqData[0]===-1/0&&s({freqDataQueue:e,timeDataQueue:t}),e.push(this.freqData.slice(0,this.columnTruncateLength))),this.includeWaveform&&(this.analyser.getFloatTimeDomainData(this.timeData),t.push(this.timeData.slice())),++n===this.numFrames&&(clearInterval(r),s({freqDataQueue:e,timeDataQueue:t}))},this.fftSize/this.sampleRateHz*1e3)})}stop(){this.isClosed||(this.isClosed=!0,this.analyser.disconnect(),this.audioContext.close(),this.stream!=null&&this.stream.getTracks().length>0&&this.stream.getTracks()[0].stop())}toArray(){throw new Error("Can not convert infinite audio stream to array.")}getSampleRate(){return this.sampleRateHz}flattenQueue(e){let t=e[0].length,n=new Float32Array(e.length*t);return e.forEach((s,r)=>n.set(s,r*t)),n}getTensorFromAudioDataArray(e,t){let n=new Float32Array(v.sizeFromShape(t));return n.set(e,n.length-e.length),Gt(n,t)}},I7=class extends bn{constructor(e,t){super();if(this.webcamVideoElement=e,this.webcamConfig=t,this.isClosed=!0,this.resize=!1,this.needToResize())if(this.resize=!0,this.cropSize=[this.webcamConfig.resizeHeight,this.webcamConfig.resizeWidth],this.cropBoxInd=Zt([0],"int32"),this.webcamConfig.centerCrop){let n=this.webcamConfig.resizeWidth*1/this.webcamVideoElement.width,s=this.webcamConfig.resizeHeight*1/this.webcamVideoElement.height,r=(1-n)/2,a=(1-s)/2,o=r+n,i=s+a;this.cropBox=ur([a,r,i,o],[1,4])}else this.cropBox=ur([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(e,t={}){if(K().get("IS_NODE"))throw new Error("tf.data.webcam is only supported in browser environment.");if(!e){if(e=document.createElement("video"),!t.resizeWidth||!t.resizeHeight)throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");e.width=t.resizeWidth,e.height=t.resizeHeight}let n=new I7(e,t);return await n.start(),n}async start(){this.webcamConfig.facingMode&&v.assert(this.webcamConfig.facingMode==="user"||this.webcamConfig.facingMode==="environment",()=>`Invalid webcam facing mode: ${this.webcamConfig.facingMode}. Please provide 'user' or 'environment'`);try{this.stream=await navigator.mediaDevices.getUserMedia({video:{deviceId:this.webcamConfig.deviceId,facingMode:this.webcamConfig.facingMode?this.webcamConfig.facingMode:"user",width:this.webcamVideoElement.width,height:this.webcamVideoElement.height}})}catch(e){throw e.message=`Error thrown while initializing video stream: ${e.message}`,e}if(!this.stream)throw new Error("Could not obtain video from webcam.");try{this.webcamVideoElement.srcObject=this.stream}catch(e){console.log(e),this.webcamVideoElement.src=window.URL.createObjectURL(this.stream)}return this.webcamVideoElement.play(),this.isClosed=!1,new Promise(e=>{this.webcamVideoElement.onloadedmetadata=()=>{e()}})}async next(){if(this.isClosed)return{value:null,done:!0};let e;try{e=Gs.fromPixels(this.webcamVideoElement)}catch(t){throw new Error(`Error thrown converting video to pixels: ${JSON.stringify(t)}`)}if(this.resize)try{return{value:this.cropAndResizeFrame(e),done:!1}}catch(t){throw new Error(`Error thrown cropping the video: ${t.message}`)}finally{e.dispose()}else return{value:e,done:!1}}needToResize(){return!!(this.webcamConfig.resizeWidth&&this.webcamConfig.resizeHeight&&(this.webcamVideoElement.width!==this.webcamConfig.resizeWidth||this.webcamVideoElement.height!==this.webcamConfig.resizeHeight))}cropAndResizeFrame(e){return j(()=>{let t=Kt(de(e,"float32"),0),n;n=$e.cropAndResize(t,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");let s=n.shape;return G(n,s.slice(1))})}async capture(){return(await this.next()).value}stop(){this.stream.getTracks().forEach(t=>t.stop());try{this.webcamVideoElement.srcObject=null}catch(t){console.log(t),this.webcamVideoElement.src=null}this.isClosed=!0}toArray(){throw new Error("Can not convert infinite video stream to array.")}},S7=class{},C7=class extends bn{split(e){return new JU(this,e)}},JU=class extends C7{constructor(e,t){super();this.upstream=e,this.impl=new QU(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},QU=class extends Ay{constructor(e,t){super();this.upstream=e,this.separator=t,this.carryover=""}summary(){return`${this.upstream.summary()} -> Split('${this.separator}')`}async pump(){let e=await this.upstream.next();if(e.done)return this.carryover===""?!1:(this.outputQueue.push(this.carryover),this.carryover="",!0);let t=e.value.split(this.separator);t[0]=this.carryover+t[0];for(let n of t.slice(0,-1))this.outputQueue.push(n);return this.carryover=t[t.length-1],!0}},eG=class extends bn{decodeUTF8(){return new tG(this)}},tG=class extends C7{constructor(e){super();this.upstream=e,this.impl=new nG(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},nG=class extends Ay{constructor(e){super();if(this.upstream=e,K().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{let{StringDecoder:t}=t5();this.decoder=new t("utf8")}}summary(){return`${this.upstream.summary()} -> Utf8`}async pump(){let e=await this.upstream.next(),t;if(e.done)return!1;t=e.value;let n;return K().get("IS_BROWSER")?n=this.decoder.decode(t,{stream:!0}):n=this.decoder.write(Buffer.from(t.buffer)),this.outputQueue.push(n),!0}},T7=class extends eG{constructor(e,t={}){super();this.file=e,this.options=t,v.assert(e instanceof Uint8Array||(K().get("IS_BROWSER")?e instanceof File||e instanceof Blob:!1),()=>"FileChunkIterator only supports File, Blob and Uint8Array right now."),this.offset=t.offset||0,this.chunkSize=t.chunkSize||1024*1024}summary(){return`FileChunks ${this.file}`}async next(){return this.offset>=(this.file instanceof Uint8Array?this.file.byteLength:this.file.size)?{value:null,done:!0}:{value:await new Promise((t,n)=>{let s=this.offset+this.chunkSize;if(this.file instanceof Uint8Array)t(new Uint8Array(this.file.slice(this.offset,s)));else{let r=new FileReader;r.onload=o=>{let i=r.result;if(i instanceof ArrayBuffer&&(i=new Uint8Array(i)),!(i instanceof Uint8Array))return n(new TypeError("FileReader returned unknown type."));t(i)},r.onabort=o=>n(new Error("Aborted")),r.onerror=o=>n(new Error(o.type));let a=this.file.slice(this.offset,s);r.readAsArrayBuffer(a)}this.offset=s}),done:!1}}};async function sG(e,t={},n){let s,r;typeof e=="string"?s=e:(s=e.url,r=rG(e));let a=await(n||v.fetch)(s,r);if(a.ok){let o=new Uint8Array(await a.arrayBuffer());return new T7(o,t)}else throw new Error(a.statusText)}var rG=e=>({method:e.method,headers:e.headers,body:e.body,mode:e.mode,credentials:e.credentials,cache:e.cache,redirect:e.redirect,referrer:e.referrer,integrity:e.integrity});function N7(e){return typeof e=="string"&&e.substr(0,7)==="file://"}var E7=class extends S7{constructor(e,t={}){super();this.input=e,this.options=t}async iterator(){if(N7(this.input)&&K().get("IS_NODE")){let e=Ws("fs");this.input=e.readFileSync(this.input.substr(7))}return new T7(this.input,this.options)}},R7=class extends S7{constructor(e,t={}){super();this.url=e,this.fileOptions=t}async iterator(){return N7(this.url)?new E7(this.url,this.fileOptions).iterator():sG(this.url,this.fileOptions)}};function aG(e,t={}){return new w7(new R7(e),t)}function oG(e){let t=gy(e);return ys(async()=>t)}function iG(e){return ys(async()=>{let t=await e();return gy(()=>t.next())})}async function lG(e,t){return I7.create(e,t)}async function uG(e){return k7.create(e)}var cG="0.0.0";function Ne(e,t){Array.isArray(e)||(e=[e]),e.forEach(n=>{n!=null&&v.assert(n.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the CPU backend.`)})}var dG=Xs.whereImpl,$7=class extends Ll{constructor(){super();this.blockSize=48,this.firstUse=!0,this.data=new Dc(this,ss())}nextDataId(){return $7.nextDataId++}write(e,t,n){this.firstUse&&(this.firstUse=!1,K().get("IS_NODE")&&N.warn(` +`).map(s=>(s.endsWith("\r")&&(s=s.slice(0,-1)),s))}},rm='"',zd=Symbol("out"),b7=Symbol("field"),am=Symbol("quote"),yy=Symbol("quoteafterquote"),v7=Symbol("quoteinquote"),w7=class extends Bu{constructor(e,t){super();this.input=e,this.hasHeader=!0,this.fullColumnNames=null,this.columnNamesValidated=!1,this.columnConfigs=null,this.configuredColumnsOnly=!1,this.delimiter=",",this.delimWhitespace=!1,this.base=new x7(e),t||(t={}),this.hasHeader=t.hasHeader!==!1,this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(v.assert(t.delimiter==null,()=>"Delimiter should not be provided when delimWhitespace is true."),this.delimWhitespace=!0,this.delimiter=" "):this.delimiter=t.delimiter?t.delimiter:","}async columnNames(){return this.columnNamesValidated||await this.setColumnNames(),this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames}async setColumnNames(){let e=await this.maybeReadHeaderLine();if(!this.fullColumnNames&&!e)throw new Error("Column names must be provided if there is no header line.");this.fullColumnNames&&e&&v.assert(e.length===this.fullColumnNames.length,()=>"The length of provided columnNames ("+this.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+e.length.toString()+")."),this.fullColumnNames||(this.fullColumnNames=e);let t=this.fullColumnNames.reduce((s,r)=>(s[r]=s[r]+1||1,s),{}),n=Object.keys(t).filter(s=>t[s]>1);if(v.assert(n.length===0,()=>"Duplicate column names found: "+n.toString()),this.columnConfigs){for(let s of Object.keys(this.columnConfigs))if(this.fullColumnNames.indexOf(s)===-1)throw new Error('The key "'+s+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){let t=await(await this.base.iterator()).next();if(t.done)throw new Error("No data was found for CSV parsing.");let n=t.value;return this.parseRow(n,!1)}else return null}async iterator(){this.columnNamesValidated||await this.setColumnNames();let e=await this.base.iterator();return this.hasHeader&&(e=e.skip(1)),e.map(t=>this.makeDataElement(t))}makeDataElement(e){let t=this.parseRow(e),n={},s={};for(let r=0;r14||!Number.isInteger(t))throw new Error(`Invalid fftSize: it must be a power of 2 between 2 to 4 and 2 to 14, but got ${this.fftSize}`);if(this.numFrames=e.numFramesPerSpectrogram||43,this.sampleRateHz=e.sampleRateHz,this.columnTruncateLength=e.columnTruncateLength||this.fftSize,this.audioTrackConstraints=e.audioTrackConstraints,this.smoothingTimeConstant=e.smoothingTimeConstant||0,this.includeSpectrogram=e.includeSpectrogram!==!1,this.includeWaveform=e.includeWaveform===!0,!this.includeSpectrogram&&!this.includeWaveform)throw new Error("Both includeSpectrogram and includeWaveform are false. At least one type of data should be returned.")}summary(){return"microphone"}static async create(e={}){if(K().get("IS_NODE"))throw new Error("microphone API is only supported in browser environment.");let t=new k7(e);return await t.start(),t}async start(){try{this.stream=await navigator.mediaDevices.getUserMedia({audio:this.audioTrackConstraints==null?!0:this.audioTrackConstraints,video:!1})}catch(n){throw new Error(`Error thrown while initializing video stream: ${n.message}`)}if(!this.stream)throw new Error("Could not obtain audio from microphone.");let e=window.AudioContext||window.webkitAudioContext;if(this.audioContext=new e,!this.sampleRateHz)this.sampleRateHz=this.audioContext.sampleRate;else if(this.audioContext.sampleRate!==this.sampleRateHz)throw new Error(`Mismatch in sampling rate: Expected: ${this.sampleRateHz}; Actual: ${this.audioContext.sampleRate}`);let t=this.audioContext.createMediaStreamSource(this.stream);this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=this.fftSize*2,this.analyser.smoothingTimeConstant=this.smoothingTimeConstant,t.connect(this.analyser),this.freqData=new Float32Array(this.fftSize),this.timeData=new Float32Array(this.fftSize)}async next(){if(this.isClosed)return{value:null,done:!0};let e,t,n=await this.getAudioData();if(this.includeSpectrogram){let s=this.flattenQueue(n.freqDataQueue);e=this.getTensorFromAudioDataArray(s,[this.numFrames,this.columnTruncateLength,1])}if(this.includeWaveform){let s=this.flattenQueue(n.timeDataQueue);t=this.getTensorFromAudioDataArray(s,[this.numFrames*this.fftSize,1])}return{value:{spectrogram:e,waveform:t},done:!1}}async capture(){return(await this.next()).value}async getAudioData(){let e=[],t=[],n=0;return new Promise(s=>{let r=setInterval(()=>{this.includeSpectrogram&&(this.analyser.getFloatFrequencyData(this.freqData),this.freqData[0]===-1/0&&s({freqDataQueue:e,timeDataQueue:t}),e.push(this.freqData.slice(0,this.columnTruncateLength))),this.includeWaveform&&(this.analyser.getFloatTimeDomainData(this.timeData),t.push(this.timeData.slice())),++n===this.numFrames&&(clearInterval(r),s({freqDataQueue:e,timeDataQueue:t}))},this.fftSize/this.sampleRateHz*1e3)})}stop(){this.isClosed||(this.isClosed=!0,this.analyser.disconnect(),this.audioContext.close(),this.stream!=null&&this.stream.getTracks().length>0&&this.stream.getTracks()[0].stop())}toArray(){throw new Error("Can not convert infinite audio stream to array.")}getSampleRate(){return this.sampleRateHz}flattenQueue(e){let t=e[0].length,n=new Float32Array(e.length*t);return e.forEach((s,r)=>n.set(s,r*t)),n}getTensorFromAudioDataArray(e,t){let n=new Float32Array(v.sizeFromShape(t));return n.set(e,n.length-e.length),Gt(n,t)}},I7=class extends bn{constructor(e,t){super();if(this.webcamVideoElement=e,this.webcamConfig=t,this.isClosed=!0,this.resize=!1,this.needToResize())if(this.resize=!0,this.cropSize=[this.webcamConfig.resizeHeight,this.webcamConfig.resizeWidth],this.cropBoxInd=Zt([0],"int32"),this.webcamConfig.centerCrop){let n=this.webcamConfig.resizeWidth*1/this.webcamVideoElement.width,s=this.webcamConfig.resizeHeight*1/this.webcamVideoElement.height,r=(1-n)/2,a=(1-s)/2,o=r+n,i=s+a;this.cropBox=ur([a,r,i,o],[1,4])}else this.cropBox=ur([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(e,t={}){if(K().get("IS_NODE"))throw new Error("tf.data.webcam is only supported in browser environment.");if(!e){if(e=document.createElement("video"),!t.resizeWidth||!t.resizeHeight)throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");e.width=t.resizeWidth,e.height=t.resizeHeight}let n=new I7(e,t);return await n.start(),n}async start(){this.webcamConfig.facingMode&&v.assert(this.webcamConfig.facingMode==="user"||this.webcamConfig.facingMode==="environment",()=>`Invalid webcam facing mode: ${this.webcamConfig.facingMode}. Please provide 'user' or 'environment'`);try{this.stream=await navigator.mediaDevices.getUserMedia({video:{deviceId:this.webcamConfig.deviceId,facingMode:this.webcamConfig.facingMode?this.webcamConfig.facingMode:"user",width:this.webcamVideoElement.width,height:this.webcamVideoElement.height}})}catch(e){throw e.message=`Error thrown while initializing video stream: ${e.message}`,e}if(!this.stream)throw new Error("Could not obtain video from webcam.");try{this.webcamVideoElement.srcObject=this.stream}catch(e){console.log(e),this.webcamVideoElement.src=window.URL.createObjectURL(this.stream)}return this.webcamVideoElement.play(),this.isClosed=!1,new Promise(e=>{this.webcamVideoElement.onloadedmetadata=()=>{e()}})}async next(){if(this.isClosed)return{value:null,done:!0};let e;try{e=Gs.fromPixels(this.webcamVideoElement)}catch(t){throw new Error(`Error thrown converting video to pixels: ${JSON.stringify(t)}`)}if(this.resize)try{return{value:this.cropAndResizeFrame(e),done:!1}}catch(t){throw new Error(`Error thrown cropping the video: ${t.message}`)}finally{e.dispose()}else return{value:e,done:!1}}needToResize(){return!!(this.webcamConfig.resizeWidth&&this.webcamConfig.resizeHeight&&(this.webcamVideoElement.width!==this.webcamConfig.resizeWidth||this.webcamVideoElement.height!==this.webcamConfig.resizeHeight))}cropAndResizeFrame(e){return j(()=>{let t=Kt(he(e,"float32"),0),n;n=$e.cropAndResize(t,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");let s=n.shape;return G(n,s.slice(1))})}async capture(){return(await this.next()).value}stop(){this.stream.getTracks().forEach(t=>t.stop());try{this.webcamVideoElement.srcObject=null}catch(t){console.log(t),this.webcamVideoElement.src=null}this.isClosed=!0}toArray(){throw new Error("Can not convert infinite video stream to array.")}},S7=class{},C7=class extends bn{split(e){return new JU(this,e)}},JU=class extends C7{constructor(e,t){super();this.upstream=e,this.impl=new QU(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},QU=class extends Ay{constructor(e,t){super();this.upstream=e,this.separator=t,this.carryover=""}summary(){return`${this.upstream.summary()} -> Split('${this.separator}')`}async pump(){let e=await this.upstream.next();if(e.done)return this.carryover===""?!1:(this.outputQueue.push(this.carryover),this.carryover="",!0);let t=e.value.split(this.separator);t[0]=this.carryover+t[0];for(let n of t.slice(0,-1))this.outputQueue.push(n);return this.carryover=t[t.length-1],!0}},eG=class extends bn{decodeUTF8(){return new tG(this)}},tG=class extends C7{constructor(e){super();this.upstream=e,this.impl=new nG(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},nG=class extends Ay{constructor(e){super();if(this.upstream=e,K().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{let{StringDecoder:t}=t5();this.decoder=new t("utf8")}}summary(){return`${this.upstream.summary()} -> Utf8`}async pump(){let e=await this.upstream.next(),t;if(e.done)return!1;t=e.value;let n;return K().get("IS_BROWSER")?n=this.decoder.decode(t,{stream:!0}):n=this.decoder.write(Buffer.from(t.buffer)),this.outputQueue.push(n),!0}},T7=class extends eG{constructor(e,t={}){super();this.file=e,this.options=t,v.assert(e instanceof Uint8Array||(K().get("IS_BROWSER")?e instanceof File||e instanceof Blob:!1),()=>"FileChunkIterator only supports File, Blob and Uint8Array right now."),this.offset=t.offset||0,this.chunkSize=t.chunkSize||1024*1024}summary(){return`FileChunks ${this.file}`}async next(){return this.offset>=(this.file instanceof Uint8Array?this.file.byteLength:this.file.size)?{value:null,done:!0}:{value:await new Promise((t,n)=>{let s=this.offset+this.chunkSize;if(this.file instanceof Uint8Array)t(new Uint8Array(this.file.slice(this.offset,s)));else{let r=new FileReader;r.onload=o=>{let i=r.result;if(i instanceof ArrayBuffer&&(i=new Uint8Array(i)),!(i instanceof Uint8Array))return n(new TypeError("FileReader returned unknown type."));t(i)},r.onabort=o=>n(new Error("Aborted")),r.onerror=o=>n(new Error(o.type));let a=this.file.slice(this.offset,s);r.readAsArrayBuffer(a)}this.offset=s}),done:!1}}};async function sG(e,t={},n){let s,r;typeof e=="string"?s=e:(s=e.url,r=rG(e));let a=await(n||v.fetch)(s,r);if(a.ok){let o=new Uint8Array(await a.arrayBuffer());return new T7(o,t)}else throw new Error(a.statusText)}var rG=e=>({method:e.method,headers:e.headers,body:e.body,mode:e.mode,credentials:e.credentials,cache:e.cache,redirect:e.redirect,referrer:e.referrer,integrity:e.integrity});function N7(e){return typeof e=="string"&&e.substr(0,7)==="file://"}var E7=class extends S7{constructor(e,t={}){super();this.input=e,this.options=t}async iterator(){if(N7(this.input)&&K().get("IS_NODE")){let e=Ws("fs");this.input=e.readFileSync(this.input.substr(7))}return new T7(this.input,this.options)}},R7=class extends S7{constructor(e,t={}){super();this.url=e,this.fileOptions=t}async iterator(){return N7(this.url)?new E7(this.url,this.fileOptions).iterator():sG(this.url,this.fileOptions)}};function aG(e,t={}){return new w7(new R7(e),t)}function oG(e){let t=gy(e);return ys(async()=>t)}function iG(e){return ys(async()=>{let t=await e();return gy(()=>t.next())})}async function lG(e,t){return I7.create(e,t)}async function uG(e){return k7.create(e)}var cG="0.0.0";function Ne(e,t){Array.isArray(e)||(e=[e]),e.forEach(n=>{n!=null&&v.assert(n.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the CPU backend.`)})}var dG=Xs.whereImpl,$7=class extends Ll{constructor(){super();this.blockSize=48,this.firstUse=!0,this.data=new Dc(this,ss())}nextDataId(){return $7.nextDataId++}write(e,t,n){this.firstUse&&(this.firstUse=!1,K().get("IS_NODE")&&N.warn(` ============================ Hi there \u{1F44B}. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details. -============================`));let s={id:this.nextDataId()};return this.data.set(s,{values:e,dtype:n,refCount:1}),s}makeTensorInfo(e,t,n){let s;if(t==="string"&&n!=null&&n.length>0&&v.isString(n[0])){let r=n.map(a=>v.encodeString(a));s=this.write(r,e,t)}else s=this.write(n,e,t);return{dataId:s,shape:e,dtype:t}}refCount(e){return this.data.has(e)?this.data.get(e).refCount:0}incRef(e){let t=this.data.get(e);t.refCount++}decRef(e){if(this.data.has(e)){let t=this.data.get(e);t.refCount--}}move(e,t,n,s,r){this.data.set(e,{values:t,dtype:s,refCount:r})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){let{dtype:t,complexTensorInfos:n}=this.data.get(e);if(t==="complex64"){let s=this.readSync(n.real.dataId),r=this.readSync(n.imag.dataId);return N.mergeRealAndImagArrays(s,r)}return this.data.get(e).values}bufferSync(e){let t=this.readSync(e.dataId),n=t;if(e.dtype==="string")try{n=t.map(s=>v.decodeString(s))}catch(s){throw new Error("Failed to decode encoded string bytes into utf-8")}return Le(e.shape,e.dtype,n)}makeOutput(e,t,n){let s=this.write(e,t,n);return ss().makeTensorFromDataId(s,t,n,this)}disposeData(e,t=!1){if(this.data.has(e)){if(this.data.get(e).refCount--,!t&&this.data.get(e).refCount>0)return!1;let{complexTensorInfos:n}=this.data.get(e);n!=null&&(this.disposeData(n.real.dataId,!0),this.disposeData(n.imag.dataId,!0)),this.data.delete(e)}return!0}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}async time(e){let t=v.now();return e(),{kernelMs:v.now()-t}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}where(e){Ne([e],"where");let t=this.readSync(e.dataId);return dG(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}},xy=$7;xy.nextDataId=0;var om={};ze(om,{addImpl:()=>_7,bincountImpl:()=>vy,bincountReduceImpl:()=>P7,ceilImpl:()=>F7,concatImpl:()=>wy,equalImpl:()=>O7,expImpl:()=>z7,expm1Impl:()=>B7,floorImpl:()=>W7,gatherNdImpl:()=>V7,gatherV2Impl:()=>U7,greaterEqualImpl:()=>H7,greaterImpl:()=>G7,lessEqualImpl:()=>q7,lessImpl:()=>j7,linSpaceImpl:()=>X7,logImpl:()=>K7,maxImpl:()=>Z7,maximumImpl:()=>Y7,minimumImpl:()=>J7,multiplyImpl:()=>ky,negImpl:()=>Q7,notEqualImpl:()=>eI,prodImpl:()=>tI,rangeImpl:()=>Sy,rsqrtImpl:()=>nI,sigmoidImpl:()=>QG,simpleAbsImpl:()=>D7,sliceImpl:()=>um,sparseFillEmptyRowsImpl:()=>rI,sparseReshapeImpl:()=>aI,sparseSegmentReductionImpl:()=>Cy,sqrtImpl:()=>nH,squaredDifferenceImpl:()=>oI,stridedSliceImpl:()=>iI,stringNGramsImpl:()=>lI,stringSplitImpl:()=>uI,stringToHashBucketFastImpl:()=>cI,subImpl:()=>dI,tileImpl:()=>pI,topKImpl:()=>fI,transposeImpl:()=>Iy,uniqueImpl:()=>mI});function D7(e){let t=new Float32Array(e.length);for(let n=0;n{let{x:t}=e.inputs,n=e.backend;Ne(t,"abs");let s=new Float32Array(v.sizeFromShape(t.shape)),r=n.data.get(t.dataId).values;return s=D7(r),n.makeOutput(s,t.shape,t.dtype)},hG={kernelName:ni,backendName:"cpu",kernelFunc:pG};function Jt(e){return(t,n,s,r,a)=>{let o=N.assertAndGetBroadcastShape(t,n),i=o.length,l=v.computeStrides(o),c=v.sizeFromShape(o),u=v.getTypedArrayFromDType(a,c),d=t.length,p=n.length,h=v.computeStrides(t),f=v.computeStrides(n),m=N.getBroadcastDims(t,o),g=N.getBroadcastDims(n,o);if(m.length+g.length===0)for(let A=0;Ax[S]=0);let b=v.locToIndex(x,d,h),w=y.slice(-p);g.forEach(S=>w[S]=0);let k=v.locToIndex(w,p,f);u[A]=e(s[b],r[k])}return[u,o]}}function xs(e){let{inputs:t,backend:n}=e,{real:s,imag:r}=t,a=n.data.get(s.dataId).values,o=n.data.get(r.dataId).values,i=n.makeTensorInfo(s.shape,"complex64"),l=n.data.get(i.dataId);return l.complexTensorInfos={real:n.makeTensorInfo(s.shape,"float32",a),imag:n.makeTensorInfo(r.shape,"float32",o)},i}var fG={kernelName:Oc,backendName:"cpu",kernelFunc:xs};function im(e,t,n="float32"){if(n==="complex64"){let r=im(e,t,"float32"),a=im(e,t,"float32");return xs({inputs:{real:r,imag:a},backend:e})}let s=v.makeZerosTypedArray(v.sizeFromShape(t),n);return e.makeTensorInfo(t,n,s)}function Or(e){let{inputs:t,backend:n}=e,{x:s}=t;return n.incRef(s.dataId),{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}var mG={kernelName:Ba,backendName:"cpu",kernelFunc:Or};function dl(e){let{inputs:t,backend:n}=e,{input:s}=t,r=n.data.get(s.dataId).complexTensorInfos.real,a=n.data.get(r.dataId).values;return n.makeTensorInfo(r.shape,r.dtype,a)}var gG={kernelName:Hc,backendName:"cpu",kernelFunc:dl};function _o(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{dtype:a}=s;if(a==="complex64"){if(r.dtype==="complex64")return Or({inputs:{x:r},backend:n});let o=im(n,r.shape,r.dtype),i=_o({inputs:{x:r},backend:n,attrs:{dtype:"float32"}}),l=xs({inputs:{real:i,imag:o},backend:n});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(i),l}if(r.dtype==="complex64"){let o=dl({inputs:{input:r},backend:n}),i=_o({inputs:{x:o},backend:n,attrs:{dtype:a}});return n.disposeIntermediateTensorInfo(o),i}if(!v.hasEncodingLoss(r.dtype,a)){let o=Or({inputs:{x:r},backend:n});return{dataId:o.dataId,shape:o.shape,dtype:a}}if(a==="int32"){let o=n.data.get(r.dataId).values,i=Int32Array.from(o);return n.makeTensorInfo(r.shape,"int32",i)}if(a==="bool"){let o=n.data.get(r.dataId).values,i=v.toTypedArray([0],r.dtype),[l,c]=Jt((u,d)=>u!==d?1:0)(r.shape,[],o,i,"bool");return n.makeTensorInfo(c,"bool",l)}throw new Error(`Error in Cast: failed to cast ${r.dtype} to ${a}`)}var AG={kernelName:Ca,backendName:"cpu",kernelFunc:_o};function vn(e,t,n,s){return n==null?({inputs:r,backend:a})=>{let{a:o,b:i}=r,l=a;Ne([o,i],e);let c=l.data.get(o.dataId).values,u=l.data.get(i.dataId).values,d=o.dtype==="string"?N.fromUint8ToStringArray(c):c,p=o.dtype==="string"?N.fromUint8ToStringArray(u):u,h=s||o.dtype,[f,m]=t(o.shape,i.shape,d,p,h);return l.makeTensorInfo(m,h,f)}:({inputs:r,backend:a})=>{let{a:o,b:i}=r,l=a;if(o.dtype==="complex64"||i.dtype==="complex64"){let c=_o({inputs:{x:o},backend:l,attrs:{dtype:"complex64"}}),u=l.data.get(c.dataId),d=u.complexTensorInfos.real,p=u.complexTensorInfos.imag,h=l.data.get(d.dataId).values,f=l.data.get(p.dataId).values,m=_o({inputs:{x:i},backend:l,attrs:{dtype:"complex64"}}),g=l.data.get(m.dataId),A=g.complexTensorInfos.real,y=g.complexTensorInfos.imag,x=l.data.get(A.dataId).values,b=l.data.get(y.dataId).values,[w,k,S]=n(o.shape,i.shape,h,f,x,b),E=l.makeTensorInfo(S,"float32",w),P=l.makeTensorInfo(S,"float32",k),F=xs({inputs:{real:E,imag:P},backend:l});return l.disposeIntermediateTensorInfo(c),l.disposeIntermediateTensorInfo(m),l.disposeIntermediateTensorInfo(E),l.disposeIntermediateTensorInfo(P),F}else{let c=l.data.get(o.dataId).values,u=l.data.get(i.dataId).values,d=s||o.dtype,[p,h]=t(o.shape,i.shape,c,u,d);return l.makeTensorInfo(h,d,p)}}}function by(e){return(t,n,s,r,a,o)=>{let i=N.assertAndGetBroadcastShape(t,n),l=v.sizeFromShape(i),c=i.length,u=v.computeStrides(i),d=v.getTypedArrayFromDType("float32",l),p=v.getTypedArrayFromDType("float32",l),h=N.getBroadcastDims(t,i),f=N.getBroadcastDims(n,i),m=N.mergeRealAndImagArrays(s,r),g=N.mergeRealAndImagArrays(a,o),A=t.length,y=v.computeStrides(t),x=n.length,b=v.computeStrides(n);if(h.length+f.length===0)for(let w=0;wS[_]=0);let E=v.locToIndex(S,A,y),P=k.slice(-x);f.forEach(_=>P[_]=0);let F=v.locToIndex(P,x,b),R=e(m[E*2],m[E*2+1],g[F*2],g[F*2+1]);d[w]=R.real,p[w]=R.imag}return[d,p,i]}}var _7=Jt((e,t)=>e+t),yG=by((e,t,n,s)=>({real:e+n,imag:t+s})),Ld=vn(Hr,_7,yG),xG={kernelName:Hr,backendName:"cpu",kernelFunc:Ld};function vy(e,t,n,s,r){let a=v.sizeFromShape(s),o=v.makeZerosTypedArray(r,n);for(let i=0;i=r||(a>0?o[l]+=t[i]:o[l]+=1)}return o}function P7(e,t,n,s=!1){let r=e.shape[0],a=e.shape[1],o=Le([r,n],t.dtype);for(let i=0;i=n||(s?o.set(1,i,c):t.size>0?o.set(o.get(i,c)+t.get(i,l),i,c):o.set(o.get(i,c)+1,i,c))}return o}function Po(e){return(t,n,s)=>{let r=v.getTypedArrayFromDType(n,t.length);for(let a=0;a{let{x:o}=s;if(Ne(o,e),o.dtype==="string"||n==="string")throw new Error("unaryKernelFunc does not support string input/output");let i=a,l=i.data.get(o.dataId).values,c=v.sizeFromShape(o.shape),u=n||o.dtype,d=v.getArrayFromDType(u,c);for(let p=0;p{let{x:o}=s;if(Ne(o,e),o.dtype==="string"||n==="string")throw new Error("unaryKernelFunc does not support string input/output");let i=a,l=i.data.get(o.dataId).values,c=n||o.dtype,u=t(l,c,r);return i.makeTensorInfo(o.shape,c,u)}}var F7=Po(e=>Math.ceil(e)),bG=Wu(Ta,F7),vG={kernelName:Ta,backendName:"cpu",kernelFunc:bG};function wy(e,t,n,s){let r=v.getArrayFromDType(n,v.sizeFromShape(t));if(s&&n!=="string"){let a=0;e.forEach(o=>{let i=v.sizeFromShape(o.shape);r.set(o.vals,a),a+=i})}else{let a=0;e.forEach(o=>{let i=n==="string"?N.fromUint8ToStringArray(o.vals):o.vals,l=0;for(let c=0;ce===t?1:0),M7=vn(li,O7,null,"bool"),wG={kernelName:li,backendName:"cpu",kernelFunc:M7},z7=Po(e=>Math.exp(e)),L7=Wu(Fa,z7,"float32"),kG={kernelName:Fa,backendName:"cpu",kernelFunc:L7},B7=Po(e=>Math.expm1(e)),IG=Wu(ci,B7),SG={kernelName:ci,backendName:"cpu",kernelFunc:IG},W7=Po(e=>Math.floor(e)),CG=Wu(Oa,W7),TG={kernelName:Oa,backendName:"cpu",kernelFunc:CG};function V7(e,t,n,s,r,a,o,i,l){let c=Le([s,a],n);for(let u=0;u=l/a)throw new Error(`Invalid indices: ${d} does not index into ${i}`);for(let h=0;he>t?1:0),NG=vn(fi,G7,null,"bool"),EG={kernelName:fi,backendName:"cpu",kernelFunc:NG},H7=Jt((e,t)=>e>=t?1:0),RG=vn(La,H7,null,"bool"),$G={kernelName:La,backendName:"cpu",kernelFunc:RG},j7=Jt((e,t)=>ee<=t?1:0),PG=vn(Ai,q7,null,"bool"),FG={kernelName:Ai,backendName:"cpu",kernelFunc:PG};function X7(e,t,n){let s=(t-e)/(n-1),r=v.makeZerosTypedArray(n,"float32");r[0]=e;for(let a=1;aMath.log(e)),OG=Wu(Wa,K7),MG={kernelName:Wa,backendName:"cpu",kernelFunc:OG};function Z7(e,t,n,s){let r=v.getTypedArrayFromDType(s,v.sizeFromShape(n));for(let a=0;ai)&&(i=c)}r[a]=i}return r}var Y7=Jt((e,t)=>Math.max(e,t)),zG=vn(Ua,Y7),LG={kernelName:Ua,backendName:"cpu",kernelFunc:zG},J7=Jt((e,t)=>Math.min(e,t)),BG=vn(qa,J7),WG={kernelName:qa,backendName:"cpu",kernelFunc:BG},ky=Jt((e,t)=>e*t),VG=by((e,t,n,s)=>({real:e*n-t*s,imag:e*s+t*n})),lm=vn(Ka,ky,VG),UG={kernelName:Ka,backendName:"cpu",kernelFunc:lm};function Q7(e,t,n){let s=v.createScalarValue(-1,n);return ky([],t,s,e,n)}function GG(e){let{inputs:t,backend:n}=e,{x:s}=t;Ne(s,"neg");let r=n.data.get(s.dataId).values,[a,o]=Q7(r,s.shape,s.dtype);return n.makeTensorInfo(o,s.dtype,a)}var HG={kernelName:xi,backendName:"cpu",kernelFunc:GG},eI=Jt((e,t)=>e!==t?1:0),jG=vn(bi,eI,null,"bool"),qG={kernelName:bi,backendName:"cpu",kernelFunc:jG};function Iy(e,t,n,s,r){let a=t.length,o=v.sizeFromShape(t),i=v.computeStrides(t),l=v.computeStrides(r),c=v.getTypedArrayFromDType(n,v.sizeFromShape(r));for(let u=0;un.disposeIntermediateTensorInfo(y)),n.makeTensorInfo(A,g,f)}var ZG={kernelName:Ci,backendName:"cpu",kernelFunc:KG};function Sy(e,t,n,s){let r=e===t,a=e1;if(r||a||o)return v.makeZerosTypedArray(0,s);let i=Math.abs(Math.ceil((t-e)/n)),l=v.makeZerosTypedArray(i,s);t1/Math.sqrt(e)),YG=Wu(no,nI),JG={kernelName:no,backendName:"cpu",kernelFunc:YG},QG=Po(e=>1/(1+Math.exp(-e))),sI=gt(ro,e=>1/(1+Math.exp(-e))),eH={kernelName:ro,backendName:"cpu",kernelFunc:sI};function um(e,t,n,s,r){let a=An.isSliceContinous(s,t,n),o=v.sizeFromShape(n),i=v.computeStrides(s);if(a){let d=An.computeFlatOffset(t,i);return r==="string"?e.slice(d,d+o):e.subarray(d,d+o)}let l=r==="string"?N.fromUint8ToStringArray(e):e,c=Le(s,r,l),u=Le(n,r);for(let d=0;df+t[m]);u.set(c.get(...h),...p)}return r==="string"?N.fromStringArrayToUint8(u.values):u.values}function pl(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,size:o}=s;Ne(r,"slice");let[i,l]=An.parseSliceParams(r,a,o);An.assertParamsValid(r,i,l);let c=n.data.get(r.dataId).values,u=um(c,i,l,r.shape,r.dtype);return n.makeTensorInfo(l,r.dtype,u)}var tH={kernelName:Di,backendName:"cpu",kernelFunc:pl};function rI(e,t,n,s,r,a,o){let i=t[0],l=a[0],c=new Array(l),u=new Array(i),d=t[1];if(l===0){if(i!==0)throw new Error(`Received SparseTensor with denseShape[0] = 0 but +============================`));let s={id:this.nextDataId()};return this.data.set(s,{values:e,dtype:n,refCount:1}),s}makeTensorInfo(e,t,n){let s;if(t==="string"&&n!=null&&n.length>0&&v.isString(n[0])){let r=n.map(a=>v.encodeString(a));s=this.write(r,e,t)}else s=this.write(n,e,t);return{dataId:s,shape:e,dtype:t}}refCount(e){return this.data.has(e)?this.data.get(e).refCount:0}incRef(e){let t=this.data.get(e);t.refCount++}decRef(e){if(this.data.has(e)){let t=this.data.get(e);t.refCount--}}move(e,t,n,s,r){this.data.set(e,{values:t,dtype:s,refCount:r})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){let{dtype:t,complexTensorInfos:n}=this.data.get(e);if(t==="complex64"){let s=this.readSync(n.real.dataId),r=this.readSync(n.imag.dataId);return N.mergeRealAndImagArrays(s,r)}return this.data.get(e).values}bufferSync(e){let t=this.readSync(e.dataId),n=t;if(e.dtype==="string")try{n=t.map(s=>v.decodeString(s))}catch(s){throw new Error("Failed to decode encoded string bytes into utf-8")}return Le(e.shape,e.dtype,n)}makeOutput(e,t,n){let s=this.write(e,t,n);return ss().makeTensorFromDataId(s,t,n,this)}disposeData(e,t=!1){if(this.data.has(e)){if(this.data.get(e).refCount--,!t&&this.data.get(e).refCount>0)return!1;let{complexTensorInfos:n}=this.data.get(e);n!=null&&(this.disposeData(n.real.dataId,!0),this.disposeData(n.imag.dataId,!0)),this.data.delete(e)}return!0}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}async time(e){let t=v.now();return e(),{kernelMs:v.now()-t}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}where(e){Ne([e],"where");let t=this.readSync(e.dataId);return dG(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}},xy=$7;xy.nextDataId=0;var om={};ze(om,{addImpl:()=>_7,bincountImpl:()=>vy,bincountReduceImpl:()=>P7,ceilImpl:()=>F7,concatImpl:()=>wy,equalImpl:()=>O7,expImpl:()=>z7,expm1Impl:()=>B7,floorImpl:()=>W7,gatherNdImpl:()=>V7,gatherV2Impl:()=>U7,greaterEqualImpl:()=>H7,greaterImpl:()=>G7,lessEqualImpl:()=>q7,lessImpl:()=>j7,linSpaceImpl:()=>X7,logImpl:()=>K7,maxImpl:()=>Z7,maximumImpl:()=>Y7,minimumImpl:()=>J7,multiplyImpl:()=>ky,negImpl:()=>Q7,notEqualImpl:()=>eI,prodImpl:()=>tI,rangeImpl:()=>Sy,rsqrtImpl:()=>nI,sigmoidImpl:()=>QG,simpleAbsImpl:()=>D7,sliceImpl:()=>um,sparseFillEmptyRowsImpl:()=>rI,sparseReshapeImpl:()=>aI,sparseSegmentReductionImpl:()=>Cy,sqrtImpl:()=>nH,squaredDifferenceImpl:()=>oI,stridedSliceImpl:()=>iI,stringNGramsImpl:()=>lI,stringSplitImpl:()=>uI,stringToHashBucketFastImpl:()=>cI,subImpl:()=>dI,tileImpl:()=>pI,topKImpl:()=>fI,transposeImpl:()=>Iy,uniqueImpl:()=>mI});function D7(e){let t=new Float32Array(e.length);for(let n=0;n{let{x:t}=e.inputs,n=e.backend;Ne(t,"abs");let s=new Float32Array(v.sizeFromShape(t.shape)),r=n.data.get(t.dataId).values;return s=D7(r),n.makeOutput(s,t.shape,t.dtype)},hG={kernelName:ni,backendName:"cpu",kernelFunc:pG};function Jt(e){return(t,n,s,r,a)=>{let o=N.assertAndGetBroadcastShape(t,n),i=o.length,l=v.computeStrides(o),c=v.sizeFromShape(o),u=v.getTypedArrayFromDType(a,c),d=t.length,p=n.length,h=v.computeStrides(t),f=v.computeStrides(n),m=N.getBroadcastDims(t,o),g=N.getBroadcastDims(n,o);if(m.length+g.length===0)for(let A=0;Ax[S]=0);let b=v.locToIndex(x,d,h),w=y.slice(-p);g.forEach(S=>w[S]=0);let k=v.locToIndex(w,p,f);u[A]=e(s[b],r[k])}return[u,o]}}function xs(e){let{inputs:t,backend:n}=e,{real:s,imag:r}=t,a=n.data.get(s.dataId).values,o=n.data.get(r.dataId).values,i=n.makeTensorInfo(s.shape,"complex64"),l=n.data.get(i.dataId);return l.complexTensorInfos={real:n.makeTensorInfo(s.shape,"float32",a),imag:n.makeTensorInfo(r.shape,"float32",o)},i}var fG={kernelName:Oc,backendName:"cpu",kernelFunc:xs};function im(e,t,n="float32"){if(n==="complex64"){let r=im(e,t,"float32"),a=im(e,t,"float32");return xs({inputs:{real:r,imag:a},backend:e})}let s=v.makeZerosTypedArray(v.sizeFromShape(t),n);return e.makeTensorInfo(t,n,s)}function Or(e){let{inputs:t,backend:n}=e,{x:s}=t;return n.incRef(s.dataId),{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}var mG={kernelName:Ba,backendName:"cpu",kernelFunc:Or};function dl(e){let{inputs:t,backend:n}=e,{input:s}=t,r=n.data.get(s.dataId).complexTensorInfos.real,a=n.data.get(r.dataId).values;return n.makeTensorInfo(r.shape,r.dtype,a)}var gG={kernelName:Hc,backendName:"cpu",kernelFunc:dl};function _o(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{dtype:a}=s;if(a==="complex64"){if(r.dtype==="complex64")return Or({inputs:{x:r},backend:n});let o=im(n,r.shape,r.dtype),i=_o({inputs:{x:r},backend:n,attrs:{dtype:"float32"}}),l=xs({inputs:{real:i,imag:o},backend:n});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(i),l}if(r.dtype==="complex64"){let o=dl({inputs:{input:r},backend:n}),i=_o({inputs:{x:o},backend:n,attrs:{dtype:a}});return n.disposeIntermediateTensorInfo(o),i}if(!v.hasEncodingLoss(r.dtype,a)){let o=Or({inputs:{x:r},backend:n});return{dataId:o.dataId,shape:o.shape,dtype:a}}if(a==="int32"){let o=n.data.get(r.dataId).values,i=Int32Array.from(o);return n.makeTensorInfo(r.shape,"int32",i)}if(a==="bool"){let o=n.data.get(r.dataId).values,i=v.toTypedArray([0],r.dtype),[l,c]=Jt((u,d)=>u!==d?1:0)(r.shape,[],o,i,"bool");return n.makeTensorInfo(c,"bool",l)}throw new Error(`Error in Cast: failed to cast ${r.dtype} to ${a}`)}var AG={kernelName:Ca,backendName:"cpu",kernelFunc:_o};function vn(e,t,n,s){return n==null?({inputs:r,backend:a})=>{let{a:o,b:i}=r,l=a;Ne([o,i],e);let c=l.data.get(o.dataId).values,u=l.data.get(i.dataId).values,d=o.dtype==="string"?N.fromUint8ToStringArray(c):c,p=o.dtype==="string"?N.fromUint8ToStringArray(u):u,h=s||o.dtype,[f,m]=t(o.shape,i.shape,d,p,h);return l.makeTensorInfo(m,h,f)}:({inputs:r,backend:a})=>{let{a:o,b:i}=r,l=a;if(o.dtype==="complex64"||i.dtype==="complex64"){let c=_o({inputs:{x:o},backend:l,attrs:{dtype:"complex64"}}),u=l.data.get(c.dataId),d=u.complexTensorInfos.real,p=u.complexTensorInfos.imag,h=l.data.get(d.dataId).values,f=l.data.get(p.dataId).values,m=_o({inputs:{x:i},backend:l,attrs:{dtype:"complex64"}}),g=l.data.get(m.dataId),A=g.complexTensorInfos.real,y=g.complexTensorInfos.imag,x=l.data.get(A.dataId).values,b=l.data.get(y.dataId).values,[w,k,S]=n(o.shape,i.shape,h,f,x,b),E=l.makeTensorInfo(S,"float32",w),$=l.makeTensorInfo(S,"float32",k),F=xs({inputs:{real:E,imag:$},backend:l});return l.disposeIntermediateTensorInfo(c),l.disposeIntermediateTensorInfo(m),l.disposeIntermediateTensorInfo(E),l.disposeIntermediateTensorInfo($),F}else{let c=l.data.get(o.dataId).values,u=l.data.get(i.dataId).values,d=s||o.dtype,[p,h]=t(o.shape,i.shape,c,u,d);return l.makeTensorInfo(h,d,p)}}}function by(e){return(t,n,s,r,a,o)=>{let i=N.assertAndGetBroadcastShape(t,n),l=v.sizeFromShape(i),c=i.length,u=v.computeStrides(i),d=v.getTypedArrayFromDType("float32",l),p=v.getTypedArrayFromDType("float32",l),h=N.getBroadcastDims(t,i),f=N.getBroadcastDims(n,i),m=N.mergeRealAndImagArrays(s,r),g=N.mergeRealAndImagArrays(a,o),A=t.length,y=v.computeStrides(t),x=n.length,b=v.computeStrides(n);if(h.length+f.length===0)for(let w=0;wS[P]=0);let E=v.locToIndex(S,A,y),$=k.slice(-x);f.forEach(P=>$[P]=0);let F=v.locToIndex($,x,b),R=e(m[E*2],m[E*2+1],g[F*2],g[F*2+1]);d[w]=R.real,p[w]=R.imag}return[d,p,i]}}var _7=Jt((e,t)=>e+t),yG=by((e,t,n,s)=>({real:e+n,imag:t+s})),Ld=vn(Hr,_7,yG),xG={kernelName:Hr,backendName:"cpu",kernelFunc:Ld};function vy(e,t,n,s,r){let a=v.sizeFromShape(s),o=v.makeZerosTypedArray(r,n);for(let i=0;i=r||(a>0?o[l]+=t[i]:o[l]+=1)}return o}function P7(e,t,n,s=!1){let r=e.shape[0],a=e.shape[1],o=Le([r,n],t.dtype);for(let i=0;i=n||(s?o.set(1,i,c):t.size>0?o.set(o.get(i,c)+t.get(i,l),i,c):o.set(o.get(i,c)+1,i,c))}return o}function Po(e){return(t,n,s)=>{let r=v.getTypedArrayFromDType(n,t.length);for(let a=0;a{let{x:o}=s;if(Ne(o,e),o.dtype==="string"||n==="string")throw new Error("unaryKernelFunc does not support string input/output");let i=a,l=i.data.get(o.dataId).values,c=v.sizeFromShape(o.shape),u=n||o.dtype,d=v.getArrayFromDType(u,c);for(let p=0;p{let{x:o}=s;if(Ne(o,e),o.dtype==="string"||n==="string")throw new Error("unaryKernelFunc does not support string input/output");let i=a,l=i.data.get(o.dataId).values,c=n||o.dtype,u=t(l,c,r);return i.makeTensorInfo(o.shape,c,u)}}var F7=Po(e=>Math.ceil(e)),bG=Wu(Ta,F7),vG={kernelName:Ta,backendName:"cpu",kernelFunc:bG};function wy(e,t,n,s){let r=v.getArrayFromDType(n,v.sizeFromShape(t));if(s&&n!=="string"){let a=0;e.forEach(o=>{let i=v.sizeFromShape(o.shape);r.set(o.vals,a),a+=i})}else{let a=0;e.forEach(o=>{let i=n==="string"?N.fromUint8ToStringArray(o.vals):o.vals,l=0;for(let c=0;ce===t?1:0),M7=vn(li,O7,null,"bool"),wG={kernelName:li,backendName:"cpu",kernelFunc:M7},z7=Po(e=>Math.exp(e)),L7=Wu(Fa,z7,"float32"),kG={kernelName:Fa,backendName:"cpu",kernelFunc:L7},B7=Po(e=>Math.expm1(e)),IG=Wu(ci,B7),SG={kernelName:ci,backendName:"cpu",kernelFunc:IG},W7=Po(e=>Math.floor(e)),CG=Wu(Oa,W7),TG={kernelName:Oa,backendName:"cpu",kernelFunc:CG};function V7(e,t,n,s,r,a,o,i,l){let c=Le([s,a],n);for(let u=0;u=l/a)throw new Error(`Invalid indices: ${d} does not index into ${i}`);for(let h=0;he>t?1:0),NG=vn(fi,G7,null,"bool"),EG={kernelName:fi,backendName:"cpu",kernelFunc:NG},H7=Jt((e,t)=>e>=t?1:0),RG=vn(La,H7,null,"bool"),$G={kernelName:La,backendName:"cpu",kernelFunc:RG},j7=Jt((e,t)=>ee<=t?1:0),PG=vn(Ai,q7,null,"bool"),FG={kernelName:Ai,backendName:"cpu",kernelFunc:PG};function X7(e,t,n){let s=(t-e)/(n-1),r=v.makeZerosTypedArray(n,"float32");r[0]=e;for(let a=1;aMath.log(e)),OG=Wu(Wa,K7),MG={kernelName:Wa,backendName:"cpu",kernelFunc:OG};function Z7(e,t,n,s){let r=v.getTypedArrayFromDType(s,v.sizeFromShape(n));for(let a=0;ai)&&(i=c)}r[a]=i}return r}var Y7=Jt((e,t)=>Math.max(e,t)),zG=vn(Ua,Y7),LG={kernelName:Ua,backendName:"cpu",kernelFunc:zG},J7=Jt((e,t)=>Math.min(e,t)),BG=vn(qa,J7),WG={kernelName:qa,backendName:"cpu",kernelFunc:BG},ky=Jt((e,t)=>e*t),VG=by((e,t,n,s)=>({real:e*n-t*s,imag:e*s+t*n})),lm=vn(Ka,ky,VG),UG={kernelName:Ka,backendName:"cpu",kernelFunc:lm};function Q7(e,t,n){let s=v.createScalarValue(-1,n);return ky([],t,s,e,n)}function GG(e){let{inputs:t,backend:n}=e,{x:s}=t;Ne(s,"neg");let r=n.data.get(s.dataId).values,[a,o]=Q7(r,s.shape,s.dtype);return n.makeTensorInfo(o,s.dtype,a)}var HG={kernelName:xi,backendName:"cpu",kernelFunc:GG},eI=Jt((e,t)=>e!==t?1:0),jG=vn(bi,eI,null,"bool"),qG={kernelName:bi,backendName:"cpu",kernelFunc:jG};function Iy(e,t,n,s,r){let a=t.length,o=v.sizeFromShape(t),i=v.computeStrides(t),l=v.computeStrides(r),c=v.getTypedArrayFromDType(n,v.sizeFromShape(r));for(let u=0;un.disposeIntermediateTensorInfo(y)),n.makeTensorInfo(A,g,f)}var ZG={kernelName:Ci,backendName:"cpu",kernelFunc:KG};function Sy(e,t,n,s){let r=e===t,a=e1;if(r||a||o)return v.makeZerosTypedArray(0,s);let i=Math.abs(Math.ceil((t-e)/n)),l=v.makeZerosTypedArray(i,s);t1/Math.sqrt(e)),YG=Wu(no,nI),JG={kernelName:no,backendName:"cpu",kernelFunc:YG},QG=Po(e=>1/(1+Math.exp(-e))),sI=gt(ro,e=>1/(1+Math.exp(-e))),eH={kernelName:ro,backendName:"cpu",kernelFunc:sI};function um(e,t,n,s,r){let a=An.isSliceContinous(s,t,n),o=v.sizeFromShape(n),i=v.computeStrides(s);if(a){let d=An.computeFlatOffset(t,i);return r==="string"?e.slice(d,d+o):e.subarray(d,d+o)}let l=r==="string"?N.fromUint8ToStringArray(e):e,c=Le(s,r,l),u=Le(n,r);for(let d=0;df+t[m]);u.set(c.get(...h),...p)}return r==="string"?N.fromStringArrayToUint8(u.values):u.values}function pl(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,size:o}=s;Ne(r,"slice");let[i,l]=An.parseSliceParams(r,a,o);An.assertParamsValid(r,i,l);let c=n.data.get(r.dataId).values,u=um(c,i,l,r.shape,r.dtype);return n.makeTensorInfo(l,r.dtype,u)}var tH={kernelName:Di,backendName:"cpu",kernelFunc:pl};function rI(e,t,n,s,r,a,o){let i=t[0],l=a[0],c=new Array(l),u=new Array(i),d=t[1];if(l===0){if(i!==0)throw new Error(`Received SparseTensor with denseShape[0] = 0 but indices.shape[0] = ${i}`);let g=v.getArrayFromDType(n,0),A=v.getArrayFromDType(r,0);return[g,[0,d],A,c,u]}let p=!0,h=0,f=new Array(l).fill(0);for(let g=0;g=l)throw new Error(`indices(${g}, 0) is invalid: ${A} >= ${l}`);++f[A],p=p&&A>=h,h=A}let m=!0;for(let g=0;g0&&(f[g]+=f[g-1])}if(m&&p){let g=e,A=s;for(let y=0;y0){h[p-1]=1;for(let g=p-2;g>=0;--g)h[g]=h[g+1]*s[g+1]}let f=[];if(i>0){f[i-1]=1;for(let g=i-2;g>=0;--g)f[g]=f[g+1]*l[g+1]}let m=v.getArrayFromDType(n,o*i);for(let g=0;g0?r[i-1]+1:0;if(d<0)throw new Error("segment ids must be >= 0");let p=t.slice();p[0]=d;let h=p.reduce((x,b)=>x*b,1),f=v.getArrayFromDType(n,h);if(i===0)return d>0&&f.fill(o),[f,p];if(d<=0)throw new Error("segment ids must be >= 0");let m=0,g=1,A=0,y=r[m];for(;;){let x=0;if(g=x)throw new Error("segment ids are not increasing")}if(y<0||y>=d)throw new Error(`Segment id ${y} out of range [0, ${d}), possibly because segmentIds input is not sorted.`);y>A&&f.fill(o,A*c,y*c);for(let b=m;b=l[0])throw new Error(`Bad: indices[${b}] == ${s[b]} out of range [0, ${l[0]})`);for(let k=0;ki)break}return AMath.sqrt(e)),sH=gt(ao,e=>Math.sqrt(e)),rH={kernelName:ao,backendName:"cpu",kernelFunc:sH},oI=Jt((e,t)=>{let n=e-t;return n*n}),aH=vn(lo,oI),oH={kernelName:lo,backendName:"cpu",kernelFunc:aH};function iI(e,t,n,s){let r=Le(e,t.dtype);for(let a=0;a0?0:o-i),p=0;p+=l*this.leftPad.length;for(let A=0;AA.forEach(y=>f[m++]=y);for(let A=0;A0){g(e[d+u-1]);for(let A=0;A0){let i=t[0];if(i!==0)throw new Error(`First split value must be 0, got ${i}`);for(let l=1;l=i;if(c=c&&t[l]<=n,!c)throw new Error(`Invalid split value ${t[l]}, must be in [${i}, ${n}]`);i=t[l]}if(i!==n)throw new Error(`Last split value must be data size. Expected ${n}, got ${i}`)}let r=s-1,a=v.getArrayFromDType("int32",s);if(n===0||s===0){let i=new Array(n);for(let l=0;l<=r;++l)a[l]=0;return[i,a]}a[0]=0;for(let i=1;i<=r;++i){let l=t[i]-t[i-1],c=0;this.nGramWidths.forEach(u=>{c+=this.getNumNGrams(l,u)}),this.preserveShort&&l>0&&c===0&&(c=1),a[i]=a[i-1]+c}let o=new Array(a[r]);for(let i=0;i{let d=t[i+1]-t[i],p=this.getNumNGrams(d,u);this.createNGrams(e,l,o,c,p,u),c+=p}),this.preserveShort&&c===a[i]){let u=t[i+1]-t[i];if(u===0)continue;let d=u+2*this.padWidth,p=1;this.createNGrams(e,l,o,c,p,d)}}return[o,a]}};function lI(e,t,n,s,r,a,o,i){return new iH(n,s,r,a,o,i).compute(e,t)}function lH(e,t,n,s){if(!e.length)return;if(t.length===0){for(let a=0;ae-t),uH=by((e,t,n,s)=>({real:e-n,imag:t-s})),Ty=vn(uo,dI,uH),cH={kernelName:uo,backendName:"cpu",kernelFunc:Ty};function pI(e,t){let n=new Array(e.rank);for(let r=0;r{let n=t.value-e.value;return n===0?e.index-t.index:n};function hI(e,t,n=0,s=e.length-1){for(;s>n;){if(s-n>600){let i=s-n+1,l=t-n+1,c=Math.log(i),u=.5*Math.exp(2*c/3),d=.5*Math.sqrt(c*u*(i-u)/i)*Math.sign(l-i/2),p=Math.max(n,Math.floor(t-l*u/i+d)),h=Math.min(s,Math.floor(t+(i-l)*u/i+d));hI(e,t,p,h)}let r=e[t],a=n,o=s;for(v.swap(e,n,t),Bd(e[s],r)>0&&v.swap(e,n,s);a0;)o=o-1}Bd(e[n],r)===0?v.swap(e,n,o):(o=o+1,v.swap(e,o,s)),o<=t&&(n=o+1),t<=o&&(s=o-1)}}function fI(e,t,n,s,r){let a=t[t.length-1],[o,i]=[e.length/a,a],l=v.getTypedArrayFromDType(n,o*s),c=v.getTypedArrayFromDType("int32",o*s);for(let d=0;df[x]={value:y,index:x}),s{for(let g=0;gnew xy,1);var gI=gt(Pa,e=>e>=0?e:Math.exp(e)-1),pH={kernelName:Pa,backendName:"cpu",kernelFunc:gI};function AI(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{alpha:a}=s;Ne([r],"leakyRelu");let o=v.sizeFromShape(r.shape),i=n.data.get(r.dataId).values,l=v.getTypedArrayFromDType("float32",o);for(let c=0;ce<0?t*e:e);function yI(e){let{inputs:t,backend:n}=e,{x:s,alpha:r}=t;Ne([s,r],"prelu");let a=n.data.get(s.dataId).values,o=n.data.get(r.dataId).values,[i,l]=fH(s.shape,r.shape,a,o,"float32");return n.makeTensorInfo(l,"float32",i)}var mH={kernelName:Ja,backendName:"cpu",kernelFunc:yI},xI=gt(Qa,e=>Math.max(0,e)),gH={kernelName:Qa,backendName:"cpu",kernelFunc:xI},bI=gt(to,e=>Math.min(Math.max(0,e),6)),AH={kernelName:to,backendName:"cpu",kernelFunc:bI};function Ny(e,t,n,s,r){if(n==="linear")return Or({inputs:{x:t},backend:e});if(n==="relu")return xI({inputs:{x:t},backend:e});if(n==="elu")return gI({inputs:{x:t},backend:e});if(n==="relu6")return bI({inputs:{x:t},backend:e});if(n==="prelu")return yI({inputs:{x:t,alpha:s},backend:e});if(n==="leakyrelu")return AI({inputs:{x:t},backend:e,attrs:{alpha:r}});if(n==="sigmoid")return sI({inputs:{x:t},backend:e});throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)}function Tt(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{shape:a}=s,o=v.sizeFromShape(r.shape),i=v.inferFromImplicitShape(a,o),l=v.sizeFromShape(i);v.assert(o===l,()=>`The new shape (${i}) has ${l} elements and the old shape (${r.shape}) has ${o} elements. The new shape and old shape must have the same number of elements.`),n.incRef(r.dataId);let c=n.data.get(r.dataId);if(c.complexTensorInfos!=null){let u=c.complexTensorInfos.real,d=c.complexTensorInfos.imag;u.shape=i,d.shape=i}return{dataId:r.dataId,shape:i,dtype:r.dtype}}var yH={kernelName:Ti,backendName:"cpu",kernelFunc:Tt};function vI(e){let{inputs:t,backend:n,attrs:s}=e,{a:r,b:a}=t,{transposeA:o,transposeB:i}=s;Ne([r,a],"matMul");let l=r.shape.length,c=a.shape.length,u=o?r.shape[l-2]:r.shape[l-1],d=i?a.shape[c-1]:a.shape[c-2],p=o?r.shape[l-1]:r.shape[l-2],h=i?a.shape[c-2]:a.shape[c-1],f=r.shape.slice(0,-2),m=a.shape.slice(0,-2),g=v.sizeFromShape(f),A=v.sizeFromShape(m),y=g===A||g===1||A===1;v.assert(l>=2&&c>=2&&y,()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${f}) and (${m}).`);let b=(g>A?r.shape.slice(0,-2):a.shape.slice(0,-2)).concat([p,h]);v.assert(u===d,()=>`Error in matMul: inner shapes (${u}) and (${d}) of Tensors with shapes ${r.shape} and ${a.shape} and transposeA=${o} and transposeB=${i} must match.`);let w=o?[g,u,p]:[g,p,u],k=i?[A,h,d]:[A,d,h],S=Tt({inputs:{x:r},backend:n,attrs:{shape:w}}),E=Tt({inputs:{x:a},backend:n,attrs:{shape:k}}),P=o?S.shape[1]:S.shape[2],F=o?S.shape[2]:S.shape[1],R=i?E.shape[1]:E.shape[2],_=Math.max(g,A),T=n.data.get(S.dataId).values,M=n.data.get(E.dataId).values,U=v.computeStrides(S.shape),H=v.computeStrides(E.shape),[z,X,ee]=o?[U[0],1,U[1]]:[U[0],U[1],1],[Y,se,ne]=i?[1,H[1],H[0]]:[H[1],1,H[0]],J=F*R,te=Le([_,F,R],S.dtype),ue=te.values,ce=n.blockSize;for(let xe=0;xe<_;xe++)for(let we=0;weMath.acos(e)),kH={kernelName:Vl,backendName:"cpu",kernelFunc:wH},IH=gt(Ul,e=>Math.acosh(e)),SH={kernelName:Ul,backendName:"cpu",kernelFunc:IH};function CH(e){let{inputs:t,backend:n}=e,s=t;Ne(t,"addN");let r=s.map(i=>n.data.get(i.dataId).values),a=Le(s[0].shape,s[0].dtype),o=a.values;for(let i=0;iy&&(y=w,x=b)}h[g]=x}return c.forEach(g=>n.disposeIntermediateTensorInfo(g)),n.makeTensorInfo(u,"int32",h)}var _H={kernelName:ka,backendName:"cpu",kernelFunc:DH};function PH(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a}=s;Ne(r,"argMin");let o=v.parseAxisParam(a,r.shape),i=N.getAxesPermutation(o,r.shape.length),l=r,c=[];i!=null&&(l=Ds({inputs:{x:r},backend:n,attrs:{perm:i}}),c.push(l),o=N.getInnerMostAxes(o.length,l.shape.length)),o=[o[0]],N.assertAxesAreInnerMostDims("argMin",o,l.shape.length);let[u,d]=N.computeOutAndReduceShapes(l.shape,o),p=v.sizeFromShape(u),h=v.makeZerosTypedArray(p,"int32"),f=v.sizeFromShape(d),m=n.data.get(l.dataId).values;for(let g=0;gn.disposeIntermediateTensorInfo(g)),n.makeTensorInfo(u,"int32",h)}var FH={kernelName:jl,backendName:"cpu",kernelFunc:PH},OH=gt(ql,e=>Math.asin(e)),MH={kernelName:ql,backendName:"cpu",kernelFunc:OH},zH=gt(Xl,e=>Math.asinh(e)),LH={kernelName:Xl,backendName:"cpu",kernelFunc:zH},BH=gt(Kl,e=>Math.atan(e)),WH={kernelName:Kl,backendName:"cpu",kernelFunc:BH},VH=Jt((e,t)=>Math.atan2(e,t)),UH=vn(Yl,VH),GH={kernelName:Yl,backendName:"cpu",kernelFunc:UH},HH=gt(Zl,e=>Math.atanh(e)),jH={kernelName:Zl,backendName:"cpu",kernelFunc:HH};function Ey(e,t,n,s,r,a){let o=r.strideHeight,i=r.strideWidth,l=r.dilationHeight,c=r.dilationWidth,u=r.effectiveFilterHeight,d=r.effectiveFilterWidth,p=r.padInfo.top,h=r.padInfo.left,f=a==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,m=Le(r.outShape,n),g=m.values,A=r.outShape[1]*r.outShape[2]*r.outShape[3],y=r.outShape[2]*r.outShape[3],x=r.outShape[3];for(let b=0;bz?z=ue:a==="avg"&&(X+=ue,ee++)}if(isNaN(z))break}let Y=_+T*x+S;g[Y]=a==="avg"?X/ee:z}}}return m}function wI(e,t,n,s,r=!1,a=!1){let o=Le(s.outShape,"int32"),i=s.strideHeight,l=s.strideWidth,c=s.dilationHeight,u=s.dilationWidth,d=s.effectiveFilterHeight,p=s.effectiveFilterWidth,h=s.padInfo.top,f=s.padInfo.left,m=Le(t,n,e);for(let g=0;gF&&(F=H,r?R=a?((g*s.inHeight+_)*s.inWidth+M)*s.inChannels+A:(_*s.inWidth+M)*s.inChannels+A:R=T*p+U)}}o.set(R,g,y,k,A)}}return o}function kI(e,t,n,s,r,a){let o=r.strideDepth,i=r.strideHeight,l=r.strideWidth,c=r.dilationDepth,u=r.dilationHeight,d=r.dilationWidth,p=r.effectiveFilterDepth,h=r.effectiveFilterHeight,f=r.effectiveFilterWidth,m=r.padInfo.front,g=r.padInfo.top,A=r.padInfo.left,y=a==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,x=Le(r.outShape,n),b=x.values,w=r.outShape[1]*r.outShape[2]*r.outShape[3]*r.outShape[4],k=r.outShape[2]*r.outShape[3]*r.outShape[4],S=r.outShape[3]*r.outShape[4],E=r.outShape[4];for(let P=0;Pwe?we=yt:a==="avg"&&(Ce+=yt,Oe++),isNaN(we))break}if(isNaN(we))break}if(isNaN(we))break}let Ue=xe+_;b[Ue]=a==="avg"?Ce/Oe:we}}}}return x}function qH(e,t){let n=Le(t.outShape,"int32"),s=t.strideDepth,r=t.strideHeight,a=t.strideWidth,o=t.dilationDepth,i=t.dilationHeight,l=t.dilationWidth,c=t.effectiveFilterDepth,u=t.effectiveFilterHeight,d=t.effectiveFilterWidth,p=t.padInfo.front,h=t.padInfo.top,f=t.padInfo.left;for(let m=0;m=T&&(T=se,M=H*u*d+X*u+Y)}}}n.set(M,m,A,w,P,g)}}}return n}function XH(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t;Ne(r,"avgPool");let{filterSize:a,strides:o,pad:i,dimRoundingMode:l}=s,c=1;v.assert(N.eitherStridesOrDilationsAreOne(o,c),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${c}'`);let u=N.computePool2DInfo(r.shape,a,o,c,i,l),d;if(u.filterWidth===1&&u.filterHeight===1&&v.arraysEqual(u.inShape,u.outShape))d=Or({inputs:{x:r},backend:n});else{let p=n.data.get(r.dataId).values,h=v.computeStrides(r.shape),f=Ey(p,r.shape,r.dtype,h,u,"avg");d=n.makeTensorInfo(u.outShape,r.dtype,f.values)}return d}var KH={kernelName:Ia,backendName:"cpu",kernelFunc:XH};function ZH(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:l,dataFormat:c}=s;Ne(r,"avgPool3d");let u=N.computePool3DInfo(r.shape,a,o,1,i,l,c),d=n.data.get(r.dataId).values,p=kI(d,r.shape,r.dtype,v.computeStrides(r.shape),u,"avg");return n.makeTensorInfo(p.shape,"float32",p.values)}var YH={kernelName:Fc,backendName:"cpu",kernelFunc:ZH};function JH(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,{filterSize:o,strides:i,pad:l,dimRoundingMode:c}=s;Ne([r,a],"avgPool3DGrad");let u=N.computePool3DInfo(a.shape,o,i,1,l,c),d=u.strideDepth,p=u.strideHeight,h=u.strideWidth,f=u.filterDepth,m=u.filterHeight,g=u.filterWidth,A=u.dilationDepth,y=u.dilationHeight,x=u.dilationWidth,b=u.effectiveFilterDepth,w=u.effectiveFilterHeight,k=u.effectiveFilterWidth,S=b-1-u.padInfo.front,E=k-1-u.padInfo.left,P=w-1-u.padInfo.top,F=Le(a.shape,"float32"),R=1/(f*m*g),_=n.bufferSync(r);for(let T=0;T=u.outDepth||Math.floor(J)!==J))for(let te=0;te=u.outHeight||Math.floor(ue)!==ue))for(let ce=0;ce=u.outWidth||Math.floor(xe)!==xe)continue;se+=_.get(T,J,ue,xe,M)}}}F.set(se*R,T,U,H,z,M)}return n.makeTensorInfo(F.shape,F.dtype,F.values)}var QH={kernelName:th,backendName:"cpu",kernelFunc:JH};function ej(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,o=a;Ne([r,a],"avgPoolGrad");let{filterSize:i,strides:l,pad:c}=s,u=N.computePool2DInfo(o.shape,i,l,1,c),d=u.strideHeight,p=u.strideWidth,h=u.filterHeight,f=u.filterWidth,m=u.dilationHeight,g=u.dilationWidth,A=u.effectiveFilterHeight,y=u.effectiveFilterWidth,x=y-1-u.padInfo.left,b=A-1-u.padInfo.top,w=Le(o.shape,"float32"),k=1/(h*f),S=n.data.get(r.dataId).values,E=Le(r.shape,"float32",S);for(let P=0;P=u.outHeight||Math.floor(z)!==z))for(let X=0;X=u.outWidth||Math.floor(ee)!==ee)continue;U+=E.get(P,z,ee,F)}}w.set(U*k,P,R,_,F)}return n.makeTensorInfo(w.shape,w.dtype,w.values)}var tj={kernelName:eh,backendName:"cpu",kernelFunc:ej};function nj(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,scale:a,offset:o,mean:i,variance:l}=t;v.assert(i.shape.length===l.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),v.assert(o==null||i.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),v.assert(a==null||i.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks."),Ne([r,i,l,a,o],"batchNorm");let{varianceEpsilon:c}=s;c==null&&(c=.001);let u=n.data.get(r.dataId).values,d=n.data.get(i.dataId).values,p=n.data.get(l.dataId).values,h=a?n.data.get(a.dataId).values:new Float32Array([1]),f=o?n.data.get(o.dataId).values:new Float32Array([0]),m=new Float32Array(u.length),g=f.length,A=h.length,y=p.length,x=d.length,b=0,w=0,k=0,S=0;for(let E=0;E=g&&(b=0),w>=x&&(w=0),k>=A&&(k=0),S>=y&&(S=0);return n.makeTensorInfo(r.shape,r.dtype,m)}var sj={kernelName:za,backendName:"cpu",kernelFunc:nj};function rj(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,crops:o}=s;Ne([r],"batchToSpaceND");let i=a.reduce((A,y)=>A*y),l=N.getReshaped(r.shape,a,i),c=N.getPermuted(l.length,a.length),u=N.getReshapedPermuted(r.shape,a,i),d=N.getSliceBeginCoords(o,a.length),p=N.getSliceSize(u,o,a.length),h=Tt({inputs:{x:r},backend:n,attrs:{shape:l}}),f=Ds({inputs:{x:h},backend:n,attrs:{perm:c}}),m=Tt({inputs:{x:f},backend:n,attrs:{shape:u}}),g=pl({inputs:{x:m},backend:n,attrs:{begin:d,size:p}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}var aj={kernelName:si,backendName:"cpu",kernelFunc:rj};function oj(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,weights:a}=t,{size:o}=s,i=n.data.get(r.dataId).values,l=n.data.get(a.dataId).values,c=vy(i,l,a.dtype,a.shape,o);return n.makeTensorInfo([o],a.dtype,c)}var ij={kernelName:nh,backendName:"cpu",kernelFunc:oj};function lj(e){let{inputs:t,backend:n}=e,{s0:s,s1:r}=t,a=n.data.get(s.dataId).values,o=n.data.get(r.dataId).values,i=N.assertAndGetBroadcastShape(Array.from(a),Array.from(o));return n.makeTensorInfo([i.length],"int32",Int32Array.from(i))}var uj={kernelName:sh,backendName:"cpu",kernelFunc:lj},cj=gt(jr,(e,t)=>{let n=t;return e>n.clipValueMax?n.clipValueMax:e{let{x:t}=e.inputs,n=e.backend,s=new Float32Array(v.sizeFromShape(t.shape)),r=n.data.get(t.dataId),a=r.complexTensorInfos.real,o=r.complexTensorInfos.imag,i=n.data.get(a.dataId).values,l=n.data.get(o.dataId).values;for(let c=0;cm.shape),a);if(v.sizeFromShape(o)===0)return n.makeTensorInfo(o,t[0].dtype,[]);let i=t.filter(m=>v.sizeFromShape(m.shape)>0);if(i.length===1)return Or({inputs:{x:i[0]},backend:n});let l=i.map(m=>m.shape);if(N.assertParamsConsistent(l,a),i[0].dtype==="complex64"){let m=i.map(b=>dl({inputs:{input:b},backend:n})),g=i.map(b=>Vu({inputs:{input:b},backend:n})),A=Uu({inputs:m,backend:n,attrs:{axis:a}}),y=Uu({inputs:g,backend:n,attrs:{axis:a}}),x=xs({inputs:{real:A,imag:y},backend:n});return m.forEach(b=>n.disposeIntermediateTensorInfo(b)),g.forEach(b=>n.disposeIntermediateTensorInfo(b)),n.disposeIntermediateTensorInfo(A),n.disposeIntermediateTensorInfo(y),x}let c=i.map(m=>{let g=v.sizeFromShape(m.shape.slice(a));return Tt({inputs:{x:m},backend:n,attrs:{shape:[-1,g]}})}),u=c.map(m=>({vals:n.data.get(m.dataId).values,shape:m.shape}));o=N.computeOutShape(c.map(m=>m.shape),1);let d=c[0].shape[0]===1,p=wy(u,o,t[0].dtype,d),h=N.computeOutShape(i.map(m=>m.shape),a),f=n.makeTensorInfo(h,t[0].dtype,p);return c.forEach(m=>n.disposeIntermediateTensorInfo(m)),f}var mj={kernelName:ri,backendName:"cpu",kernelFunc:Uu};function II(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:o,pad:i,dataFormat:l,dilations:c,dimRoundingMode:u}=s;Ne([r,a],"conv2d");let d=N.convertConv2DDataFormat(l),p=N.computeConv2DInfo(r.shape,a.shape,o,c,i,u,!1,d),h=p.filterHeight,f=p.filterWidth,m=p.dilationHeight,g=p.dilationWidth,A=p.padInfo.left,y=p.padInfo.top,x=p.dataFormat==="channelsLast",b=new sn(p.outShape,r.dtype),w=v.computeStrides(r.shape),k=v.computeStrides(a.shape),S=w[0],E=x?w[1]:w[2],P=x?w[2]:1,F=x?1:w[1],R=b.strides[0],_=x?b.strides[1]:b.strides[2],T=x?b.strides[2]:1,M=x?1:b.strides[1],U=n.data.get(r.dataId).values,H=n.data.get(a.dataId).values,z=b.values;for(let X=0;X=p.inHeight)continue;let ce=te*k[0],xe=ee+ue*E;for(let we=0;we=p.inWidth)continue;let rt=ce+Ue*k[1],ft=xe+Xe*P,ut=rt;for(let ct=0;ct=c.inDepth)continue;let X=H*P[0],ee=R+z*E[1];for(let Y=0;Y=c.inHeight)continue;let ue=X+J*P[1],ce=ee+te*E[2];for(let xe=0;xe=c.inWidth)continue;let Xe=ue+Oe*P[2],rt=ce+Ue*c.inChannels,ft=Xe;for(let ut=0;utMath.cos(e)),Nj={kernelName:Ra,backendName:"cpu",kernelFunc:Tj},Ej=gt($a,e=>Math.cosh(e)),Rj={kernelName:$a,backendName:"cpu",kernelFunc:Ej};function $j(e){let{inputs:t,backend:n,attrs:s}=e,{image:r,boxes:a,boxInd:o}=t,{cropSize:i,method:l,extrapolationValue:c}=s,[u,d,p,h]=r.shape,f=a.shape[0],[m,g]=i,A=Le([f,m,g,h],"float32"),y=n.data.get(a.dataId).values,x=n.data.get(o.dataId).values,b=n.data.get(r.dataId).values,w=v.computeStrides(r.shape),k=v.computeStrides(A.shape);for(let S=0;S=u)continue;let M=m>1?(R-P)*(d-1)/(m-1):0,U=g>1?(_-F)*(p-1)/(g-1):0;for(let H=0;H1?P*(d-1)+H*M:.5*(P+R)*(d-1);if(z<0||z>d-1){for(let X=0;X1?F*(p-1)+se*U:.5*(F+_)*(p-1);if(ne<0||ne>p-1){for(let ce=0;ce1?F*(p-1)+X*U:.5*(F+_)*(p-1);if(ee<0||ee>p-1){for(let ne=0;neA+f-y-1:(A,y)=>A+y;for(let A=0;A`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${o}`);let i=r.shape[0],l=r.shape[1],c=r.shape[2],u=r.shape[3],d=l*a,p=c*a,h=u/(a*a),f=n.data.get(r.dataId).values,m=new Float32Array(i*d*p*h),g=0;for(let A=0;A`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${p}'`);let h=N.computeConv2DInfo(r.shape,a.shape,o,p,i,c,!0),{filterHeight:f,filterWidth:m,dilationHeight:g,dilationWidth:A,padInfo:y}=h,x=y.left,b=y.top,w=h.outChannels/h.inChannels,k=new sn(h.outShape,r.dtype),S=n.data.get(r.dataId).values,E=n.data.get(a.dataId).values,P=k.values;for(let F=0;F=h.inHeight)continue;let X=H*d[0],ee=R+z*u[1];for(let Y=0;Y=h.inWidth)continue;let ue=X+J*d[1],ce=ee+te*h.inChannels,xe=se,we=ue;for(let Ce=0;Ce{let{x:s,filter:r}=e,{strides:a,pad:o,dilations:i}=n,l=t,c=l.data.get(s.dataId).values,u=s.shape.length,d=l.data.get(r.dataId).values,p=r.shape.length,{batchSize:h,inHeight:f,inWidth:m,inChannels:g,outHeight:A,outWidth:y,padInfo:x,strideHeight:b,strideWidth:w,filterHeight:k,filterWidth:S,dilationHeight:E,dilationWidth:P,outShape:F}=N.computeDilation2DInfo(s.shape,r.shape,a,o,"NHWC",i),R=v.sizeFromShape(F),_=F.length,T=v.getArrayFromDType(s.dtype,R);for(let U=0;U=0&&te=0&&cese&&(se=Ce)}}}let ne=v.locToIndex([U,H,X,Y],_,v.computeStrides(F));T[ne]=se}}}return{dataId:l.write(v.toTypedArray(T,s.dtype),F,s.dtype),shape:F,dtype:s.dtype}}},qj={kernelName:ph,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{let{x:s,filter:r,dy:a}=e,{strides:o,pad:i,dilations:l}=n,c=t,u=v.toNestedArray(s.shape,c.data.get(s.dataId).values),d=v.toNestedArray(r.shape,c.data.get(r.dataId).values),{batchSize:p,inHeight:h,inWidth:f,inChannels:m,outHeight:g,outWidth:A,padInfo:y,strideHeight:x,strideWidth:b,filterHeight:w,filterWidth:k,dilationHeight:S,dilationWidth:E,outShape:P}=N.computeDilation2DInfo(s.shape,r.shape,o,i,"NHWC",l);v.assert(a.rank===P.length,()=>`Error in ${ph}, dy must have the same rank as output ${P.length}, but got ${a.rank}`);let F=v.toNestedArray(P,c.data.get(a.dataId).values),R=v.makeZerosNestedTypedArray(r.shape,r.dtype);for(let T=0;T=0&&J=0&&ueee&&(ee=ce,Y=ne,se=te)}}}R[Y][se][X]+=F[T][M][H][X]}}}return{dataId:c.write(v.toTypedArray(R,s.dtype),r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},Xj={kernelName:dh,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{let{x:s,filter:r,dy:a}=e,{strides:o,pad:i,dilations:l}=n,c=t,u=v.toNestedArray(s.shape,c.data.get(s.dataId).values),d=v.toNestedArray(r.shape,c.data.get(r.dataId).values),{batchSize:p,inHeight:h,inWidth:f,inChannels:m,outHeight:g,outWidth:A,padInfo:y,strideHeight:x,strideWidth:b,filterHeight:w,filterWidth:k,dilationHeight:S,dilationWidth:E,outShape:P}=N.computeDilation2DInfo(s.shape,r.shape,o,i,"NHWC",l);v.assert(a.rank===P.length,()=>`Error in ${dh}, dy must have the same rank as output ${P.length}, but got ${a.rank}`);let F=v.toNestedArray(P,c.data.get(a.dataId).values),R=v.makeZerosNestedTypedArray(s.shape,s.dtype);for(let T=0;T=0&&J=0&&ueee&&(ee=ce,Y=J,se=ue)}}}R[T][Y][se][X]+=F[T][M][H][X]}}}return{dataId:c.write(v.toTypedArray(R,s.dtype),s.shape,s.dtype),shape:s.shape,dtype:s.dtype}}};function Wd(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s;Ne(r,"sum");let i;r.dtype==="bool"?i=_o({inputs:{x:r},backend:n,attrs:{dtype:"int32"}}):i=Or({inputs:{x:r},backend:n});let l=i.shape.length,c=v.parseAxisParam(a,i.shape),u=N.getAxesPermutation(c,l),d=c,p=i;u!=null&&(p=Ds({inputs:{x:i},backend:n,attrs:{perm:u}}),d=N.getInnerMostAxes(d.length,l)),N.assertAxesAreInnerMostDims("sum",d,p.shape.length);let[h,f]=N.computeOutAndReduceShapes(p.shape,d),m=N.upcastType(p.dtype,"int32"),g=im(n,h,m),A=v.sizeFromShape(f),y=n.data.get(g.dataId).values,x=n.data.get(p.dataId).values;for(let b=0;b=0&&(p=Wd({inputs:{x:p},backend:n,attrs:{axis:c[m]-(o.length-h),keepDims:!1}}),f.push(p)),h--)}for(let m of f)m!==p&&n.disposeIntermediateTensorInfo(m);return p}var Yj={kernelName:Bc,backendName:"cpu",kernelFunc:Zj};function Jj(e){let{inputs:t,backend:n}=e,{dy:s,y:r}=t;Ne([s,r],"eluGrad");let a=new Float32Array(v.sizeFromShape(r.shape)),o=n.data.get(r.dataId).values,i=n.data.get(s.dataId).values;for(let l=0;l=1?a[l]=i[l]:a[l]=i[l]*(c+1)}return n.makeTensorInfo(r.shape,"float32",a)}var Qj={kernelName:hh,backendName:"cpu",kernelFunc:Jj},eq=N.ERF_P,tq=N.ERF_A1,nq=N.ERF_A2,sq=N.ERF_A3,rq=N.ERF_A4,aq=N.ERF_A5,oq=gt(Jl,e=>{let t=Math.sign(e),n=Math.abs(e),s=1/(1+eq*n);return t*(1-((((aq*s+rq)*s+sq)*s+nq)*s+tq)*s*Math.exp(-n*n))}),iq={kernelName:Jl,backendName:"cpu",kernelFunc:oq};function cm(e){let{inputs:t,backend:n,attrs:s}=e,{input:r}=t,{dim:a}=s,o=r.shape.length,i=r.shape.slice(),l=a;return a<0&&(v.assert(-(o+1)<=a,()=>`Axis must be in the interval [${-(o+1)}, ${o}]`),l=o+a+1),i.splice(l,0,1),Tt({inputs:{x:r},backend:n,attrs:{shape:i}})}var lq={kernelName:ui,backendName:"cpu",kernelFunc:cm},uq=Jt((e,t)=>e/t),Ry=vn(_a,uq),$y={kernelName:_a,backendName:"cpu",kernelFunc:Ry};function CI(e,t,n){let s=e.shape,r=s[0],a=s[1],o=n.data.get(e.dataId),i=o.complexTensorInfos.real,l=o.complexTensorInfos.imag,c=[r,a],u=v.sizeFromShape(c),d=v.getTypedArrayFromDType("float32",u),p=v.getTypedArrayFromDType("float32",u);for(let g=0;g{let{image:s}=e,r=n,a=v.getTypedArrayFromDType(s.dtype,v.sizeFromShape(s.shape)),[o,i,l,c]=s.shape,u=r.data.get(s.dataId).values;for(let p=0;p=0&&xMath.floor(e/t)),xq=vn(Ma,yq,null,"int32"),bq={kernelName:Ma,backendName:"cpu",kernelFunc:xq};function vq(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:c,dataFormat:u,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=s,m=II({inputs:{x:r,filter:a},backend:n,attrs:{strides:l,pad:c,dataFormat:u,dilations:d,dimRoundingMode:p}});if(o){let g=m;m=Ld({inputs:{a:m,b:o},backend:n}),n.disposeIntermediateTensorInfo(g)}if(h){let g=m;m=Ny(n,m,h,i,f),n.disposeIntermediateTensorInfo(g)}return m}var wq={kernelName:mo,backendName:"cpu",kernelFunc:vq};function kq(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:c,dataFormat:u,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=s,m=SI({inputs:{x:r,filter:a},backend:n,attrs:{strides:l,pad:c,dataFormat:u,dilations:d,dimRoundingMode:p}});if(o){let g=m;m=Ld({inputs:{a:m,b:o},backend:n}),n.disposeIntermediateTensorInfo(g)}if(h){let g=m;m=Ny(n,m,h,i,f),n.disposeIntermediateTensorInfo(g)}return m}var Iq={kernelName:go,backendName:"cpu",kernelFunc:kq};function Sq(e){let{inputs:t,backend:n}=e,{params:s,indices:r}=t,a=v.sizeFromShape(s.shape),o=r.shape,i=o[o.length-1],[l,c,u,d]=N.prepareAndValidate(s,r);if(c===0)return n.makeTensorInfo(l,s.dtype,[]);let p=n.data.get(r.dataId).values,h=n.bufferSync(s),f=V7(p,h,s.dtype,c,i,u,d,s.shape,a);return n.makeTensorInfo(l,s.dtype,f.values)}var Cq={kernelName:hi,backendName:"cpu",kernelFunc:Sq};function Tq(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,indices:a}=t,{axis:o,batchDims:i}=s;Ne([r,a],"gatherV2");let l=v.parseAxisParam(o,r.shape)[0],c=n.data.get(a.dataId).values,u=r.shape[l];for(let b=0;b=0,()=>`GatherV2: the index value ${w} is not in [0, ${u-1}]`)}let d=i;i==null&&(d=0);let p=v.sizeFromShape(a.shape),h=N.segment_util.collectGatherOpShapeInfo(r,a,l,d),f=Tt({inputs:{x:r},backend:n,attrs:{shape:[h.batchSize,h.outerSize,h.dimSize,h.sliceSize]}}),m=Tt({inputs:{x:a},backend:n,attrs:{shape:[h.batchSize,p/h.batchSize]}}),g=[h.batchSize,h.outerSize,p/h.batchSize,h.sliceSize],A=n.bufferSync(m),y=n.bufferSync(f),x=U7(y,A,g);return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),n.makeTensorInfo(h.outputShape,x.dtype,x.values)}var Nq={kernelName:pi,backendName:"cpu",kernelFunc:Tq};function Eq(e){let{inputs:t,backend:n}=e,{input:s}=t,r=v.sizeFromShape(s.shape),a=s.shape[s.shape.length-1],o=r/a,i=Tt({inputs:{x:s},backend:n,attrs:{shape:[o,a]}}),l=CI(i,!0,n),c=Tt({inputs:{x:l},backend:n,attrs:{shape:s.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(l),c}var Rq={kernelName:mh,backendName:"cpu",kernelFunc:Eq},$q=gt(eu,e=>Number.isFinite(e)?1:0,"bool"),Dq={kernelName:eu,backendName:"cpu",kernelFunc:$q},_q=gt(tu,e=>Math.abs(e)===1/0?1:0,"bool"),Pq={kernelName:tu,backendName:"cpu",kernelFunc:_q},Fq=gt(nu,e=>Number.isNaN(e)?1:0,"bool"),Oq={kernelName:nu,backendName:"cpu",kernelFunc:Fq};function Mq(e){let{backend:t,attrs:n}=e,{start:s,stop:r,num:a}=n,o=X7(s,r,a);return t.makeTensorInfo([o.length],"float32",o)}var zq={kernelName:gh,backendName:"cpu",kernelFunc:Mq},Lq=gt(su,e=>Math.log1p(e)),Bq={kernelName:su,backendName:"cpu",kernelFunc:Lq},Wq=Jt((e,t)=>e&&t),Vq=vn(yi,Wq,null,"bool"),Uq={kernelName:yi,backendName:"cpu",kernelFunc:Vq},Gq=gt(ru,e=>e?0:1,"bool"),Hq={kernelName:ru,backendName:"cpu",kernelFunc:Gq},jq=Jt((e,t)=>e||t),qq=vn(Vc,jq,null,"bool"),Xq={kernelName:Vc,backendName:"cpu",kernelFunc:qq};function Kq(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{depthRadius:a,bias:o,alpha:i,beta:l}=s;Ne(r,"LRN");let c=r.shape[3],u=c-1,d=n.data.get(r.dataId).values,p=v.sizeFromShape(r.shape),h=new Float32Array(p);function f(m){let g=m%c,A=m-g+Math.max(0,g-a),y=m-g+Math.min(g+a,u),x=0;for(;A<=y;A++){let b=d[A];x+=b*b}return x}for(let m=0;m`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${c}'`);let u=N.computePool2DInfo(r.shape,a,o,c,i,l),d;if(u.filterWidth===1&&u.filterHeight===1&&v.arraysEqual(u.inShape,u.outShape))d=Or({inputs:{x:r},backend:n});else{let p=n.data.get(r.dataId).values,h=v.computeStrides(r.shape),f=Ey(p,r.shape,r.dtype,h,u,"max");d=n.makeTensorInfo(u.outShape,r.dtype,f.values)}return d}var tX={kernelName:Ga,backendName:"cpu",kernelFunc:eX};function nX(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:l,dataFormat:c}=s;Ne(r,"maxPool3d");let u=N.computePool3DInfo(r.shape,a,o,1,i,l,c),d=n.data.get(r.dataId).values,p=kI(d,r.shape,r.dtype,v.computeStrides(r.shape),u,"max");return n.makeTensorInfo(p.shape,"float32",p.values)}var sX={kernelName:Gc,backendName:"cpu",kernelFunc:nX};function rX(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,{filterSize:o,strides:i,pad:l,dimRoundingMode:c}=s;Ne([r,a],"maxPool3DGrad");let u=N.computePool3DInfo(a.shape,o,i,1,l,c),d=n.bufferSync(a),p=qH(d,u),h=u.strideDepth,f=u.strideHeight,m=u.strideWidth,g=u.dilationDepth,A=u.dilationHeight,y=u.dilationWidth,x=u.effectiveFilterDepth,b=u.effectiveFilterHeight,w=u.effectiveFilterWidth,k=x-1-u.padInfo.front,S=w-1-u.padInfo.left,E=b-1-u.padInfo.top,P=Le(a.shape,"float32"),F=n.bufferSync(r);for(let R=0;R=u.outDepth||Math.floor(se)!==se))for(let ne=0;ne=u.outHeight||Math.floor(J)!==J))for(let te=0;te=u.outWidth||Math.floor(ue)!==ue)continue;let ce=x*b*w-1-p.get(R,se,J,ue,_),xe=Y*b*w+ne*w+te,we=ce===xe?1:0;if(we===0)continue;ee+=F.get(R,se,J,ue,_)*we}}}P.set(ee,R,T,M,U,_)}return n.makeTensorInfo(P.shape,P.dtype,P.values)}var aX={kernelName:xh,backendName:"cpu",kernelFunc:rX};function oX(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a,output:o}=t,i=a;Ne([a,o],"maxPoolGrad");let{filterSize:l,strides:c,pad:u,dimRoundingMode:d}=s,p=N.computePool2DInfo(i.shape,l,c,1,u,d),h=n.data.get(i.dataId).values,f=Le(p.outShape,i.dtype,wI(h,i.shape,i.dtype,p).values),m=p.strideHeight,g=p.strideWidth,A=p.dilationHeight,y=p.dilationWidth,x=p.effectiveFilterHeight,b=p.effectiveFilterWidth,w=b-1-p.padInfo.left,k=x-1-p.padInfo.top,S=Le(i.shape,"float32"),E=n.data.get(r.dataId).values,P=Le(r.shape,"float32",E);for(let F=0;F=p.outHeight||Math.floor(X)!==X))for(let ee=0;ee=p.outWidth||Math.floor(Y)!==Y)continue;let se=x*b-1-f.get(F,X,Y,R),ne=z*b+ee,J=se===ne?1:0;if(J===0)continue;H+=P.get(F,X,Y,R)*J}}S.set(H,F,_,T,R)}return n.makeTensorInfo(S.shape,S.dtype,S.values)}var iX={kernelName:yh,backendName:"cpu",kernelFunc:oX};function lX(e,t,n,s,r){let a=v.computeStrides(t),o=Ey(e,t,n,a,r,"max"),i=wI(e,t,n,r,!0,s);return[o.values,i.values]}var uX={kernelName:bh,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:s}=e,{filterSize:r,strides:a,pad:o,includeBatchInIndex:i}=t,l=n;Ne(s,"MaxPoolWithArgmax");let c=l.data.get(s.dataId).values,u=N.computePool2DInfo(s.shape,r,a,[1,1],o),[d,p]=lX(c,s.shape,s.dtype,i,u),h=l.write(d,u.outShape,s.dtype),f=l.write(p,u.outShape,s.dtype);return[{dataId:h,shape:u.outShape,dtype:s.dtype},{dataId:f,shape:u.outShape,dtype:"int32"}]}};function cX(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s,i=v.parseAxisParam(a,r.shape),c=N.computeOutAndReduceShapes(r.shape,i)[1],u=v.sizeFromShape(c),d=[],p=n.makeTensorInfo([],"float32",new Float32Array([u]));d.push(p);let h=_o({inputs:{x:r},backend:n,attrs:{dtype:"float32"}});d.push(h);let f=Ry({inputs:{a:h,b:p},backend:n});d.push(f);let m=Wd({inputs:{x:f},backend:n,attrs:{axis:a,keepDims:o}});return d.forEach(g=>n.disposeIntermediateTensorInfo(g)),m}var dX={kernelName:Ha,backendName:"cpu",kernelFunc:cX};function pX(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s;Ne(r,"min");let i=v.parseAxisParam(a,r.shape),l=i,c=N.getAxesPermutation(l,r.shape.length),u=r;c!=null&&(u=Ds({inputs:{x:r},backend:n,attrs:{perm:c}}),l=N.getInnerMostAxes(l.length,r.shape.length)),N.assertAxesAreInnerMostDims("min",l,u.shape.length);let[d,p]=N.computeOutAndReduceShapes(u.shape,l),h=v.sizeFromShape(p),f=v.makeZerosTypedArray(v.sizeFromShape(d),u.dtype),m=n.data.get(u.dataId).values;for(let A=0;Ax[0]+r.shape[b]+x[1]),l=a.map(x=>x[0]),c=a.map((x,b)=>x[0]+r.shape[b]),u=o==="reflect"?0:1,d=n.data.get(r.dataId).values,p=r.shape.length,h=v.computeStrides(r.shape),f=v.sizeFromShape(i),m=i.length,g=v.computeStrides(i),A=v.getTypedArrayFromDType(r.dtype,f);for(let x=0;x=c[k]&&(b[k]=(c[k]-1)*2-b[k]+u);b=b.map((k,S)=>k-l[S]);let w=v.locToIndex(b,p,h);A[x]=d[w]}return{dataId:n.write(A,i,r.dtype),shape:i,dtype:r.dtype}}var mX={kernelName:Xa,backendName:"cpu",kernelFunc:fX},gX=Jt((e,t)=>{let n=e%t;return e<0&&t<0||e>=0&&t>=0?n:(n+t)%t}),AX=vn(au,gX),yX={kernelName:au,backendName:"cpu",kernelFunc:AX};function NI(e){let{inputs:t,backend:n,attrs:s}=e,{logits:r}=t,{dim:a}=s,o=r.shape.length,i=a;if(i===-1&&(i=o-1),i!==o-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${o} and dim was ${i}`);let l=v.parseAxisParam([i],r.shape),c=TI({inputs:{x:r},backend:n,attrs:{reductionIndices:l,keepDims:!1}}),u=N.expandShapeToKeepDim(c.shape,l),d=Tt({inputs:{x:c},backend:n,attrs:{shape:u}}),p=Ty({inputs:{a:r,b:d},backend:n}),h=L7({inputs:{x:p},backend:n}),f=Wd({inputs:{x:h},backend:n,attrs:{axis:l,keepDims:!1}}),m=Tt({inputs:{x:f},backend:n,attrs:{shape:u}}),g=Ry({inputs:{a:h,b:m},backend:n});return n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}var xX={kernelName:io,backendName:"cpu",kernelFunc:NI},bX=Qo(Kp());function vX(e){let{inputs:t,backend:n,attrs:s}=e,{logits:r}=t,{numSamples:a,seed:o,normalized:i}=s;Ne(r,"multinomial");let l=i?r:NI({inputs:{logits:r},backend:n,attrs:{dim:-1}}),c=l.shape[0],u=l.shape[1],d=n.data.get(l.dataId).values,p=[c,a],h=v.makeZerosTypedArray(v.sizeFromShape(p),"int32");for(let f=0;f=0&&u[d]{v.assertShapesMatch(a,u.shape,"All tensors passed to stack must have matching shapes"),v.assert(o===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],l=t.map(u=>{let d=cm({inputs:{input:u},backend:n,attrs:{dim:r}});return i.push(d),d}),c=Uu({inputs:l,backend:n,attrs:{axis:r}});return i.forEach(u=>n.disposeIntermediateTensorInfo(u)),c}var OX={kernelName:Si,backendName:"cpu",kernelFunc:RI};function MX(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{paddings:a,constantValue:o}=s;Ne(r,"pad");let i=a.map((y,x)=>y[0]+r.shape[x]+y[1]),l=a.map(y=>y[0]),c=n.data.get(r.dataId).values,u=v.sizeFromShape(r.shape),d=r.shape.length,p=v.computeStrides(r.shape),h=v.sizeFromShape(i),f=i.length,m=v.computeStrides(i),g=v.getTypedArrayFromDType(r.dtype,h);o!==0&&g.fill(o);for(let y=0;yk+l[S]),w=v.locToIndex(b,f,m);g[w]=c[y]}return{dataId:n.write(g,i,r.dtype),shape:i,dtype:r.dtype}}var $I={kernelName:Za,backendName:"cpu",kernelFunc:MX},zX=Jt((e,t)=>Math.pow(e,t)),LX=vn(Ya,zX),BX={kernelName:Ya,backendName:"cpu",kernelFunc:LX};function WX(e){let{backend:t,attrs:n}=e,{start:s,stop:r,dtype:a,step:o}=n,i=Sy(s,r,o,a);return t.makeTensorInfo([i.length],a,i)}var VX={kernelName:iu,backendName:"cpu",kernelFunc:WX},UX=gt(lu,e=>1/e),GX={kernelName:lu,backendName:"cpu",kernelFunc:UX};function HX(e){let{inputs:t,backend:n,attrs:s}=e,{images:r}=t,{alignCorners:a,halfPixelCenters:o,size:i}=s;Ne(r,"resizeBilinear");let l=v.computeStrides(r.shape),[c,u]=i,[d,p,h,f]=r.shape,m=n.data.get(r.dataId).values,g=new Float32Array(v.sizeFromShape([d,c,u,f])),A=[a&&c>1?p-1:p,a&&u>1?h-1:h],y=[a&&c>1?c-1:c,a&&u>1?u-1:u],x=0,b=A[0]/y[0],w=A[1]/y[1];for(let k=0;k1?c-1:c,o&&h>1?u-1:u],g=[o&&p>1?p-1:p,o&&h>1?h-1:h],A=m[0]/g[0],y=m[1]/g[1],x=n.data.get(a.dataId).values,b=0;for(let w=0;w1?p-1:p,a&&u>1?h-1:h],y=[a&&c>1?c-1:c,a&&u>1?u-1:u],x=A[0]/y[0],b=A[1]/y[1],w=0;for(let k=0;k1?u-1:u,o&&f>1?d-1:d],y=[o&&h>1?h-1:h,o&&f>1?f-1:f],x=A[0]/y[0],b=A[1]/y[1],w=1/x,k=1/b,S=Math.ceil(w)*2+2,E=Math.ceil(k)*2+2;for(let P=0;P=h)continue;let J=F+ne*l[1],te=ne*x,ue=Math.min(u-1,o?Math.round(te):Math.floor(te));if(R===ue)for(let ce=0;ce=f)continue;let we=J+xe*l[2],Ce=xe*b,Oe=Math.min(d-1,o?Math.round(Ce):Math.floor(Ce));U===Oe&&(Y+=g[we+ee])}}m[H+ee]=Y}}}}return n.makeTensorInfo(r.shape,r.dtype,m)}var JX={kernelName:wh,backendName:"cpu",kernelFunc:YX};function QX(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{dims:a}=s;Ne(r,"reverse");let o=r.shape.length,i=v.parseAxisParam(a,r.shape);if(o===0)return Or({inputs:{x:r},backend:n});let l=new sn(r.shape,r.dtype),c=n.bufferSync(r);for(let u=0;up[h]=r.shape[h]-1-p[h]),l.set(c.get(...p),...d)}return n.makeTensorInfo(l.shape,l.dtype,l.values)}var eK={kernelName:Ni,backendName:"cpu",kernelFunc:QX},tK={kernelName:Vi,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:s}=e,{radians:r,fillValue:a,center:o}=t,i=n,l=v.getTypedArrayFromDType(s.dtype,v.sizeFromShape(s.shape)),[c,u,d,p]=s.shape,[h,f]=N.getImageCenter(o,u,d),m=255,g=Math.sin(r),A=Math.cos(r),y=i.data.get(s.dataId).values;for(let b=0;b=0&&M=0&&U{let t=Math.floor(e);return e-t<.5?Math.floor(e):e-t>.5?Math.ceil(e):t%2==0?t:t+1}),sK={kernelName:Ei,backendName:"cpu",kernelFunc:nK};function DI(e,t,n,s,r,a,o,i,l,c){let u=[s/r,r],d=e.values,p=t.values;if(s===0)return Le(n,t.dtype);let h=Le(u,t.dtype);h.values.fill(l);for(let f=0;f=s/r)throw new Error(`Invalid indices: ${m} does not index into ${n}`);for(let A=0;A1||r.shape.length===1?1:v.sizeFromShape(r.shape.slice(1));for(let f=0;fe>=0?uK*e:lK*(Math.exp(e)-1)),dK={kernelName:cu,backendName:"cpu",kernelFunc:cK},pK=gt(du,e=>e<0?-1:e>0?1:0),hK={kernelName:du,backendName:"cpu",kernelFunc:pK},fK=gt(so,e=>Math.sin(e)),mK={kernelName:so,backendName:"cpu",kernelFunc:fK},gK=gt(_i,e=>Math.sinh(e)),AK={kernelName:_i,backendName:"cpu",kernelFunc:gK},yK=11920928955078125e-23,_I=Math.log(yK)+2,xK=gt(pu,e=>{let t=e>-_I,n=e<_I,s=Math.exp(e),r;return n?r=s:t?r=e:r=Math.log(1+s),r}),bK={kernelName:pu,backendName:"cpu",kernelFunc:xK};function vK(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,paddings:o}=s;Ne([r],"spaceToBatchND");let i=v.sizeFromShape(a),l=[[0,0]];l.push(...o);for(let k=1+a.length;k0){h[p-1]=1;for(let g=p-2;g>=0;--g)h[g]=h[g+1]*s[g+1]}let f=[];if(i>0){f[i-1]=1;for(let g=i-2;g>=0;--g)f[g]=f[g+1]*l[g+1]}let m=v.getArrayFromDType(n,o*i);for(let g=0;g0?r[i-1]+1:0;if(d<0)throw new Error("segment ids must be >= 0");let p=t.slice();p[0]=d;let h=p.reduce((x,b)=>x*b,1),f=v.getArrayFromDType(n,h);if(i===0)return d>0&&f.fill(o),[f,p];if(d<=0)throw new Error("segment ids must be >= 0");let m=0,g=1,A=0,y=r[m];for(;;){let x=0;if(g=x)throw new Error("segment ids are not increasing")}if(y<0||y>=d)throw new Error(`Segment id ${y} out of range [0, ${d}), possibly because segmentIds input is not sorted.`);y>A&&f.fill(o,A*c,y*c);for(let b=m;b=l[0])throw new Error(`Bad: indices[${b}] == ${s[b]} out of range [0, ${l[0]})`);for(let k=0;ki)break}return AMath.sqrt(e)),sH=gt(ao,e=>Math.sqrt(e)),rH={kernelName:ao,backendName:"cpu",kernelFunc:sH},oI=Jt((e,t)=>{let n=e-t;return n*n}),aH=vn(lo,oI),oH={kernelName:lo,backendName:"cpu",kernelFunc:aH};function iI(e,t,n,s){let r=Le(e,t.dtype);for(let a=0;a0?0:o-i),p=0;p+=l*this.leftPad.length;for(let A=0;AA.forEach(y=>f[m++]=y);for(let A=0;A0){g(e[d+u-1]);for(let A=0;A0){let i=t[0];if(i!==0)throw new Error(`First split value must be 0, got ${i}`);for(let l=1;l=i;if(c=c&&t[l]<=n,!c)throw new Error(`Invalid split value ${t[l]}, must be in [${i}, ${n}]`);i=t[l]}if(i!==n)throw new Error(`Last split value must be data size. Expected ${n}, got ${i}`)}let r=s-1,a=v.getArrayFromDType("int32",s);if(n===0||s===0){let i=new Array(n);for(let l=0;l<=r;++l)a[l]=0;return[i,a]}a[0]=0;for(let i=1;i<=r;++i){let l=t[i]-t[i-1],c=0;this.nGramWidths.forEach(u=>{c+=this.getNumNGrams(l,u)}),this.preserveShort&&l>0&&c===0&&(c=1),a[i]=a[i-1]+c}let o=new Array(a[r]);for(let i=0;i{let d=t[i+1]-t[i],p=this.getNumNGrams(d,u);this.createNGrams(e,l,o,c,p,u),c+=p}),this.preserveShort&&c===a[i]){let u=t[i+1]-t[i];if(u===0)continue;let d=u+2*this.padWidth,p=1;this.createNGrams(e,l,o,c,p,d)}}return[o,a]}};function lI(e,t,n,s,r,a,o,i){return new iH(n,s,r,a,o,i).compute(e,t)}function lH(e,t,n,s){if(!e.length)return;if(t.length===0){for(let a=0;ae-t),uH=by((e,t,n,s)=>({real:e-n,imag:t-s})),Ty=vn(uo,dI,uH),cH={kernelName:uo,backendName:"cpu",kernelFunc:Ty};function pI(e,t){let n=new Array(e.rank);for(let r=0;r{let n=t.value-e.value;return n===0?e.index-t.index:n};function hI(e,t,n=0,s=e.length-1){for(;s>n;){if(s-n>600){let i=s-n+1,l=t-n+1,c=Math.log(i),u=.5*Math.exp(2*c/3),d=.5*Math.sqrt(c*u*(i-u)/i)*Math.sign(l-i/2),p=Math.max(n,Math.floor(t-l*u/i+d)),h=Math.min(s,Math.floor(t+(i-l)*u/i+d));hI(e,t,p,h)}let r=e[t],a=n,o=s;for(v.swap(e,n,t),Bd(e[s],r)>0&&v.swap(e,n,s);a0;)o=o-1}Bd(e[n],r)===0?v.swap(e,n,o):(o=o+1,v.swap(e,o,s)),o<=t&&(n=o+1),t<=o&&(s=o-1)}}function fI(e,t,n,s,r){let a=t[t.length-1],[o,i]=[e.length/a,a],l=v.getTypedArrayFromDType(n,o*s),c=v.getTypedArrayFromDType("int32",o*s);for(let d=0;df[x]={value:y,index:x}),s{for(let g=0;gnew xy,1);var gI=gt(Pa,e=>e>=0?e:Math.exp(e)-1),pH={kernelName:Pa,backendName:"cpu",kernelFunc:gI};function AI(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{alpha:a}=s;Ne([r],"leakyRelu");let o=v.sizeFromShape(r.shape),i=n.data.get(r.dataId).values,l=v.getTypedArrayFromDType("float32",o);for(let c=0;ce<0?t*e:e);function yI(e){let{inputs:t,backend:n}=e,{x:s,alpha:r}=t;Ne([s,r],"prelu");let a=n.data.get(s.dataId).values,o=n.data.get(r.dataId).values,[i,l]=fH(s.shape,r.shape,a,o,"float32");return n.makeTensorInfo(l,"float32",i)}var mH={kernelName:Ja,backendName:"cpu",kernelFunc:yI},xI=gt(Qa,e=>Math.max(0,e)),gH={kernelName:Qa,backendName:"cpu",kernelFunc:xI},bI=gt(to,e=>Math.min(Math.max(0,e),6)),AH={kernelName:to,backendName:"cpu",kernelFunc:bI};function Ny(e,t,n,s,r){if(n==="linear")return Or({inputs:{x:t},backend:e});if(n==="relu")return xI({inputs:{x:t},backend:e});if(n==="elu")return gI({inputs:{x:t},backend:e});if(n==="relu6")return bI({inputs:{x:t},backend:e});if(n==="prelu")return yI({inputs:{x:t,alpha:s},backend:e});if(n==="leakyrelu")return AI({inputs:{x:t},backend:e,attrs:{alpha:r}});if(n==="sigmoid")return sI({inputs:{x:t},backend:e});throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)}function Tt(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{shape:a}=s,o=v.sizeFromShape(r.shape),i=v.inferFromImplicitShape(a,o),l=v.sizeFromShape(i);v.assert(o===l,()=>`The new shape (${i}) has ${l} elements and the old shape (${r.shape}) has ${o} elements. The new shape and old shape must have the same number of elements.`),n.incRef(r.dataId);let c=n.data.get(r.dataId);if(c.complexTensorInfos!=null){let u=c.complexTensorInfos.real,d=c.complexTensorInfos.imag;u.shape=i,d.shape=i}return{dataId:r.dataId,shape:i,dtype:r.dtype}}var yH={kernelName:Ti,backendName:"cpu",kernelFunc:Tt};function vI(e){let{inputs:t,backend:n,attrs:s}=e,{a:r,b:a}=t,{transposeA:o,transposeB:i}=s;Ne([r,a],"matMul");let l=r.shape.length,c=a.shape.length,u=o?r.shape[l-2]:r.shape[l-1],d=i?a.shape[c-1]:a.shape[c-2],p=o?r.shape[l-1]:r.shape[l-2],h=i?a.shape[c-2]:a.shape[c-1],f=r.shape.slice(0,-2),m=a.shape.slice(0,-2),g=v.sizeFromShape(f),A=v.sizeFromShape(m),y=g===A||g===1||A===1;v.assert(l>=2&&c>=2&&y,()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${f}) and (${m}).`);let b=(g>A?r.shape.slice(0,-2):a.shape.slice(0,-2)).concat([p,h]);v.assert(u===d,()=>`Error in matMul: inner shapes (${u}) and (${d}) of Tensors with shapes ${r.shape} and ${a.shape} and transposeA=${o} and transposeB=${i} must match.`);let w=o?[g,u,p]:[g,p,u],k=i?[A,h,d]:[A,d,h],S=Tt({inputs:{x:r},backend:n,attrs:{shape:w}}),E=Tt({inputs:{x:a},backend:n,attrs:{shape:k}}),$=o?S.shape[1]:S.shape[2],F=o?S.shape[2]:S.shape[1],R=i?E.shape[1]:E.shape[2],P=Math.max(g,A),T=n.data.get(S.dataId).values,M=n.data.get(E.dataId).values,U=v.computeStrides(S.shape),H=v.computeStrides(E.shape),[z,X,ee]=o?[U[0],1,U[1]]:[U[0],U[1],1],[Y,ne,se]=i?[1,H[1],H[0]]:[H[1],1,H[0]],J=F*R,te=Le([P,F,R],S.dtype),ue=te.values,ce=n.blockSize;for(let be=0;beMath.acos(e)),kH={kernelName:Vl,backendName:"cpu",kernelFunc:wH},IH=gt(Ul,e=>Math.acosh(e)),SH={kernelName:Ul,backendName:"cpu",kernelFunc:IH};function CH(e){let{inputs:t,backend:n}=e,s=t;Ne(t,"addN");let r=s.map(i=>n.data.get(i.dataId).values),a=Le(s[0].shape,s[0].dtype),o=a.values;for(let i=0;iy&&(y=w,x=b)}h[g]=x}return c.forEach(g=>n.disposeIntermediateTensorInfo(g)),n.makeTensorInfo(u,"int32",h)}var _H={kernelName:ka,backendName:"cpu",kernelFunc:DH};function PH(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a}=s;Ne(r,"argMin");let o=v.parseAxisParam(a,r.shape),i=N.getAxesPermutation(o,r.shape.length),l=r,c=[];i!=null&&(l=Ds({inputs:{x:r},backend:n,attrs:{perm:i}}),c.push(l),o=N.getInnerMostAxes(o.length,l.shape.length)),o=[o[0]],N.assertAxesAreInnerMostDims("argMin",o,l.shape.length);let[u,d]=N.computeOutAndReduceShapes(l.shape,o),p=v.sizeFromShape(u),h=v.makeZerosTypedArray(p,"int32"),f=v.sizeFromShape(d),m=n.data.get(l.dataId).values;for(let g=0;gn.disposeIntermediateTensorInfo(g)),n.makeTensorInfo(u,"int32",h)}var FH={kernelName:jl,backendName:"cpu",kernelFunc:PH},OH=gt(ql,e=>Math.asin(e)),MH={kernelName:ql,backendName:"cpu",kernelFunc:OH},zH=gt(Xl,e=>Math.asinh(e)),LH={kernelName:Xl,backendName:"cpu",kernelFunc:zH},BH=gt(Kl,e=>Math.atan(e)),WH={kernelName:Kl,backendName:"cpu",kernelFunc:BH},VH=Jt((e,t)=>Math.atan2(e,t)),UH=vn(Yl,VH),GH={kernelName:Yl,backendName:"cpu",kernelFunc:UH},HH=gt(Zl,e=>Math.atanh(e)),jH={kernelName:Zl,backendName:"cpu",kernelFunc:HH};function Ey(e,t,n,s,r,a){let o=r.strideHeight,i=r.strideWidth,l=r.dilationHeight,c=r.dilationWidth,u=r.effectiveFilterHeight,d=r.effectiveFilterWidth,p=r.padInfo.top,h=r.padInfo.left,f=a==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,m=Le(r.outShape,n),g=m.values,A=r.outShape[1]*r.outShape[2]*r.outShape[3],y=r.outShape[2]*r.outShape[3],x=r.outShape[3];for(let b=0;bz?z=ue:a==="avg"&&(X+=ue,ee++)}if(isNaN(z))break}let Y=P+T*x+S;g[Y]=a==="avg"?X/ee:z}}}return m}function wI(e,t,n,s,r=!1,a=!1){let o=Le(s.outShape,"int32"),i=s.strideHeight,l=s.strideWidth,c=s.dilationHeight,u=s.dilationWidth,d=s.effectiveFilterHeight,p=s.effectiveFilterWidth,h=s.padInfo.top,f=s.padInfo.left,m=Le(t,n,e);for(let g=0;gF&&(F=H,r?R=a?((g*s.inHeight+P)*s.inWidth+M)*s.inChannels+A:(P*s.inWidth+M)*s.inChannels+A:R=T*p+U)}}o.set(R,g,y,k,A)}}return o}function kI(e,t,n,s,r,a){let o=r.strideDepth,i=r.strideHeight,l=r.strideWidth,c=r.dilationDepth,u=r.dilationHeight,d=r.dilationWidth,p=r.effectiveFilterDepth,h=r.effectiveFilterHeight,f=r.effectiveFilterWidth,m=r.padInfo.front,g=r.padInfo.top,A=r.padInfo.left,y=a==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,x=Le(r.outShape,n),b=x.values,w=r.outShape[1]*r.outShape[2]*r.outShape[3]*r.outShape[4],k=r.outShape[2]*r.outShape[3]*r.outShape[4],S=r.outShape[3]*r.outShape[4],E=r.outShape[4];for(let $=0;$we?we=yt:a==="avg"&&(Ce+=yt,Oe++),isNaN(we))break}if(isNaN(we))break}if(isNaN(we))break}let Ue=be+P;b[Ue]=a==="avg"?Ce/Oe:we}}}}return x}function qH(e,t){let n=Le(t.outShape,"int32"),s=t.strideDepth,r=t.strideHeight,a=t.strideWidth,o=t.dilationDepth,i=t.dilationHeight,l=t.dilationWidth,c=t.effectiveFilterDepth,u=t.effectiveFilterHeight,d=t.effectiveFilterWidth,p=t.padInfo.front,h=t.padInfo.top,f=t.padInfo.left;for(let m=0;m=T&&(T=ne,M=H*u*d+X*u+Y)}}}n.set(M,m,A,w,$,g)}}}return n}function XH(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t;Ne(r,"avgPool");let{filterSize:a,strides:o,pad:i,dimRoundingMode:l}=s,c=1;v.assert(N.eitherStridesOrDilationsAreOne(o,c),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${c}'`);let u=N.computePool2DInfo(r.shape,a,o,c,i,l),d;if(u.filterWidth===1&&u.filterHeight===1&&v.arraysEqual(u.inShape,u.outShape))d=Or({inputs:{x:r},backend:n});else{let p=n.data.get(r.dataId).values,h=v.computeStrides(r.shape),f=Ey(p,r.shape,r.dtype,h,u,"avg");d=n.makeTensorInfo(u.outShape,r.dtype,f.values)}return d}var KH={kernelName:Ia,backendName:"cpu",kernelFunc:XH};function ZH(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:l,dataFormat:c}=s;Ne(r,"avgPool3d");let u=N.computePool3DInfo(r.shape,a,o,1,i,l,c),d=n.data.get(r.dataId).values,p=kI(d,r.shape,r.dtype,v.computeStrides(r.shape),u,"avg");return n.makeTensorInfo(p.shape,"float32",p.values)}var YH={kernelName:Fc,backendName:"cpu",kernelFunc:ZH};function JH(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,{filterSize:o,strides:i,pad:l,dimRoundingMode:c}=s;Ne([r,a],"avgPool3DGrad");let u=N.computePool3DInfo(a.shape,o,i,1,l,c),d=u.strideDepth,p=u.strideHeight,h=u.strideWidth,f=u.filterDepth,m=u.filterHeight,g=u.filterWidth,A=u.dilationDepth,y=u.dilationHeight,x=u.dilationWidth,b=u.effectiveFilterDepth,w=u.effectiveFilterHeight,k=u.effectiveFilterWidth,S=b-1-u.padInfo.front,E=k-1-u.padInfo.left,$=w-1-u.padInfo.top,F=Le(a.shape,"float32"),R=1/(f*m*g),P=n.bufferSync(r);for(let T=0;T=u.outDepth||Math.floor(J)!==J))for(let te=0;te=u.outHeight||Math.floor(ue)!==ue))for(let ce=0;ce=u.outWidth||Math.floor(be)!==be)continue;ne+=P.get(T,J,ue,be,M)}}}F.set(ne*R,T,U,H,z,M)}return n.makeTensorInfo(F.shape,F.dtype,F.values)}var QH={kernelName:th,backendName:"cpu",kernelFunc:JH};function ej(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,o=a;Ne([r,a],"avgPoolGrad");let{filterSize:i,strides:l,pad:c}=s,u=N.computePool2DInfo(o.shape,i,l,1,c),d=u.strideHeight,p=u.strideWidth,h=u.filterHeight,f=u.filterWidth,m=u.dilationHeight,g=u.dilationWidth,A=u.effectiveFilterHeight,y=u.effectiveFilterWidth,x=y-1-u.padInfo.left,b=A-1-u.padInfo.top,w=Le(o.shape,"float32"),k=1/(h*f),S=n.data.get(r.dataId).values,E=Le(r.shape,"float32",S);for(let $=0;$=u.outHeight||Math.floor(z)!==z))for(let X=0;X=u.outWidth||Math.floor(ee)!==ee)continue;U+=E.get($,z,ee,F)}}w.set(U*k,$,R,P,F)}return n.makeTensorInfo(w.shape,w.dtype,w.values)}var tj={kernelName:eh,backendName:"cpu",kernelFunc:ej};function nj(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,scale:a,offset:o,mean:i,variance:l}=t;v.assert(i.shape.length===l.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),v.assert(o==null||i.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),v.assert(a==null||i.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks."),Ne([r,i,l,a,o],"batchNorm");let{varianceEpsilon:c}=s;c==null&&(c=.001);let u=n.data.get(r.dataId).values,d=n.data.get(i.dataId).values,p=n.data.get(l.dataId).values,h=a?n.data.get(a.dataId).values:new Float32Array([1]),f=o?n.data.get(o.dataId).values:new Float32Array([0]),m=new Float32Array(u.length),g=f.length,A=h.length,y=p.length,x=d.length,b=0,w=0,k=0,S=0;for(let E=0;E=g&&(b=0),w>=x&&(w=0),k>=A&&(k=0),S>=y&&(S=0);return n.makeTensorInfo(r.shape,r.dtype,m)}var sj={kernelName:za,backendName:"cpu",kernelFunc:nj};function rj(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,crops:o}=s;Ne([r],"batchToSpaceND");let i=a.reduce((A,y)=>A*y),l=N.getReshaped(r.shape,a,i),c=N.getPermuted(l.length,a.length),u=N.getReshapedPermuted(r.shape,a,i),d=N.getSliceBeginCoords(o,a.length),p=N.getSliceSize(u,o,a.length),h=Tt({inputs:{x:r},backend:n,attrs:{shape:l}}),f=Ds({inputs:{x:h},backend:n,attrs:{perm:c}}),m=Tt({inputs:{x:f},backend:n,attrs:{shape:u}}),g=pl({inputs:{x:m},backend:n,attrs:{begin:d,size:p}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}var aj={kernelName:si,backendName:"cpu",kernelFunc:rj};function oj(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,weights:a}=t,{size:o}=s,i=n.data.get(r.dataId).values,l=n.data.get(a.dataId).values,c=vy(i,l,a.dtype,a.shape,o);return n.makeTensorInfo([o],a.dtype,c)}var ij={kernelName:nh,backendName:"cpu",kernelFunc:oj};function lj(e){let{inputs:t,backend:n}=e,{s0:s,s1:r}=t,a=n.data.get(s.dataId).values,o=n.data.get(r.dataId).values,i=N.assertAndGetBroadcastShape(Array.from(a),Array.from(o));return n.makeTensorInfo([i.length],"int32",Int32Array.from(i))}var uj={kernelName:sh,backendName:"cpu",kernelFunc:lj},cj=gt(jr,(e,t)=>{let n=t;return e>n.clipValueMax?n.clipValueMax:e{let{x:t}=e.inputs,n=e.backend,s=new Float32Array(v.sizeFromShape(t.shape)),r=n.data.get(t.dataId),a=r.complexTensorInfos.real,o=r.complexTensorInfos.imag,i=n.data.get(a.dataId).values,l=n.data.get(o.dataId).values;for(let c=0;cm.shape),a);if(v.sizeFromShape(o)===0)return n.makeTensorInfo(o,t[0].dtype,[]);let i=t.filter(m=>v.sizeFromShape(m.shape)>0);if(i.length===1)return Or({inputs:{x:i[0]},backend:n});let l=i.map(m=>m.shape);if(N.assertParamsConsistent(l,a),i[0].dtype==="complex64"){let m=i.map(b=>dl({inputs:{input:b},backend:n})),g=i.map(b=>Vu({inputs:{input:b},backend:n})),A=Uu({inputs:m,backend:n,attrs:{axis:a}}),y=Uu({inputs:g,backend:n,attrs:{axis:a}}),x=xs({inputs:{real:A,imag:y},backend:n});return m.forEach(b=>n.disposeIntermediateTensorInfo(b)),g.forEach(b=>n.disposeIntermediateTensorInfo(b)),n.disposeIntermediateTensorInfo(A),n.disposeIntermediateTensorInfo(y),x}let c=i.map(m=>{let g=v.sizeFromShape(m.shape.slice(a));return Tt({inputs:{x:m},backend:n,attrs:{shape:[-1,g]}})}),u=c.map(m=>({vals:n.data.get(m.dataId).values,shape:m.shape}));o=N.computeOutShape(c.map(m=>m.shape),1);let d=c[0].shape[0]===1,p=wy(u,o,t[0].dtype,d),h=N.computeOutShape(i.map(m=>m.shape),a),f=n.makeTensorInfo(h,t[0].dtype,p);return c.forEach(m=>n.disposeIntermediateTensorInfo(m)),f}var mj={kernelName:ri,backendName:"cpu",kernelFunc:Uu};function II(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:o,pad:i,dataFormat:l,dilations:c,dimRoundingMode:u}=s;Ne([r,a],"conv2d");let d=N.convertConv2DDataFormat(l),p=N.computeConv2DInfo(r.shape,a.shape,o,c,i,u,!1,d),h=p.filterHeight,f=p.filterWidth,m=p.dilationHeight,g=p.dilationWidth,A=p.padInfo.left,y=p.padInfo.top,x=p.dataFormat==="channelsLast",b=new sn(p.outShape,r.dtype),w=v.computeStrides(r.shape),k=v.computeStrides(a.shape),S=w[0],E=x?w[1]:w[2],$=x?w[2]:1,F=x?1:w[1],R=b.strides[0],P=x?b.strides[1]:b.strides[2],T=x?b.strides[2]:1,M=x?1:b.strides[1],U=n.data.get(r.dataId).values,H=n.data.get(a.dataId).values,z=b.values;for(let X=0;X=p.inHeight)continue;let ce=te*k[0],be=ee+ue*E;for(let we=0;we=p.inWidth)continue;let rt=ce+Ue*k[1],ft=be+Xe*$,ut=rt;for(let ct=0;ct=c.inDepth)continue;let X=H*$[0],ee=R+z*E[1];for(let Y=0;Y=c.inHeight)continue;let ue=X+J*$[1],ce=ee+te*E[2];for(let be=0;be=c.inWidth)continue;let Xe=ue+Oe*$[2],rt=ce+Ue*c.inChannels,ft=Xe;for(let ut=0;utMath.cos(e)),Nj={kernelName:Ra,backendName:"cpu",kernelFunc:Tj},Ej=gt($a,e=>Math.cosh(e)),Rj={kernelName:$a,backendName:"cpu",kernelFunc:Ej};function $j(e){let{inputs:t,backend:n,attrs:s}=e,{image:r,boxes:a,boxInd:o}=t,{cropSize:i,method:l,extrapolationValue:c}=s,[u,d,p,h]=r.shape,f=a.shape[0],[m,g]=i,A=Le([f,m,g,h],"float32"),y=n.data.get(a.dataId).values,x=n.data.get(o.dataId).values,b=n.data.get(r.dataId).values,w=v.computeStrides(r.shape),k=v.computeStrides(A.shape);for(let S=0;S=u)continue;let M=m>1?(R-$)*(d-1)/(m-1):0,U=g>1?(P-F)*(p-1)/(g-1):0;for(let H=0;H1?$*(d-1)+H*M:.5*($+R)*(d-1);if(z<0||z>d-1){for(let X=0;X1?F*(p-1)+ne*U:.5*(F+P)*(p-1);if(se<0||se>p-1){for(let ce=0;ce1?F*(p-1)+X*U:.5*(F+P)*(p-1);if(ee<0||ee>p-1){for(let se=0;seA+f-y-1:(A,y)=>A+y;for(let A=0;A`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${o}`);let i=r.shape[0],l=r.shape[1],c=r.shape[2],u=r.shape[3],d=l*a,p=c*a,h=u/(a*a),f=n.data.get(r.dataId).values,m=new Float32Array(i*d*p*h),g=0;for(let A=0;A`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${p}'`);let h=N.computeConv2DInfo(r.shape,a.shape,o,p,i,c,!0),{filterHeight:f,filterWidth:m,dilationHeight:g,dilationWidth:A,padInfo:y}=h,x=y.left,b=y.top,w=h.outChannels/h.inChannels,k=new sn(h.outShape,r.dtype),S=n.data.get(r.dataId).values,E=n.data.get(a.dataId).values,$=k.values;for(let F=0;F=h.inHeight)continue;let X=H*d[0],ee=R+z*u[1];for(let Y=0;Y=h.inWidth)continue;let ue=X+J*d[1],ce=ee+te*h.inChannels,be=ne,we=ue;for(let Ce=0;Ce{let{x:s,filter:r}=e,{strides:a,pad:o,dilations:i}=n,l=t,c=l.data.get(s.dataId).values,u=s.shape.length,d=l.data.get(r.dataId).values,p=r.shape.length,{batchSize:h,inHeight:f,inWidth:m,inChannels:g,outHeight:A,outWidth:y,padInfo:x,strideHeight:b,strideWidth:w,filterHeight:k,filterWidth:S,dilationHeight:E,dilationWidth:$,outShape:F}=N.computeDilation2DInfo(s.shape,r.shape,a,o,"NHWC",i),R=v.sizeFromShape(F),P=F.length,T=v.getArrayFromDType(s.dtype,R);for(let U=0;U=0&&te=0&&cene&&(ne=Ce)}}}let se=v.locToIndex([U,H,X,Y],P,v.computeStrides(F));T[se]=ne}}}return{dataId:l.write(v.toTypedArray(T,s.dtype),F,s.dtype),shape:F,dtype:s.dtype}}},qj={kernelName:ph,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{let{x:s,filter:r,dy:a}=e,{strides:o,pad:i,dilations:l}=n,c=t,u=v.toNestedArray(s.shape,c.data.get(s.dataId).values),d=v.toNestedArray(r.shape,c.data.get(r.dataId).values),{batchSize:p,inHeight:h,inWidth:f,inChannels:m,outHeight:g,outWidth:A,padInfo:y,strideHeight:x,strideWidth:b,filterHeight:w,filterWidth:k,dilationHeight:S,dilationWidth:E,outShape:$}=N.computeDilation2DInfo(s.shape,r.shape,o,i,"NHWC",l);v.assert(a.rank===$.length,()=>`Error in ${ph}, dy must have the same rank as output ${$.length}, but got ${a.rank}`);let F=v.toNestedArray($,c.data.get(a.dataId).values),R=v.makeZerosNestedTypedArray(r.shape,r.dtype);for(let T=0;T=0&&J=0&&ueee&&(ee=ce,Y=se,ne=te)}}}R[Y][ne][X]+=F[T][M][H][X]}}}return{dataId:c.write(v.toTypedArray(R,s.dtype),r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},Xj={kernelName:dh,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{let{x:s,filter:r,dy:a}=e,{strides:o,pad:i,dilations:l}=n,c=t,u=v.toNestedArray(s.shape,c.data.get(s.dataId).values),d=v.toNestedArray(r.shape,c.data.get(r.dataId).values),{batchSize:p,inHeight:h,inWidth:f,inChannels:m,outHeight:g,outWidth:A,padInfo:y,strideHeight:x,strideWidth:b,filterHeight:w,filterWidth:k,dilationHeight:S,dilationWidth:E,outShape:$}=N.computeDilation2DInfo(s.shape,r.shape,o,i,"NHWC",l);v.assert(a.rank===$.length,()=>`Error in ${dh}, dy must have the same rank as output ${$.length}, but got ${a.rank}`);let F=v.toNestedArray($,c.data.get(a.dataId).values),R=v.makeZerosNestedTypedArray(s.shape,s.dtype);for(let T=0;T=0&&J=0&&ueee&&(ee=ce,Y=J,ne=ue)}}}R[T][Y][ne][X]+=F[T][M][H][X]}}}return{dataId:c.write(v.toTypedArray(R,s.dtype),s.shape,s.dtype),shape:s.shape,dtype:s.dtype}}};function Wd(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s;Ne(r,"sum");let i;r.dtype==="bool"?i=_o({inputs:{x:r},backend:n,attrs:{dtype:"int32"}}):i=Or({inputs:{x:r},backend:n});let l=i.shape.length,c=v.parseAxisParam(a,i.shape),u=N.getAxesPermutation(c,l),d=c,p=i;u!=null&&(p=Ds({inputs:{x:i},backend:n,attrs:{perm:u}}),d=N.getInnerMostAxes(d.length,l)),N.assertAxesAreInnerMostDims("sum",d,p.shape.length);let[h,f]=N.computeOutAndReduceShapes(p.shape,d),m=N.upcastType(p.dtype,"int32"),g=im(n,h,m),A=v.sizeFromShape(f),y=n.data.get(g.dataId).values,x=n.data.get(p.dataId).values;for(let b=0;b=0&&(p=Wd({inputs:{x:p},backend:n,attrs:{axis:c[m]-(o.length-h),keepDims:!1}}),f.push(p)),h--)}for(let m of f)m!==p&&n.disposeIntermediateTensorInfo(m);return p}var Yj={kernelName:Bc,backendName:"cpu",kernelFunc:Zj};function Jj(e){let{inputs:t,backend:n}=e,{dy:s,y:r}=t;Ne([s,r],"eluGrad");let a=new Float32Array(v.sizeFromShape(r.shape)),o=n.data.get(r.dataId).values,i=n.data.get(s.dataId).values;for(let l=0;l=1?a[l]=i[l]:a[l]=i[l]*(c+1)}return n.makeTensorInfo(r.shape,"float32",a)}var Qj={kernelName:hh,backendName:"cpu",kernelFunc:Jj},eq=N.ERF_P,tq=N.ERF_A1,nq=N.ERF_A2,sq=N.ERF_A3,rq=N.ERF_A4,aq=N.ERF_A5,oq=gt(Jl,e=>{let t=Math.sign(e),n=Math.abs(e),s=1/(1+eq*n);return t*(1-((((aq*s+rq)*s+sq)*s+nq)*s+tq)*s*Math.exp(-n*n))}),iq={kernelName:Jl,backendName:"cpu",kernelFunc:oq};function cm(e){let{inputs:t,backend:n,attrs:s}=e,{input:r}=t,{dim:a}=s,o=r.shape.length,i=r.shape.slice(),l=a;return a<0&&(v.assert(-(o+1)<=a,()=>`Axis must be in the interval [${-(o+1)}, ${o}]`),l=o+a+1),i.splice(l,0,1),Tt({inputs:{x:r},backend:n,attrs:{shape:i}})}var lq={kernelName:ui,backendName:"cpu",kernelFunc:cm},uq=Jt((e,t)=>e/t),Ry=vn(_a,uq),$y={kernelName:_a,backendName:"cpu",kernelFunc:Ry};function CI(e,t,n){let s=e.shape,r=s[0],a=s[1],o=n.data.get(e.dataId),i=o.complexTensorInfos.real,l=o.complexTensorInfos.imag,c=[r,a],u=v.sizeFromShape(c),d=v.getTypedArrayFromDType("float32",u),p=v.getTypedArrayFromDType("float32",u);for(let g=0;g{let{image:s}=e,r=n,a=v.getTypedArrayFromDType(s.dtype,v.sizeFromShape(s.shape)),[o,i,l,c]=s.shape,u=r.data.get(s.dataId).values;for(let p=0;p=0&&xMath.floor(e/t)),xq=vn(Ma,yq,null,"int32"),bq={kernelName:Ma,backendName:"cpu",kernelFunc:xq};function vq(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:c,dataFormat:u,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=s,m=II({inputs:{x:r,filter:a},backend:n,attrs:{strides:l,pad:c,dataFormat:u,dilations:d,dimRoundingMode:p}});if(o){let g=m;m=Ld({inputs:{a:m,b:o},backend:n}),n.disposeIntermediateTensorInfo(g)}if(h){let g=m;m=Ny(n,m,h,i,f),n.disposeIntermediateTensorInfo(g)}return m}var wq={kernelName:mo,backendName:"cpu",kernelFunc:vq};function kq(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:c,dataFormat:u,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=s,m=SI({inputs:{x:r,filter:a},backend:n,attrs:{strides:l,pad:c,dataFormat:u,dilations:d,dimRoundingMode:p}});if(o){let g=m;m=Ld({inputs:{a:m,b:o},backend:n}),n.disposeIntermediateTensorInfo(g)}if(h){let g=m;m=Ny(n,m,h,i,f),n.disposeIntermediateTensorInfo(g)}return m}var Iq={kernelName:go,backendName:"cpu",kernelFunc:kq};function Sq(e){let{inputs:t,backend:n}=e,{params:s,indices:r}=t,a=v.sizeFromShape(s.shape),o=r.shape,i=o[o.length-1],[l,c,u,d]=N.prepareAndValidate(s,r);if(c===0)return n.makeTensorInfo(l,s.dtype,[]);let p=n.data.get(r.dataId).values,h=n.bufferSync(s),f=V7(p,h,s.dtype,c,i,u,d,s.shape,a);return n.makeTensorInfo(l,s.dtype,f.values)}var Cq={kernelName:hi,backendName:"cpu",kernelFunc:Sq};function Tq(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,indices:a}=t,{axis:o,batchDims:i}=s;Ne([r,a],"gatherV2");let l=v.parseAxisParam(o,r.shape)[0],c=n.data.get(a.dataId).values,u=r.shape[l];for(let b=0;b=0,()=>`GatherV2: the index value ${w} is not in [0, ${u-1}]`)}let d=i;i==null&&(d=0);let p=v.sizeFromShape(a.shape),h=N.segment_util.collectGatherOpShapeInfo(r,a,l,d),f=Tt({inputs:{x:r},backend:n,attrs:{shape:[h.batchSize,h.outerSize,h.dimSize,h.sliceSize]}}),m=Tt({inputs:{x:a},backend:n,attrs:{shape:[h.batchSize,p/h.batchSize]}}),g=[h.batchSize,h.outerSize,p/h.batchSize,h.sliceSize],A=n.bufferSync(m),y=n.bufferSync(f),x=U7(y,A,g);return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),n.makeTensorInfo(h.outputShape,x.dtype,x.values)}var Nq={kernelName:pi,backendName:"cpu",kernelFunc:Tq};function Eq(e){let{inputs:t,backend:n}=e,{input:s}=t,r=v.sizeFromShape(s.shape),a=s.shape[s.shape.length-1],o=r/a,i=Tt({inputs:{x:s},backend:n,attrs:{shape:[o,a]}}),l=CI(i,!0,n),c=Tt({inputs:{x:l},backend:n,attrs:{shape:s.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(l),c}var Rq={kernelName:mh,backendName:"cpu",kernelFunc:Eq},$q=gt(eu,e=>Number.isFinite(e)?1:0,"bool"),Dq={kernelName:eu,backendName:"cpu",kernelFunc:$q},_q=gt(tu,e=>Math.abs(e)===1/0?1:0,"bool"),Pq={kernelName:tu,backendName:"cpu",kernelFunc:_q},Fq=gt(nu,e=>Number.isNaN(e)?1:0,"bool"),Oq={kernelName:nu,backendName:"cpu",kernelFunc:Fq};function Mq(e){let{backend:t,attrs:n}=e,{start:s,stop:r,num:a}=n,o=X7(s,r,a);return t.makeTensorInfo([o.length],"float32",o)}var zq={kernelName:gh,backendName:"cpu",kernelFunc:Mq},Lq=gt(su,e=>Math.log1p(e)),Bq={kernelName:su,backendName:"cpu",kernelFunc:Lq},Wq=Jt((e,t)=>e&&t),Vq=vn(yi,Wq,null,"bool"),Uq={kernelName:yi,backendName:"cpu",kernelFunc:Vq},Gq=gt(ru,e=>e?0:1,"bool"),Hq={kernelName:ru,backendName:"cpu",kernelFunc:Gq},jq=Jt((e,t)=>e||t),qq=vn(Vc,jq,null,"bool"),Xq={kernelName:Vc,backendName:"cpu",kernelFunc:qq};function Kq(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{depthRadius:a,bias:o,alpha:i,beta:l}=s;Ne(r,"LRN");let c=r.shape[3],u=c-1,d=n.data.get(r.dataId).values,p=v.sizeFromShape(r.shape),h=new Float32Array(p);function f(m){let g=m%c,A=m-g+Math.max(0,g-a),y=m-g+Math.min(g+a,u),x=0;for(;A<=y;A++){let b=d[A];x+=b*b}return x}for(let m=0;m`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${c}'`);let u=N.computePool2DInfo(r.shape,a,o,c,i,l),d;if(u.filterWidth===1&&u.filterHeight===1&&v.arraysEqual(u.inShape,u.outShape))d=Or({inputs:{x:r},backend:n});else{let p=n.data.get(r.dataId).values,h=v.computeStrides(r.shape),f=Ey(p,r.shape,r.dtype,h,u,"max");d=n.makeTensorInfo(u.outShape,r.dtype,f.values)}return d}var tX={kernelName:Ga,backendName:"cpu",kernelFunc:eX};function nX(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:l,dataFormat:c}=s;Ne(r,"maxPool3d");let u=N.computePool3DInfo(r.shape,a,o,1,i,l,c),d=n.data.get(r.dataId).values,p=kI(d,r.shape,r.dtype,v.computeStrides(r.shape),u,"max");return n.makeTensorInfo(p.shape,"float32",p.values)}var sX={kernelName:Gc,backendName:"cpu",kernelFunc:nX};function rX(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,{filterSize:o,strides:i,pad:l,dimRoundingMode:c}=s;Ne([r,a],"maxPool3DGrad");let u=N.computePool3DInfo(a.shape,o,i,1,l,c),d=n.bufferSync(a),p=qH(d,u),h=u.strideDepth,f=u.strideHeight,m=u.strideWidth,g=u.dilationDepth,A=u.dilationHeight,y=u.dilationWidth,x=u.effectiveFilterDepth,b=u.effectiveFilterHeight,w=u.effectiveFilterWidth,k=x-1-u.padInfo.front,S=w-1-u.padInfo.left,E=b-1-u.padInfo.top,$=Le(a.shape,"float32"),F=n.bufferSync(r);for(let R=0;R=u.outDepth||Math.floor(ne)!==ne))for(let se=0;se=u.outHeight||Math.floor(J)!==J))for(let te=0;te=u.outWidth||Math.floor(ue)!==ue)continue;let ce=x*b*w-1-p.get(R,ne,J,ue,P),be=Y*b*w+se*w+te,we=ce===be?1:0;if(we===0)continue;ee+=F.get(R,ne,J,ue,P)*we}}}$.set(ee,R,T,M,U,P)}return n.makeTensorInfo($.shape,$.dtype,$.values)}var aX={kernelName:xh,backendName:"cpu",kernelFunc:rX};function oX(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a,output:o}=t,i=a;Ne([a,o],"maxPoolGrad");let{filterSize:l,strides:c,pad:u,dimRoundingMode:d}=s,p=N.computePool2DInfo(i.shape,l,c,1,u,d),h=n.data.get(i.dataId).values,f=Le(p.outShape,i.dtype,wI(h,i.shape,i.dtype,p).values),m=p.strideHeight,g=p.strideWidth,A=p.dilationHeight,y=p.dilationWidth,x=p.effectiveFilterHeight,b=p.effectiveFilterWidth,w=b-1-p.padInfo.left,k=x-1-p.padInfo.top,S=Le(i.shape,"float32"),E=n.data.get(r.dataId).values,$=Le(r.shape,"float32",E);for(let F=0;F=p.outHeight||Math.floor(X)!==X))for(let ee=0;ee=p.outWidth||Math.floor(Y)!==Y)continue;let ne=x*b-1-f.get(F,X,Y,R),se=z*b+ee,J=ne===se?1:0;if(J===0)continue;H+=$.get(F,X,Y,R)*J}}S.set(H,F,P,T,R)}return n.makeTensorInfo(S.shape,S.dtype,S.values)}var iX={kernelName:yh,backendName:"cpu",kernelFunc:oX};function lX(e,t,n,s,r){let a=v.computeStrides(t),o=Ey(e,t,n,a,r,"max"),i=wI(e,t,n,r,!0,s);return[o.values,i.values]}var uX={kernelName:bh,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:s}=e,{filterSize:r,strides:a,pad:o,includeBatchInIndex:i}=t,l=n;Ne(s,"MaxPoolWithArgmax");let c=l.data.get(s.dataId).values,u=N.computePool2DInfo(s.shape,r,a,[1,1],o),[d,p]=lX(c,s.shape,s.dtype,i,u),h=l.write(d,u.outShape,s.dtype),f=l.write(p,u.outShape,s.dtype);return[{dataId:h,shape:u.outShape,dtype:s.dtype},{dataId:f,shape:u.outShape,dtype:"int32"}]}};function cX(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s,i=v.parseAxisParam(a,r.shape),c=N.computeOutAndReduceShapes(r.shape,i)[1],u=v.sizeFromShape(c),d=[],p=n.makeTensorInfo([],"float32",new Float32Array([u]));d.push(p);let h=_o({inputs:{x:r},backend:n,attrs:{dtype:"float32"}});d.push(h);let f=Ry({inputs:{a:h,b:p},backend:n});d.push(f);let m=Wd({inputs:{x:f},backend:n,attrs:{axis:a,keepDims:o}});return d.forEach(g=>n.disposeIntermediateTensorInfo(g)),m}var dX={kernelName:Ha,backendName:"cpu",kernelFunc:cX};function pX(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s;Ne(r,"min");let i=v.parseAxisParam(a,r.shape),l=i,c=N.getAxesPermutation(l,r.shape.length),u=r;c!=null&&(u=Ds({inputs:{x:r},backend:n,attrs:{perm:c}}),l=N.getInnerMostAxes(l.length,r.shape.length)),N.assertAxesAreInnerMostDims("min",l,u.shape.length);let[d,p]=N.computeOutAndReduceShapes(u.shape,l),h=v.sizeFromShape(p),f=v.makeZerosTypedArray(v.sizeFromShape(d),u.dtype),m=n.data.get(u.dataId).values;for(let A=0;Ax[0]+r.shape[b]+x[1]),l=a.map(x=>x[0]),c=a.map((x,b)=>x[0]+r.shape[b]),u=o==="reflect"?0:1,d=n.data.get(r.dataId).values,p=r.shape.length,h=v.computeStrides(r.shape),f=v.sizeFromShape(i),m=i.length,g=v.computeStrides(i),A=v.getTypedArrayFromDType(r.dtype,f);for(let x=0;x=c[k]&&(b[k]=(c[k]-1)*2-b[k]+u);b=b.map((k,S)=>k-l[S]);let w=v.locToIndex(b,p,h);A[x]=d[w]}return{dataId:n.write(A,i,r.dtype),shape:i,dtype:r.dtype}}var mX={kernelName:Xa,backendName:"cpu",kernelFunc:fX},gX=Jt((e,t)=>{let n=e%t;return e<0&&t<0||e>=0&&t>=0?n:(n+t)%t}),AX=vn(au,gX),yX={kernelName:au,backendName:"cpu",kernelFunc:AX};function NI(e){let{inputs:t,backend:n,attrs:s}=e,{logits:r}=t,{dim:a}=s,o=r.shape.length,i=a;if(i===-1&&(i=o-1),i!==o-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${o} and dim was ${i}`);let l=v.parseAxisParam([i],r.shape),c=TI({inputs:{x:r},backend:n,attrs:{reductionIndices:l,keepDims:!1}}),u=N.expandShapeToKeepDim(c.shape,l),d=Tt({inputs:{x:c},backend:n,attrs:{shape:u}}),p=Ty({inputs:{a:r,b:d},backend:n}),h=L7({inputs:{x:p},backend:n}),f=Wd({inputs:{x:h},backend:n,attrs:{axis:l,keepDims:!1}}),m=Tt({inputs:{x:f},backend:n,attrs:{shape:u}}),g=Ry({inputs:{a:h,b:m},backend:n});return n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}var xX={kernelName:io,backendName:"cpu",kernelFunc:NI},bX=Qo(Kp());function vX(e){let{inputs:t,backend:n,attrs:s}=e,{logits:r}=t,{numSamples:a,seed:o,normalized:i}=s;Ne(r,"multinomial");let l=i?r:NI({inputs:{logits:r},backend:n,attrs:{dim:-1}}),c=l.shape[0],u=l.shape[1],d=n.data.get(l.dataId).values,p=[c,a],h=v.makeZerosTypedArray(v.sizeFromShape(p),"int32");for(let f=0;f=0&&u[d]{v.assertShapesMatch(a,u.shape,"All tensors passed to stack must have matching shapes"),v.assert(o===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],l=t.map(u=>{let d=cm({inputs:{input:u},backend:n,attrs:{dim:r}});return i.push(d),d}),c=Uu({inputs:l,backend:n,attrs:{axis:r}});return i.forEach(u=>n.disposeIntermediateTensorInfo(u)),c}var OX={kernelName:Si,backendName:"cpu",kernelFunc:RI};function MX(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{paddings:a,constantValue:o}=s;Ne(r,"pad");let i=a.map((y,x)=>y[0]+r.shape[x]+y[1]),l=a.map(y=>y[0]),c=n.data.get(r.dataId).values,u=v.sizeFromShape(r.shape),d=r.shape.length,p=v.computeStrides(r.shape),h=v.sizeFromShape(i),f=i.length,m=v.computeStrides(i),g=v.getTypedArrayFromDType(r.dtype,h);o!==0&&g.fill(o);for(let y=0;yk+l[S]),w=v.locToIndex(b,f,m);g[w]=c[y]}return{dataId:n.write(g,i,r.dtype),shape:i,dtype:r.dtype}}var $I={kernelName:Za,backendName:"cpu",kernelFunc:MX},zX=Jt((e,t)=>Math.pow(e,t)),LX=vn(Ya,zX),BX={kernelName:Ya,backendName:"cpu",kernelFunc:LX};function WX(e){let{backend:t,attrs:n}=e,{start:s,stop:r,dtype:a,step:o}=n,i=Sy(s,r,o,a);return t.makeTensorInfo([i.length],a,i)}var VX={kernelName:iu,backendName:"cpu",kernelFunc:WX},UX=gt(lu,e=>1/e),GX={kernelName:lu,backendName:"cpu",kernelFunc:UX};function HX(e){let{inputs:t,backend:n,attrs:s}=e,{images:r}=t,{alignCorners:a,halfPixelCenters:o,size:i}=s;Ne(r,"resizeBilinear");let l=v.computeStrides(r.shape),[c,u]=i,[d,p,h,f]=r.shape,m=n.data.get(r.dataId).values,g=new Float32Array(v.sizeFromShape([d,c,u,f])),A=[a&&c>1?p-1:p,a&&u>1?h-1:h],y=[a&&c>1?c-1:c,a&&u>1?u-1:u],x=0,b=A[0]/y[0],w=A[1]/y[1];for(let k=0;k1?c-1:c,o&&h>1?u-1:u],g=[o&&p>1?p-1:p,o&&h>1?h-1:h],A=m[0]/g[0],y=m[1]/g[1],x=n.data.get(a.dataId).values,b=0;for(let w=0;w1?p-1:p,a&&u>1?h-1:h],y=[a&&c>1?c-1:c,a&&u>1?u-1:u],x=A[0]/y[0],b=A[1]/y[1],w=0;for(let k=0;k1?u-1:u,o&&f>1?d-1:d],y=[o&&h>1?h-1:h,o&&f>1?f-1:f],x=A[0]/y[0],b=A[1]/y[1],w=1/x,k=1/b,S=Math.ceil(w)*2+2,E=Math.ceil(k)*2+2;for(let $=0;$=h)continue;let J=F+se*l[1],te=se*x,ue=Math.min(u-1,o?Math.round(te):Math.floor(te));if(R===ue)for(let ce=0;ce=f)continue;let we=J+be*l[2],Ce=be*b,Oe=Math.min(d-1,o?Math.round(Ce):Math.floor(Ce));U===Oe&&(Y+=g[we+ee])}}m[H+ee]=Y}}}}return n.makeTensorInfo(r.shape,r.dtype,m)}var JX={kernelName:wh,backendName:"cpu",kernelFunc:YX};function QX(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{dims:a}=s;Ne(r,"reverse");let o=r.shape.length,i=v.parseAxisParam(a,r.shape);if(o===0)return Or({inputs:{x:r},backend:n});let l=new sn(r.shape,r.dtype),c=n.bufferSync(r);for(let u=0;up[h]=r.shape[h]-1-p[h]),l.set(c.get(...p),...d)}return n.makeTensorInfo(l.shape,l.dtype,l.values)}var eK={kernelName:Ni,backendName:"cpu",kernelFunc:QX},tK={kernelName:Vi,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:s}=e,{radians:r,fillValue:a,center:o}=t,i=n,l=v.getTypedArrayFromDType(s.dtype,v.sizeFromShape(s.shape)),[c,u,d,p]=s.shape,[h,f]=N.getImageCenter(o,u,d),m=255,g=Math.sin(r),A=Math.cos(r),y=i.data.get(s.dataId).values;for(let b=0;b=0&&M=0&&U{let t=Math.floor(e);return e-t<.5?Math.floor(e):e-t>.5?Math.ceil(e):t%2==0?t:t+1}),sK={kernelName:Ei,backendName:"cpu",kernelFunc:nK};function DI(e,t,n,s,r,a,o,i,l,c){let u=[s/r,r],d=e.values,p=t.values;if(s===0)return Le(n,t.dtype);let h=Le(u,t.dtype);h.values.fill(l);for(let f=0;f=s/r)throw new Error(`Invalid indices: ${m} does not index into ${n}`);for(let A=0;A1||r.shape.length===1?1:v.sizeFromShape(r.shape.slice(1));for(let f=0;fe>=0?uK*e:lK*(Math.exp(e)-1)),dK={kernelName:cu,backendName:"cpu",kernelFunc:cK},pK=gt(du,e=>e<0?-1:e>0?1:0),hK={kernelName:du,backendName:"cpu",kernelFunc:pK},fK=gt(so,e=>Math.sin(e)),mK={kernelName:so,backendName:"cpu",kernelFunc:fK},gK=gt(_i,e=>Math.sinh(e)),AK={kernelName:_i,backendName:"cpu",kernelFunc:gK},yK=11920928955078125e-23,_I=Math.log(yK)+2,xK=gt(pu,e=>{let t=e>-_I,n=e<_I,s=Math.exp(e),r;return n?r=s:t?r=e:r=Math.log(1+s),r}),bK={kernelName:pu,backendName:"cpu",kernelFunc:xK};function vK(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,paddings:o}=s;Ne([r],"spaceToBatchND");let i=v.sizeFromShape(a),l=[[0,0]];l.push(...o);for(let k=1+a.length;k{let p=[...u];p[i]=d;let h=pl({inputs:{x:r},backend:n,attrs:{begin:c,size:p}});return c[i]+=d,h})}var PK={kernelName:Fi,backendName:"cpu",kernelFunc:_K},FK={kernelName:hu,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{let{x:n}=e,s=t;Ne(n,"square");let r=s.data.get(n.dataId).values,a=new Float32Array(r.length);for(let i=0;i{let n=t;return isNaN(e)?NaN:e>0?1:n.alpha}),MK={kernelName:ho,backendName:"cpu",kernelFunc:OK};function zK(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,end:o,strides:i,beginMask:l,endMask:c,ellipsisMask:u,newAxisMask:d,shrinkAxisMask:p}=s;Ne(r,"stridedSlice");let{nonStrided:h,$begin:f,$strides:m,size:g,newShape:A,outShape:y}=An.sliceInfo(r.shape,a,o,i,l,c,u,d,p),x=Tt({inputs:{x:r},backend:n,attrs:{shape:A}}),b;if(h){let k=pl({inputs:{x},backend:n,attrs:{begin:f,size:g}});b=Tt({inputs:{x:k},backend:n,attrs:{shape:y}}),n.disposeIntermediateTensorInfo(k)}else if(y.some(k=>k===0))b=n.makeTensorInfo(y,r.dtype,[]);else{let k=n.bufferSync(x),S=iI(y,k,m,f);b=n.makeTensorInfo(S.shape,S.dtype,S.values)}let w=Tt({inputs:{x:b},backend:n,attrs:{shape:y}});return n.disposeIntermediateTensorInfo(x),n.disposeIntermediateTensorInfo(b),w}var LK={kernelName:Oi,backendName:"cpu",kernelFunc:zK};function BK(e){let{inputs:t,backend:n,attrs:s}=e,{separator:r,nGramWidths:a,leftPad:o,rightPad:i,padWidth:l,preserveShortSequences:c}=s,{data:u,dataSplits:d}=t,p=n.data.get(u.dataId).values,h=n.data.get(d.dataId).values,[f,m]=lI(p,h,r,a,o,i,l,c);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(d.shape,"int32",m)]}var WK={kernelName:qc,backendName:"cpu",kernelFunc:BK};function VK(e){let{inputs:t,backend:n,attrs:s}=e,{skipEmpty:r}=s,{input:a,delimiter:o}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(a.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${a.shape}`);if(o.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${o.shape}`);let i=n.data.get(a.dataId).values,l=n.data.get(o.dataId).values[0],[c,u,d]=uI(i,l,r),p=u.length;return[n.makeTensorInfo([p,2],"int32",c),n.makeTensorInfo([p],"string",u),n.makeTensorInfo([2],"int32",new Int32Array(d))]}var UK={kernelName:Nh,backendName:"cpu",kernelFunc:VK};function GK(e){let{inputs:t,backend:n,attrs:s}=e,{numBuckets:r}=s,{input:a}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(r<=0)throw new Error("Number of buckets must be at least 1");let o=n.data.get(a.dataId).values,i=cI(o,r);return n.makeTensorInfo(a.shape,"int32",i)}var HK={kernelName:Eh,backendName:"cpu",kernelFunc:GK},jK=gt(Mi,e=>Math.tan(e)),qK={kernelName:Mi,backendName:"cpu",kernelFunc:jK},XK=gt(co,e=>Math.tanh(e)),KK={kernelName:co,backendName:"cpu",kernelFunc:XK};function ZK(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{reps:a}=s;Ne(r,"tile");let o=pI(n.bufferSync(r),a);return n.makeTensorInfo(o.shape,o.dtype,o.values)}var YK={kernelName:qr,backendName:"cpu",kernelFunc:ZK};function JK(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{k:a,sorted:o}=s;Ne(r,"topk");let i=n.data.get(r.dataId).values,[l,c]=fI(i,r.shape,r.dtype,a,o);return[n.makeTensorInfo(l.shape,l.dtype,l.values),n.makeTensorInfo(c.shape,c.dtype,c.values)]}var QK={kernelName:zi,backendName:"cpu",kernelFunc:JK};function eZ(e){let{inputs:t,attrs:n,backend:s}=e,{image:r,transforms:a}=t,{interpolation:o,fillMode:i,fillValue:l,outputShape:c}=n,[u,d,p,h]=r.shape,[f,m]=c!=null?c:[d,p],g=[u,f,m,h],A=v.computeStrides(r.shape),y=A[0],x=A[1],b=A[2],w=v.getTypedArrayFromDType(r.dtype,v.sizeFromShape(g));w.fill(l);let k=s.data.get(r.dataId).values,S=s.data.get(a.dataId).values;for(let P=0;Pt-1)if(t<=1)n=0;else{let s=2*t;n-=s*Math.trunc(n/s),n>=t&&(n=s-n-1)}return v.clamp(0,n,t-1)}function sZ(e,t){let n=e;if(n<0)if(t<=1)n=0;else{let s=t-1;n+=t*(Math.trunc(-n/s)+1)}else if(n>t-1)if(t<=1)n=0;else{let s=t-1;n-=t*Math.trunc(n/s)}return v.clamp(0,n,t-1)}function rZ(e,t){return e}function aZ(e,t){return v.clamp(0,e,t-1)}function Vd(e,t,n,s,r,a,o,i,l,c,u){let d=o*s+i*r+l*a+c;return 0<=i&&in.disposeIntermediateTensorInfo(f)),h}var hZ={kernelName:Xc,backendName:"cpu",kernelFunc:pZ},fZ=[vH,hG,kH,SH,xG,TH,EH,$H,_H,FH,MH,LH,WH,GH,jH,KH,YH,QH,tj,xH,sj,aj,ij,uj,AG,vG,dj,fG,hj,mj,yj,bj,gj,Ij,Cj,wj,Nj,Rj,Dj,Pj,Oj,zj,Lj,Wj,Uj,Hj,jj,Xj,qj,$y,Yj,pH,Qj,wG,iq,kG,lq,SG,fq,mq,Aq,TG,bq,wq,Iq,Cq,Nq,EG,$G,mG,Rq,fj,Dq,Pq,Oq,hH,_G,FG,zq,MG,Bq,Uq,Hq,Xq,Zq,Jq,LG,tX,sX,aX,iX,uX,Qq,dX,hX,WG,mX,yX,wX,UG,HG,SX,NX,$X,qG,_X,FX,OX,$I,BX,mH,ZG,VX,gG,GX,gH,AH,yH,jX,XX,ZX,JX,eK,tK,sK,JG,aK,iK,dK,eH,hK,mK,AK,tH,xX,bK,wK,IK,CK,NK,RK,DK,PK,rH,FK,oH,MK,LK,WK,UK,HK,cH,Kj,qK,KK,YK,QK,XG,tZ,uZ,dZ,hZ,PX];for(let e of fZ)Kr(e);var FI={};ze(FI,{assertNotComplex:()=>Hu,bindCanvasToFramebuffer:()=>CZ,bindColorTextureToFramebuffer:()=>mm,bindTextureToProgramUniformSampler:()=>ZI,bindTextureUnit:()=>qI,bindVertexBufferToProgramAttribute:()=>Oy,callAndCheck:()=>Se,canBeRepresented:()=>OI,createFragmentShader:()=>LI,createFramebuffer:()=>jI,createProgram:()=>BI,createStaticIndexBuffer:()=>UI,createStaticVertexBuffer:()=>VI,createTexture:()=>GI,createVertexShader:()=>zI,getBatchDim:()=>fl,getExtensionOrThrow:()=>Hd,getFramebufferErrorMessage:()=>YI,getMaxTexturesInShader:()=>tS,getNumChannels:()=>IZ,getProgramUniformLocation:()=>KI,getProgramUniformLocationOrThrow:()=>XI,getRowsCols:()=>ml,getShapeAs3D:()=>gm,getTextureShapeFromLogicalShape:()=>QI,getWebGLDisjointQueryTimerVersion:()=>nS,getWebGLErrorMessage:()=>MI,getWebGLMaxTextureSize:()=>eS,hasExtension:()=>Ps,isCapableOfRenderingToFloatTexture:()=>sS,isDownloadFloatTextureEnabled:()=>rS,isReshapeFree:()=>qd,isWebGLFenceEnabled:()=>aS,isWebGLVersionEnabled:()=>zy,linkProgram:()=>WI,resetMaxTextureSize:()=>TZ,resetMaxTexturesInShader:()=>NZ,unbindColorTextureFromFramebuffer:()=>My,unbindTextureUnit:()=>SZ,validateFramebuffer:()=>jd,validateProgram:()=>fm,validateTextureSize:()=>HI});var hl={},Py={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function pm(e,t){hl[e]=t}function Mr(e){if(!(e in hl)){let n=gZ(e);if(n!==null)hl[e]=n;else return console.log("Could not get context for WebGL version",e),null}let t=hl[e];return t.isContextLost()?(delete hl[e],Mr(e)):(t.disable(t.DEPTH_TEST),t.disable(t.STENCIL_TEST),t.disable(t.BLEND),t.disable(t.DITHER),t.disable(t.POLYGON_OFFSET_FILL),t.disable(t.SAMPLE_COVERAGE),t.enable(t.SCISSOR_TEST),t.enable(t.CULL_FACE),t.cullFace(t.BACK),hl[e])}function mZ(e){if(typeof OffscreenCanvas!="undefined"&&e===2)return new OffscreenCanvas(300,150);if(typeof document!="undefined")return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}function gZ(e){if(e!==1&&e!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");let t=mZ(e);return t.addEventListener("webglcontextlost",n=>{n.preventDefault(),delete hl[e]},!1),e===1?t.getContext("webgl",Py)||t.getContext("experimental-webgl",Py):t.getContext("webgl2",Py)}var Ud;(function(e){e[e.DENSE=0]="DENSE",e[e.SHARED_BATCH=1]="SHARED_BATCH"})(Ud||(Ud={}));var _s;(function(e){e[e.RENDER=0]="RENDER",e[e.UPLOAD=1]="UPLOAD",e[e.PIXELS=2]="PIXELS",e[e.DOWNLOAD=3]="DOWNLOAD"})(_s||(_s={}));var Cn;(function(e){e[e.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",e[e.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",e[e.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",e[e.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",e[e.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"})(Cn||(Cn={}));function Gd(e,t){return[t,e]}function AZ(e,t){return e*t}function hm(e){let t=v.sizeFromShape(e),n=Math.ceil(t/4);return v.sizeToSquarishShape(n)}function Gu(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function yZ(e,t){let[n,s]=Gu(e,t);return n*s*4}function Fy(e,t){let n=e,s,r,a,o,i,l,c,u,d,p;return K().getNumber("WEBGL_VERSION")===2?(s=n.R32F,r=n.R16F,a=n.RGBA16F,o=n.RGBA32F,i=n.RED,c=4,u=1,d=n.HALF_FLOAT,p=n.FLOAT):(s=e.RGBA,r=e.RGBA,a=e.RGBA,o=n.RGBA,i=e.RGBA,c=4,u=4,d=t!=null?t.HALF_FLOAT_OES:null,p=e.FLOAT),l=e.RGBA,{internalFormatFloat:s,internalFormatHalfFloat:r,internalFormatPackedHalfFloat:a,internalFormatPackedFloat:o,textureFormatFloat:i,downloadTextureFormat:l,downloadUnpackNumChannels:c,defaultNumChannels:u,textureTypeHalfFloat:d,textureTypeFloat:p}}function Se(e,t){let n=t();return K().getBool("DEBUG")&&xZ(e),n}function xZ(e){let t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+MI(e,t))}var bZ=596e-10,vZ=65504;function OI(e){return!!(K().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||e===0||bZe.getExtension(t),'Extension "'+t+'" not supported on this browser.')}function zI(e,t){let n=oa(e,()=>e.createShader(e.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(Se(e,()=>e.shaderSource(n,t)),Se(e,()=>e.compileShader(n)),e.getShaderParameter(n,e.COMPILE_STATUS)===!1)throw console.log(e.getShaderInfoLog(n)),new Error("Failed to compile vertex shader.");return n}function LI(e,t){let n=oa(e,()=>e.createShader(e.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(Se(e,()=>e.shaderSource(n,t)),Se(e,()=>e.compileShader(n)),e.getShaderParameter(n,e.COMPILE_STATUS)===!1)throw kZ(t,e.getShaderInfoLog(n)),new Error("Failed to compile fragment shader.");return n}var wZ=/ERROR: [0-9]+:([0-9]+):/g;function kZ(e,t){let n=wZ.exec(t);if(n==null){console.log(`Couldn't parse line number in error: ${t}`),console.log(e);return}let s=+n[1],r=e.split(` + ${a.shape}`);let o=n.data.get(s.dataId).values,i=n.data.get(r.dataId).values,l=n.data.get(a.dataId).values,[c,u]=Cy(o,s.shape,s.dtype,i,l);return n.makeTensorInfo(u,s.dtype,c)}var RK={kernelName:Th,backendName:"cpu",kernelFunc:EK};function $K(e){let{inputs:t,backend:n,attrs:s}=e,{sparseIndices:r,sparseValues:a,defaultValue:o}=t,{outputShape:i}=s,{sliceRank:l,numUpdates:c,sliceSize:u,strides:d,outputSize:p}=N.calculateShapes(a,r,i),h=!1,f=n.bufferSync(r),m=n.bufferSync(a),g=n.data.get(o.dataId).values[0],A=DI(f,m,i,p,u,c,l,d,g,h);return n.makeTensorInfo(i,A.dtype,A.values)}var DK={kernelName:jc,backendName:"cpu",kernelFunc:$K};function _K(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{numOrSizeSplits:a,axis:o}=s,i=v.parseAxisParam(o,r.shape)[0],l=N.prepareSplitSize(r,a,i),c=new Array(r.shape.length).fill(0),u=r.shape.slice();return l.map(d=>{let p=[...u];p[i]=d;let h=pl({inputs:{x:r},backend:n,attrs:{begin:c,size:p}});return c[i]+=d,h})}var PK={kernelName:Fi,backendName:"cpu",kernelFunc:_K},FK={kernelName:hu,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{let{x:n}=e,s=t;Ne(n,"square");let r=s.data.get(n.dataId).values,a=new Float32Array(r.length);for(let i=0;i{let n=t;return isNaN(e)?NaN:e>0?1:n.alpha}),MK={kernelName:ho,backendName:"cpu",kernelFunc:OK};function zK(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,end:o,strides:i,beginMask:l,endMask:c,ellipsisMask:u,newAxisMask:d,shrinkAxisMask:p}=s;Ne(r,"stridedSlice");let{nonStrided:h,$begin:f,$strides:m,size:g,newShape:A,outShape:y}=An.sliceInfo(r.shape,a,o,i,l,c,u,d,p),x=Tt({inputs:{x:r},backend:n,attrs:{shape:A}}),b;if(h){let k=pl({inputs:{x},backend:n,attrs:{begin:f,size:g}});b=Tt({inputs:{x:k},backend:n,attrs:{shape:y}}),n.disposeIntermediateTensorInfo(k)}else if(y.some(k=>k===0))b=n.makeTensorInfo(y,r.dtype,[]);else{let k=n.bufferSync(x),S=iI(y,k,m,f);b=n.makeTensorInfo(S.shape,S.dtype,S.values)}let w=Tt({inputs:{x:b},backend:n,attrs:{shape:y}});return n.disposeIntermediateTensorInfo(x),n.disposeIntermediateTensorInfo(b),w}var LK={kernelName:Oi,backendName:"cpu",kernelFunc:zK};function BK(e){let{inputs:t,backend:n,attrs:s}=e,{separator:r,nGramWidths:a,leftPad:o,rightPad:i,padWidth:l,preserveShortSequences:c}=s,{data:u,dataSplits:d}=t,p=n.data.get(u.dataId).values,h=n.data.get(d.dataId).values,[f,m]=lI(p,h,r,a,o,i,l,c);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(d.shape,"int32",m)]}var WK={kernelName:qc,backendName:"cpu",kernelFunc:BK};function VK(e){let{inputs:t,backend:n,attrs:s}=e,{skipEmpty:r}=s,{input:a,delimiter:o}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(a.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${a.shape}`);if(o.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${o.shape}`);let i=n.data.get(a.dataId).values,l=n.data.get(o.dataId).values[0],[c,u,d]=uI(i,l,r),p=u.length;return[n.makeTensorInfo([p,2],"int32",c),n.makeTensorInfo([p],"string",u),n.makeTensorInfo([2],"int32",new Int32Array(d))]}var UK={kernelName:Nh,backendName:"cpu",kernelFunc:VK};function GK(e){let{inputs:t,backend:n,attrs:s}=e,{numBuckets:r}=s,{input:a}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(r<=0)throw new Error("Number of buckets must be at least 1");let o=n.data.get(a.dataId).values,i=cI(o,r);return n.makeTensorInfo(a.shape,"int32",i)}var HK={kernelName:Eh,backendName:"cpu",kernelFunc:GK},jK=gt(Mi,e=>Math.tan(e)),qK={kernelName:Mi,backendName:"cpu",kernelFunc:jK},XK=gt(co,e=>Math.tanh(e)),KK={kernelName:co,backendName:"cpu",kernelFunc:XK};function ZK(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{reps:a}=s;Ne(r,"tile");let o=pI(n.bufferSync(r),a);return n.makeTensorInfo(o.shape,o.dtype,o.values)}var YK={kernelName:qr,backendName:"cpu",kernelFunc:ZK};function JK(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{k:a,sorted:o}=s;Ne(r,"topk");let i=n.data.get(r.dataId).values,[l,c]=fI(i,r.shape,r.dtype,a,o);return[n.makeTensorInfo(l.shape,l.dtype,l.values),n.makeTensorInfo(c.shape,c.dtype,c.values)]}var QK={kernelName:zi,backendName:"cpu",kernelFunc:JK};function eZ(e){let{inputs:t,attrs:n,backend:s}=e,{image:r,transforms:a}=t,{interpolation:o,fillMode:i,fillValue:l,outputShape:c}=n,[u,d,p,h]=r.shape,[f,m]=c!=null?c:[d,p],g=[u,f,m,h],A=v.computeStrides(r.shape),y=A[0],x=A[1],b=A[2],w=v.getTypedArrayFromDType(r.dtype,v.sizeFromShape(g));w.fill(l);let k=s.data.get(r.dataId).values,S=s.data.get(a.dataId).values;for(let $=0;$t-1)if(t<=1)n=0;else{let s=2*t;n-=s*Math.trunc(n/s),n>=t&&(n=s-n-1)}return v.clamp(0,n,t-1)}function sZ(e,t){let n=e;if(n<0)if(t<=1)n=0;else{let s=t-1;n+=t*(Math.trunc(-n/s)+1)}else if(n>t-1)if(t<=1)n=0;else{let s=t-1;n-=t*Math.trunc(n/s)}return v.clamp(0,n,t-1)}function rZ(e,t){return e}function aZ(e,t){return v.clamp(0,e,t-1)}function Vd(e,t,n,s,r,a,o,i,l,c,u){let d=o*s+i*r+l*a+c;return 0<=i&&in.disposeIntermediateTensorInfo(f)),h}var hZ={kernelName:Xc,backendName:"cpu",kernelFunc:pZ},fZ=[vH,hG,kH,SH,xG,TH,EH,$H,_H,FH,MH,LH,WH,GH,jH,KH,YH,QH,tj,xH,sj,aj,ij,uj,AG,vG,dj,fG,hj,mj,yj,bj,gj,Ij,Cj,wj,Nj,Rj,Dj,Pj,Oj,zj,Lj,Wj,Uj,Hj,jj,Xj,qj,$y,Yj,pH,Qj,wG,iq,kG,lq,SG,fq,mq,Aq,TG,bq,wq,Iq,Cq,Nq,EG,$G,mG,Rq,fj,Dq,Pq,Oq,hH,_G,FG,zq,MG,Bq,Uq,Hq,Xq,Zq,Jq,LG,tX,sX,aX,iX,uX,Qq,dX,hX,WG,mX,yX,wX,UG,HG,SX,NX,$X,qG,_X,FX,OX,$I,BX,mH,ZG,VX,gG,GX,gH,AH,yH,jX,XX,ZX,JX,eK,tK,sK,JG,aK,iK,dK,eH,hK,mK,AK,tH,xX,bK,wK,IK,CK,NK,RK,DK,PK,rH,FK,oH,MK,LK,WK,UK,HK,cH,Kj,qK,KK,YK,QK,XG,tZ,uZ,dZ,hZ,PX];for(let e of fZ)Kr(e);var FI={};ze(FI,{assertNotComplex:()=>Hu,bindCanvasToFramebuffer:()=>CZ,bindColorTextureToFramebuffer:()=>mm,bindTextureToProgramUniformSampler:()=>ZI,bindTextureUnit:()=>qI,bindVertexBufferToProgramAttribute:()=>Oy,callAndCheck:()=>Se,canBeRepresented:()=>OI,createFragmentShader:()=>LI,createFramebuffer:()=>jI,createProgram:()=>BI,createStaticIndexBuffer:()=>UI,createStaticVertexBuffer:()=>VI,createTexture:()=>GI,createVertexShader:()=>zI,getBatchDim:()=>fl,getExtensionOrThrow:()=>Hd,getFramebufferErrorMessage:()=>YI,getMaxTexturesInShader:()=>tS,getNumChannels:()=>IZ,getProgramUniformLocation:()=>KI,getProgramUniformLocationOrThrow:()=>XI,getRowsCols:()=>ml,getShapeAs3D:()=>gm,getTextureShapeFromLogicalShape:()=>QI,getWebGLDisjointQueryTimerVersion:()=>nS,getWebGLErrorMessage:()=>MI,getWebGLMaxTextureSize:()=>eS,hasExtension:()=>Ps,isCapableOfRenderingToFloatTexture:()=>sS,isDownloadFloatTextureEnabled:()=>rS,isReshapeFree:()=>qd,isWebGLFenceEnabled:()=>aS,isWebGLVersionEnabled:()=>zy,linkProgram:()=>WI,resetMaxTextureSize:()=>TZ,resetMaxTexturesInShader:()=>NZ,unbindColorTextureFromFramebuffer:()=>My,unbindTextureUnit:()=>SZ,validateFramebuffer:()=>jd,validateProgram:()=>fm,validateTextureSize:()=>HI});var hl={},Py={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function pm(e,t){hl[e]=t}function Mr(e){if(!(e in hl)){let n=gZ(e);if(n!==null)hl[e]=n;else return console.log("Could not get context for WebGL version",e),null}let t=hl[e];return t.isContextLost()?(delete hl[e],Mr(e)):(t.disable(t.DEPTH_TEST),t.disable(t.STENCIL_TEST),t.disable(t.BLEND),t.disable(t.DITHER),t.disable(t.POLYGON_OFFSET_FILL),t.disable(t.SAMPLE_COVERAGE),t.enable(t.SCISSOR_TEST),t.enable(t.CULL_FACE),t.cullFace(t.BACK),hl[e])}function mZ(e){if(typeof OffscreenCanvas!="undefined"&&e===2)return new OffscreenCanvas(300,150);if(typeof document!="undefined")return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}function gZ(e){if(e!==1&&e!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");let t=mZ(e);return t.addEventListener("webglcontextlost",n=>{n.preventDefault(),delete hl[e]},!1),e===1?t.getContext("webgl",Py)||t.getContext("experimental-webgl",Py):t.getContext("webgl2",Py)}var Ud;(function(e){e[e.DENSE=0]="DENSE",e[e.SHARED_BATCH=1]="SHARED_BATCH"})(Ud||(Ud={}));var _s;(function(e){e[e.RENDER=0]="RENDER",e[e.UPLOAD=1]="UPLOAD",e[e.PIXELS=2]="PIXELS",e[e.DOWNLOAD=3]="DOWNLOAD"})(_s||(_s={}));var Cn;(function(e){e[e.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",e[e.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",e[e.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",e[e.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",e[e.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"})(Cn||(Cn={}));function Gd(e,t){return[t,e]}function AZ(e,t){return e*t}function hm(e){let t=v.sizeFromShape(e),n=Math.ceil(t/4);return v.sizeToSquarishShape(n)}function Gu(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function yZ(e,t){let[n,s]=Gu(e,t);return n*s*4}function Fy(e,t){let n=e,s,r,a,o,i,l,c,u,d,p;return K().getNumber("WEBGL_VERSION")===2?(s=n.R32F,r=n.R16F,a=n.RGBA16F,o=n.RGBA32F,i=n.RED,c=4,u=1,d=n.HALF_FLOAT,p=n.FLOAT):(s=e.RGBA,r=e.RGBA,a=e.RGBA,o=n.RGBA,i=e.RGBA,c=4,u=4,d=t!=null?t.HALF_FLOAT_OES:null,p=e.FLOAT),l=e.RGBA,{internalFormatFloat:s,internalFormatHalfFloat:r,internalFormatPackedHalfFloat:a,internalFormatPackedFloat:o,textureFormatFloat:i,downloadTextureFormat:l,downloadUnpackNumChannels:c,defaultNumChannels:u,textureTypeHalfFloat:d,textureTypeFloat:p}}function Se(e,t){let n=t();return K().getBool("DEBUG")&&xZ(e),n}function xZ(e){let t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+MI(e,t))}var bZ=596e-10,vZ=65504;function OI(e){return!!(K().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||e===0||bZe.getExtension(t),'Extension "'+t+'" not supported on this browser.')}function zI(e,t){let n=oa(e,()=>e.createShader(e.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(Se(e,()=>e.shaderSource(n,t)),Se(e,()=>e.compileShader(n)),e.getShaderParameter(n,e.COMPILE_STATUS)===!1)throw console.log(e.getShaderInfoLog(n)),new Error("Failed to compile vertex shader.");return n}function LI(e,t){let n=oa(e,()=>e.createShader(e.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(Se(e,()=>e.shaderSource(n,t)),Se(e,()=>e.compileShader(n)),e.getShaderParameter(n,e.COMPILE_STATUS)===!1)throw kZ(t,e.getShaderInfoLog(n)),new Error("Failed to compile fragment shader.");return n}var wZ=/ERROR: [0-9]+:([0-9]+):/g;function kZ(e,t){let n=wZ.exec(t);if(n==null){console.log(`Couldn't parse line number in error: ${t}`),console.log(e);return}let s=+n[1],r=e.split(` `),a=r.length.toString().length+2,o=r.map((d,p)=>v.rightPad((p+1).toString(),a)+d),i=0;for(let d=0;d=2&&u>=2&&x,()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${m}) and (${g}).`);let w=(A>y?e.shape.slice(0,-2):t.shape.slice(0,-2)).concat([h,f]);v.assert(d===p,()=>`Error in matMul: inner shapes (${d}) and (${p}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${n} and transposeB=${s} must match.`);let k=n?[A,d,h]:[A,h,d],S=s?[y,f,p]:[y,p,f],E=ve({inputs:{x:e},backend:r,attrs:{shape:k}}),P=ve({inputs:{x:t},backend:r,attrs:{shape:S}}),F=[E,P],R=Math.max(A,y),_=n?E.shape[1]:E.shape[2],T=a!=null,M=o!=null,U=l==="leakyrelu",H=l!=null?Sm(l,!0):null,z=T||M||U||H!=null,X;if((h===1||f===1)&&_>ZS&&z===!1){let Y=E,se=P;n&&(Y=jn({inputs:{x:E},backend:r,attrs:{perm:[0,2,1]}}),F.push(Y)),s&&(se=jn({inputs:{x:P},backend:r,attrs:{perm:[0,2,1]}}),F.push(se));let ne=f!==1,J=f===1,te=Y;ne&&(te=ve({inputs:{x:Y},backend:r,attrs:{shape:[R,_,1]}}),F.push(te));let ue=f===1?2:1,ce=se;J&&(ce=ve({inputs:{x:se},backend:r,attrs:{shape:[R,1,_]}}),F.push(ce));let xe=Ky({inputs:{a:te,b:ce},backend:r});X=Tm({inputs:{x:xe},backend:r,attrs:{axis:ue,keepDims:!0}}),F.push(xe)}else{let Y=Bn(e.dtype,t.dtype),se=new HS(k,S,[R,h,f],n,s,T,H,M,U),ne=[E,P];if(a!=null&&ne.push(a),M&&ne.push(o),U){let J=r.makeTensorInfo([],"float32",v.createScalarValue(i,"float32"));ne.push(J),F.push(J)}X=r.runWebGLProgram(se,ne,Y)}let ee=ve({inputs:{x:X},backend:r,attrs:{shape:w}});F.push(X);for(let Y of F)r.disposeIntermediateTensorInfo(Y);return ee}function aQ(e){let{inputs:t,backend:n,attrs:s}=e,{a:r,b:a,bias:o,preluActivationWeights:i}=t,{transposeA:l,transposeB:c,activation:u,leakyreluAlpha:d}=s;return Nm({a:r,b:a,transposeA:l,transposeB:c,backend:n,bias:o,preluActivationWeights:i,leakyreluAlpha:d,activation:u})}var oQ={kernelName:fo,backendName:"webgl",kernelFunc:aQ},YS="return abs(x);";function iQ(e){let{inputs:t,backend:n}=e,{x:s}=t;if(n.shouldExecuteOnCPU([s])&&s.dtype!=="complex64"){let a=n.texData.get(s.dataId),o=ES(a.values);return n.makeTensorInfo(s.shape,s.dtype,o)}let r;return K().getBool("WEBGL_PACK_UNARY_OPERATIONS")?r=new Zu(s.shape,YS):r=new Fo(s.shape,YS),n.runWebGLProgram(r,[s],s.dtype)}var lQ={kernelName:ni,backendName:"webgl",kernelFunc:iQ},uQ=yr+` + `}};function Cm(e,t,n){let s=K().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new tQ(e.shape,t):new QJ(e.shape,t);return n.runWebGLProgram(s,[e],e.dtype)}function nQ(e,t,n,s){let r=t,a=e.shape.length,o=v.parseAxisParam(r,e.shape),i=o,l=N.getAxesPermutation(i,a),c=l!=null,u=e;c&&(u=Cm(e,l,s),i=N.getInnerMostAxes(i.length,a)),N.assertAxesAreInnerMostDims("sum",i,a);let[d,p]=N.computeOutAndReduceShapes(u.shape,i),h=d;n&&(h=N.expandShapeToKeepDim(d,o));let f=v.sizeFromShape(p),g=v.sizeFromShape(e.shape)/f,A=ve({inputs:{x:u},attrs:{shape:[g,f]},backend:s}),y=rd(e.dtype),x=yl(A,y,"sum",s),b=ve({inputs:{x},attrs:{shape:h},backend:s});return s.disposeIntermediateTensorInfo(A),s.disposeIntermediateTensorInfo(x),c&&s.disposeIntermediateTensorInfo(u),b}function Tm(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s;return nQ(r,a,o,n)}var sQ={kernelName:oo,backendName:"webgl",kernelFunc:Tm};function jn(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{perm:a}=s,o=n,i=r.shape.length,l=new Array(i);for(let u=0;u=2&&u>=2&&x,()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${m}) and (${g}).`);let w=(A>y?e.shape.slice(0,-2):t.shape.slice(0,-2)).concat([h,f]);v.assert(d===p,()=>`Error in matMul: inner shapes (${d}) and (${p}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${n} and transposeB=${s} must match.`);let k=n?[A,d,h]:[A,h,d],S=s?[y,f,p]:[y,p,f],E=ve({inputs:{x:e},backend:r,attrs:{shape:k}}),$=ve({inputs:{x:t},backend:r,attrs:{shape:S}}),F=[E,$],R=Math.max(A,y),P=n?E.shape[1]:E.shape[2],T=a!=null,M=o!=null,U=l==="leakyrelu",H=l!=null?Sm(l,!0):null,z=T||M||U||H!=null,X;if((h===1||f===1)&&P>ZS&&z===!1){let Y=E,ne=$;n&&(Y=jn({inputs:{x:E},backend:r,attrs:{perm:[0,2,1]}}),F.push(Y)),s&&(ne=jn({inputs:{x:$},backend:r,attrs:{perm:[0,2,1]}}),F.push(ne));let se=f!==1,J=f===1,te=Y;se&&(te=ve({inputs:{x:Y},backend:r,attrs:{shape:[R,P,1]}}),F.push(te));let ue=f===1?2:1,ce=ne;J&&(ce=ve({inputs:{x:ne},backend:r,attrs:{shape:[R,1,P]}}),F.push(ce));let be=Ky({inputs:{a:te,b:ce},backend:r});X=Tm({inputs:{x:be},backend:r,attrs:{axis:ue,keepDims:!0}}),F.push(be)}else{let Y=Bn(e.dtype,t.dtype),ne=new HS(k,S,[R,h,f],n,s,T,H,M,U),se=[E,$];if(a!=null&&se.push(a),M&&se.push(o),U){let J=r.makeTensorInfo([],"float32",v.createScalarValue(i,"float32"));se.push(J),F.push(J)}X=r.runWebGLProgram(ne,se,Y)}let ee=ve({inputs:{x:X},backend:r,attrs:{shape:w}});F.push(X);for(let Y of F)r.disposeIntermediateTensorInfo(Y);return ee}function aQ(e){let{inputs:t,backend:n,attrs:s}=e,{a:r,b:a,bias:o,preluActivationWeights:i}=t,{transposeA:l,transposeB:c,activation:u,leakyreluAlpha:d}=s;return Nm({a:r,b:a,transposeA:l,transposeB:c,backend:n,bias:o,preluActivationWeights:i,leakyreluAlpha:d,activation:u})}var oQ={kernelName:fo,backendName:"webgl",kernelFunc:aQ},YS="return abs(x);";function iQ(e){let{inputs:t,backend:n}=e,{x:s}=t;if(n.shouldExecuteOnCPU([s])&&s.dtype!=="complex64"){let a=n.texData.get(s.dataId),o=ES(a.values);return n.makeTensorInfo(s.shape,s.dtype,o)}let r;return K().getBool("WEBGL_PACK_UNARY_OPERATIONS")?r=new Zu(s.shape,YS):r=new Fo(s.shape,YS),n.runWebGLProgram(r,[s],s.dtype)}var lQ={kernelName:ni,backendName:"webgl",kernelFunc:iQ},uQ=yr+` if (abs(x) > 1.) { return NAN; } @@ -1798,7 +1798,7 @@ return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,GQ=ot({opSnippet:UQ}),HQ={kernelNam } setOutput(${x}); } - `}},Zy=class{constructor(e,t,n,s=!1,r=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let a=e.filterWidth,o=e.strideDepth,i=e.strideHeight,l=e.strideWidth,c=e.dilationDepth,u=e.dilationHeight,d=e.dilationWidth,p=e.effectiveFilterDepth,h=e.effectiveFilterHeight,f=e.effectiveFilterWidth,m=e.padInfo.front,g=e.padInfo.top,A=e.padInfo.left;this.outputShape=e.outShape;let y=t==="avg",x="0.0";if(y||(x="-1.0 / 1e-20"),n){let P=">=";this.userCode=` + `}},Zy=class{constructor(e,t,n,s=!1,r=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let a=e.filterWidth,o=e.strideDepth,i=e.strideHeight,l=e.strideWidth,c=e.dilationDepth,u=e.dilationHeight,d=e.dilationWidth,p=e.effectiveFilterDepth,h=e.effectiveFilterHeight,f=e.effectiveFilterWidth,m=e.padInfo.front,g=e.padInfo.top,A=e.padInfo.left;this.outputShape=e.outShape;let y=t==="avg",x="0.0";if(y||(x="-1.0 / 1e-20"),n){let $=">=";this.userCode=` const ivec3 strides = ivec3(${o}, ${i}, ${l}); const ivec3 pads = ivec3(${m}, ${g}, ${A}); @@ -1849,7 +1849,7 @@ return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,GQ=ot({opSnippet:UQ}),HQ={kernelNam // use the current value. float currMinMaxValue = mix( value, minMaxValue, minMaxValueFound); - if (value ${P} currMinMaxValue) { + if (value ${$} currMinMaxValue) { minMaxValue = value; minMaxValueFound = 1.0; minMaxPosition = ${s?r?`(((batch * ${e.inDepth} + xD) * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`((xD * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`wD * ${h} * ${f} + @@ -2471,7 +2471,7 @@ return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,GQ=ot({opSnippet:UQ}),HQ={kernelNam ${s.output} = result; } - `}};function i4({x:e,filter:t,convInfo:n,backend:s,bias:r=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let l=e.shape,c=s.texData.get(e.dataId),u=n.inChannels,d=l[0]*l[1]*l[2],p=n.outChannels,h=n.dataFormat==="channelsLast",f=!1,m=!1,g,A=[];if(!((d===1||p===1)&&u>ZS)&&c.isPacked&&h&&c.texture!=null&&l[2]%2!=0&&v.arraysEqual(c.shape.slice(-3),l.slice(-3))){let b=l[0]*l[1]*(l[2]+1),w={dataId:e.dataId,shape:[1,b,n.inChannels],dtype:e.dtype},k=c.shape;c.shape=c.shape.slice(),c.shape[c.shape.length-2]++,v.assert(qd(c.shape,w.shape),()=>`packed reshape ${c.shape} to ${w.shape} isn't free`);let S=ve({inputs:{x:t},backend:s,attrs:{shape:[1,n.inChannels,n.outChannels]}});A.push(S);let E=Nm({a:w,b:S,backend:s,transposeA:f,transposeB:m,bias:r,activation:i,preluActivationWeights:a,leakyreluAlpha:o}),P=s.texData.get(E.dataId);v.assert(P.isPacked,()=>"batchMatMul result is expected to be packed"),c.shape=k,P.shape=n.outShape,g=bs({inputs:{x:E},backend:s}),g.shape=n.outShape,A.push(E)}else{let b=h?l[0]*l[1]*l[2]:l[0]*l[2]*l[3],w=ve({inputs:{x:e},backend:s,attrs:{shape:[1,b,n.inChannels]}}),k=ve({inputs:{x:t},backend:s,attrs:{shape:[1,n.inChannels,n.outChannels]}}),S=Nm({a:w,b:k,transposeA:f,transposeB:m,backend:s,bias:r,activation:i,preluActivationWeights:a,leakyreluAlpha:o});g=ve({inputs:{x:S},backend:s,attrs:{shape:n.outShape}}),A.push(w),A.push(k),A.push(S)}for(let b of A)s.disposeIntermediateTensorInfo(b);return g}function l4({x:e,filter:t,convInfo:n,backend:s,bias:r=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let{filterWidth:l,filterHeight:c,inChannels:u,outWidth:d,outHeight:p,dataFormat:h}=n,f=h==="channelsLast",m=l*c*u,g=p*d,A=[m,g],y=!0,x=!1,b=[],w=ve({inputs:{x:e},backend:s,attrs:{shape:e.shape.slice(1)}}),k=ve({inputs:{x:t},backend:s,attrs:{shape:[1,m,v.sizeFromShape(t.shape)/m]}});b.push(w),b.push(k);let S=new Bee(A,n),E=[w.shape,[n.padInfo.top,n.padInfo.left],[n.strideHeight,n.strideWidth],[n.dilationHeight,n.dilationWidth],[n.inChannels],[n.filterWidth*n.inChannels],[n.outWidth]],P=s.runWebGLProgram(S,[w],"float32",E),F=ve({inputs:{x:P},backend:s,attrs:{shape:[1,A[0],A[1]]}});b.push(P),b.push(F);let R=r!=null,_=a!=null,T=i==="leakyrelu",M=i?Sm(i,!0):null,U=new HS(F.shape,k.shape,[1,g,n.outChannels],y,x,R,M,_,T),H=[F,k];if(r&&H.push(r),_&&H.push(a),T){let Y=s.makeTensorInfo([],"float32",v.createScalarValue(o,"float32"));H.push(Y),b.push(Y)}let z=s.runWebGLProgram(U,H,"float32"),X=f?[1,p,d,n.outChannels]:[1,n.outChannels,p,d],ee=ve({inputs:{x:z},backend:s,attrs:{shape:X}});b.push(z);for(let Y of b)s.disposeIntermediateTensorInfo(Y);return ee}function Wee(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:o,pad:i,dataFormat:l,dilations:c,dimRoundingMode:u}=s,d=N.convertConv2DDataFormat(l),p=N.computeConv2DInfo(r.shape,a.shape,o,c,i,u,!1,d),h;if(p.filterHeight===1&&p.filterWidth===1&&p.dilationHeight===1&&p.dilationWidth===1&&p.strideHeight===1&&p.strideWidth===1&&(p.padInfo.type==="SAME"||p.padInfo.type==="VALID"))h=i4({x:r,filter:a,convInfo:p,backend:n});else if(K().getBool("WEBGL_CONV_IM2COL")&&r.shape[0]===1)h=l4({x:r,filter:a,convInfo:p,backend:n});else{let m=new o4(p);h=n.runWebGLProgram(m,[r,a],"float32")}let f=ve({inputs:{x:h},backend:n,attrs:{shape:p.outShape}});return n.disposeIntermediateTensorInfo(h),f}var Vee={kernelName:Na,backendName:"webgl",kernelFunc:Wee},Uee=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,n=e.strideWidth,s=e.padInfo.top,r=e.padInfo.left,a=e.dataFormat==="channelsLast";this.userCode=` + `}};function i4({x:e,filter:t,convInfo:n,backend:s,bias:r=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let l=e.shape,c=s.texData.get(e.dataId),u=n.inChannels,d=l[0]*l[1]*l[2],p=n.outChannels,h=n.dataFormat==="channelsLast",f=!1,m=!1,g,A=[];if(!((d===1||p===1)&&u>ZS)&&c.isPacked&&h&&c.texture!=null&&l[2]%2!=0&&v.arraysEqual(c.shape.slice(-3),l.slice(-3))){let b=l[0]*l[1]*(l[2]+1),w={dataId:e.dataId,shape:[1,b,n.inChannels],dtype:e.dtype},k=c.shape;c.shape=c.shape.slice(),c.shape[c.shape.length-2]++,v.assert(qd(c.shape,w.shape),()=>`packed reshape ${c.shape} to ${w.shape} isn't free`);let S=ve({inputs:{x:t},backend:s,attrs:{shape:[1,n.inChannels,n.outChannels]}});A.push(S);let E=Nm({a:w,b:S,backend:s,transposeA:f,transposeB:m,bias:r,activation:i,preluActivationWeights:a,leakyreluAlpha:o}),$=s.texData.get(E.dataId);v.assert($.isPacked,()=>"batchMatMul result is expected to be packed"),c.shape=k,$.shape=n.outShape,g=bs({inputs:{x:E},backend:s}),g.shape=n.outShape,A.push(E)}else{let b=h?l[0]*l[1]*l[2]:l[0]*l[2]*l[3],w=ve({inputs:{x:e},backend:s,attrs:{shape:[1,b,n.inChannels]}}),k=ve({inputs:{x:t},backend:s,attrs:{shape:[1,n.inChannels,n.outChannels]}}),S=Nm({a:w,b:k,transposeA:f,transposeB:m,backend:s,bias:r,activation:i,preluActivationWeights:a,leakyreluAlpha:o});g=ve({inputs:{x:S},backend:s,attrs:{shape:n.outShape}}),A.push(w),A.push(k),A.push(S)}for(let b of A)s.disposeIntermediateTensorInfo(b);return g}function l4({x:e,filter:t,convInfo:n,backend:s,bias:r=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let{filterWidth:l,filterHeight:c,inChannels:u,outWidth:d,outHeight:p,dataFormat:h}=n,f=h==="channelsLast",m=l*c*u,g=p*d,A=[m,g],y=!0,x=!1,b=[],w=ve({inputs:{x:e},backend:s,attrs:{shape:e.shape.slice(1)}}),k=ve({inputs:{x:t},backend:s,attrs:{shape:[1,m,v.sizeFromShape(t.shape)/m]}});b.push(w),b.push(k);let S=new Bee(A,n),E=[w.shape,[n.padInfo.top,n.padInfo.left],[n.strideHeight,n.strideWidth],[n.dilationHeight,n.dilationWidth],[n.inChannels],[n.filterWidth*n.inChannels],[n.outWidth]],$=s.runWebGLProgram(S,[w],"float32",E),F=ve({inputs:{x:$},backend:s,attrs:{shape:[1,A[0],A[1]]}});b.push($),b.push(F);let R=r!=null,P=a!=null,T=i==="leakyrelu",M=i?Sm(i,!0):null,U=new HS(F.shape,k.shape,[1,g,n.outChannels],y,x,R,M,P,T),H=[F,k];if(r&&H.push(r),P&&H.push(a),T){let Y=s.makeTensorInfo([],"float32",v.createScalarValue(o,"float32"));H.push(Y),b.push(Y)}let z=s.runWebGLProgram(U,H,"float32"),X=f?[1,p,d,n.outChannels]:[1,n.outChannels,p,d],ee=ve({inputs:{x:z},backend:s,attrs:{shape:X}});b.push(z);for(let Y of b)s.disposeIntermediateTensorInfo(Y);return ee}function Wee(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:o,pad:i,dataFormat:l,dilations:c,dimRoundingMode:u}=s,d=N.convertConv2DDataFormat(l),p=N.computeConv2DInfo(r.shape,a.shape,o,c,i,u,!1,d),h;if(p.filterHeight===1&&p.filterWidth===1&&p.dilationHeight===1&&p.dilationWidth===1&&p.strideHeight===1&&p.strideWidth===1&&(p.padInfo.type==="SAME"||p.padInfo.type==="VALID"))h=i4({x:r,filter:a,convInfo:p,backend:n});else if(K().getBool("WEBGL_CONV_IM2COL")&&r.shape[0]===1)h=l4({x:r,filter:a,convInfo:p,backend:n});else{let m=new o4(p);h=n.runWebGLProgram(m,[r,a],"float32")}let f=ve({inputs:{x:h},backend:n,attrs:{shape:p.outShape}});return n.disposeIntermediateTensorInfo(h),f}var Vee={kernelName:Na,backendName:"webgl",kernelFunc:Wee},Uee=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,n=e.strideWidth,s=e.padInfo.top,r=e.padInfo.left,a=e.dataFormat==="channelsLast";this.userCode=` void main() { ivec4 coords = getOutputCoords(); int wR = coords.x; @@ -3295,7 +3295,7 @@ return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,GQ=ot({opSnippet:UQ}),HQ={kernelNam ${t.output} = result; } - `}},fne={kernelName:Kc,backendName:"webgl",kernelFunc:mne},ec;function mne(e){let{inputs:t,backend:n,attrs:s}=e,{pixels:r}=t,{numChannels:a}=s,o=typeof HTMLVideoElement!="undefined"&&r instanceof HTMLVideoElement,i=typeof HTMLImageElement!="undefined"&&r instanceof HTMLImageElement,[l,c]=o?[r.videoWidth,r.videoHeight]:[r.width,r.height],u=[c,l],d=[c,l,a];(i||o)&&(ec==null&&(ec=document.createElement("canvas").getContext("2d")),ec.canvas.width=l,ec.canvas.height=c,ec.drawImage(r,0,0,l,c),r=ec.canvas);let p=n.makeTensorInfo(u,"int32");n.texData.get(p.dataId).usage=_s.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(p.dataId),r);let h=K().getBool("WEBGL_PACK")?new hne(d):new pne(d),f=n.runWebGLProgram(h,[p],"int32");return n.disposeData(p.dataId),f}function gne(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:c,dataFormat:u,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=s,m=N.convertConv2DDataFormat(u),g=N.computeConv2DInfo(r.shape,a.shape,l,d,c,p,!1,m),A,y=[];if(g.filterHeight===1&&g.filterWidth===1&&g.dilationHeight===1&&g.dilationWidth===1&&g.strideHeight===1&&g.strideWidth===1&&(g.padInfo.type==="SAME"||g.padInfo.type==="VALID"))A=i4({x:r,filter:a,convInfo:g,backend:n,bias:o,activation:h,preluActivationWeights:i,leakyreluAlpha:f});else if(K().getBool("WEBGL_CONV_IM2COL")&&r.shape[0]===1)A=l4({x:r,filter:a,convInfo:g,backend:n,bias:o,activation:h,preluActivationWeights:i,leakyreluAlpha:f});else{let b=o!=null,w=i!=null,k=h==="leakyrelu",S=h?Sm(h,!1):null,E=new o4(g,b,S,w,k),P=[r,a];if(o&&P.push(o),i&&P.push(i),k){let F=n.makeTensorInfo([],"float32",v.createScalarValue(f,"float32"));P.push(F),y.push(F)}A=n.runWebGLProgram(E,P,"float32")}let x=ve({inputs:{x:A},backend:n,attrs:{shape:g.outShape}});return y.push(A),y.forEach(b=>n.disposeIntermediateTensorInfo(b)),x}var Ane={kernelName:mo,backendName:"webgl",kernelFunc:gne};function yne(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:c,dilations:u,dimRoundingMode:d,activation:p,leakyreluAlpha:h}=s,f=[],m=u;m==null&&(m=[1,1]),v.assert(N.eitherStridesOrDilationsAreOne(l,m),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${m}'`);let g=N.computeConv2DInfo(r.shape,a.shape,l,m,c,d,!0),A=K().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels==1,y=p?Sm(p,A):null,x=[r,a],b=o!=null,w=i!=null,k=p==="leakyrelu";if(b&&x.push(o),w&&x.push(i),k){let F=n.makeTensorInfo([],"float32",v.createScalarValue(h,"float32"));x.push(F),f.push(F)}let S;A?S=new h4(g,b,y,w,k):S=new p4(g,b,y,w,k);let E=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],P=n.runWebGLProgram(S,x,"float32",E);return f.forEach(F=>n.disposeIntermediateTensorInfo(F)),P}var xne={kernelName:go,backendName:"webgl",kernelFunc:yne},bne=class{constructor(e,t,n){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=n;let s=vt(t.length),r=vt(n.length),a=this.sliceDim>1?"strides[j]":"strides";this.userCode=` + `}},fne={kernelName:Kc,backendName:"webgl",kernelFunc:mne},ec;function mne(e){let{inputs:t,backend:n,attrs:s}=e,{pixels:r}=t,{numChannels:a}=s,o=typeof HTMLVideoElement!="undefined"&&r instanceof HTMLVideoElement,i=typeof HTMLImageElement!="undefined"&&r instanceof HTMLImageElement,[l,c]=o?[r.videoWidth,r.videoHeight]:[r.width,r.height],u=[c,l],d=[c,l,a];(i||o)&&(ec==null&&(ec=document.createElement("canvas").getContext("2d")),ec.canvas.width=l,ec.canvas.height=c,ec.drawImage(r,0,0,l,c),r=ec.canvas);let p=n.makeTensorInfo(u,"int32");n.texData.get(p.dataId).usage=_s.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(p.dataId),r);let h=K().getBool("WEBGL_PACK")?new hne(d):new pne(d),f=n.runWebGLProgram(h,[p],"int32");return n.disposeData(p.dataId),f}function gne(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:c,dataFormat:u,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=s,m=N.convertConv2DDataFormat(u),g=N.computeConv2DInfo(r.shape,a.shape,l,d,c,p,!1,m),A,y=[];if(g.filterHeight===1&&g.filterWidth===1&&g.dilationHeight===1&&g.dilationWidth===1&&g.strideHeight===1&&g.strideWidth===1&&(g.padInfo.type==="SAME"||g.padInfo.type==="VALID"))A=i4({x:r,filter:a,convInfo:g,backend:n,bias:o,activation:h,preluActivationWeights:i,leakyreluAlpha:f});else if(K().getBool("WEBGL_CONV_IM2COL")&&r.shape[0]===1)A=l4({x:r,filter:a,convInfo:g,backend:n,bias:o,activation:h,preluActivationWeights:i,leakyreluAlpha:f});else{let b=o!=null,w=i!=null,k=h==="leakyrelu",S=h?Sm(h,!1):null,E=new o4(g,b,S,w,k),$=[r,a];if(o&&$.push(o),i&&$.push(i),k){let F=n.makeTensorInfo([],"float32",v.createScalarValue(f,"float32"));$.push(F),y.push(F)}A=n.runWebGLProgram(E,$,"float32")}let x=ve({inputs:{x:A},backend:n,attrs:{shape:g.outShape}});return y.push(A),y.forEach(b=>n.disposeIntermediateTensorInfo(b)),x}var Ane={kernelName:mo,backendName:"webgl",kernelFunc:gne};function yne(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:c,dilations:u,dimRoundingMode:d,activation:p,leakyreluAlpha:h}=s,f=[],m=u;m==null&&(m=[1,1]),v.assert(N.eitherStridesOrDilationsAreOne(l,m),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${m}'`);let g=N.computeConv2DInfo(r.shape,a.shape,l,m,c,d,!0),A=K().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels==1,y=p?Sm(p,A):null,x=[r,a],b=o!=null,w=i!=null,k=p==="leakyrelu";if(b&&x.push(o),w&&x.push(i),k){let F=n.makeTensorInfo([],"float32",v.createScalarValue(h,"float32"));x.push(F),f.push(F)}let S;A?S=new h4(g,b,y,w,k):S=new p4(g,b,y,w,k);let E=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],$=n.runWebGLProgram(S,x,"float32",E);return f.forEach(F=>n.disposeIntermediateTensorInfo(F)),$}var xne={kernelName:go,backendName:"webgl",kernelFunc:yne},bne=class{constructor(e,t,n){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=n;let s=vt(t.length),r=vt(n.length),a=this.sliceDim>1?"strides[j]":"strides";this.userCode=` ${s} strides = ${s}(${this.strides}); void main() { ${r} coords = getOutputCoords(); @@ -4314,7 +4314,7 @@ return a / b;`,lre=` ${a} coords = getOutputCoords(); setOutput(getX(${o})); } - `}};function Aoe(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,end:o,strides:i,beginMask:l,endMask:c,ellipsisMask:u,newAxisMask:d,shrinkAxisMask:p}=s,{nonStrided:h,$begin:f,$strides:m,size:g,newShape:A,outShape:y}=An.sliceInfo(r.shape,a,o,i,l,c,u,d,p),x=ve({inputs:{x:r},backend:n,attrs:{shape:A}}),b;if(h){let k=Ju({inputs:{x},backend:n,attrs:{begin:f,size:g}});b=ve({inputs:{x:k},backend:n,attrs:{shape:y}}),n.disposeIntermediateTensorInfo(k)}else if(y.some(k=>k===0))b=n.makeTensorInfo(y,r.dtype,[]);else if(n.shouldExecuteOnCPU([x])){let E=n.texData.get(x.dataId).values,P=Le(x.shape,x.dtype,E),F=eJ(y,P,m,f);b=n.makeTensorInfo(y,x.dtype,F.values)}else{let S=new goe(f,m,y);b=n.runWebGLProgram(S,[x],x.dtype)}let w=ve({inputs:{x:b},backend:n,attrs:{shape:y}});return n.disposeIntermediateTensorInfo(x),n.disposeIntermediateTensorInfo(b),w}var yoe={kernelName:Oi,backendName:"webgl",kernelFunc:Aoe};function xoe(e){let{inputs:t,backend:n,attrs:s}=e,{separator:r,nGramWidths:a,leftPad:o,rightPad:i,padWidth:l,preserveShortSequences:c}=s,{data:u,dataSplits:d}=t,p=n.readSync(u.dataId),h=n.readSync(d.dataId),[f,m]=tJ(p,h,r,a,o,i,l,c);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(d.shape,"int32",m)]}var boe={kernelName:qc,backendName:"webgl",kernelFunc:xoe};function voe(e){let{inputs:t,backend:n,attrs:s}=e,{skipEmpty:r}=s,{input:a,delimiter:o}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(a.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${a.shape}`);if(o.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${o.shape}`);let i=n.readSync(a.dataId),l=n.readSync(o.dataId)[0],[c,u,d]=nJ(i,l,r),p=u.length;return[n.makeTensorInfo([p,2],"int32",c),n.makeTensorInfo([p],"string",u),n.makeTensorInfo([2],"int32",new Int32Array(d))]}var woe={kernelName:Nh,backendName:"webgl",kernelFunc:voe};function koe(e){let{inputs:t,backend:n,attrs:s}=e,{numBuckets:r}=s,{input:a}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(r<=0)throw new Error("Number of buckets must be at least 1");let o=n.readSync(a.dataId),i=sJ(o,r);return n.makeTensorInfo(a.shape,"int32",i)}var Ioe={kernelName:Eh,backendName:"webgl",kernelFunc:koe},Soe="return tan(x);",Coe=ot({opSnippet:Soe}),Toe={kernelName:Mi,backendName:"webgl",kernelFunc:Coe},Noe=` + `}};function Aoe(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,end:o,strides:i,beginMask:l,endMask:c,ellipsisMask:u,newAxisMask:d,shrinkAxisMask:p}=s,{nonStrided:h,$begin:f,$strides:m,size:g,newShape:A,outShape:y}=An.sliceInfo(r.shape,a,o,i,l,c,u,d,p),x=ve({inputs:{x:r},backend:n,attrs:{shape:A}}),b;if(h){let k=Ju({inputs:{x},backend:n,attrs:{begin:f,size:g}});b=ve({inputs:{x:k},backend:n,attrs:{shape:y}}),n.disposeIntermediateTensorInfo(k)}else if(y.some(k=>k===0))b=n.makeTensorInfo(y,r.dtype,[]);else if(n.shouldExecuteOnCPU([x])){let E=n.texData.get(x.dataId).values,$=Le(x.shape,x.dtype,E),F=eJ(y,$,m,f);b=n.makeTensorInfo(y,x.dtype,F.values)}else{let S=new goe(f,m,y);b=n.runWebGLProgram(S,[x],x.dtype)}let w=ve({inputs:{x:b},backend:n,attrs:{shape:y}});return n.disposeIntermediateTensorInfo(x),n.disposeIntermediateTensorInfo(b),w}var yoe={kernelName:Oi,backendName:"webgl",kernelFunc:Aoe};function xoe(e){let{inputs:t,backend:n,attrs:s}=e,{separator:r,nGramWidths:a,leftPad:o,rightPad:i,padWidth:l,preserveShortSequences:c}=s,{data:u,dataSplits:d}=t,p=n.readSync(u.dataId),h=n.readSync(d.dataId),[f,m]=tJ(p,h,r,a,o,i,l,c);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(d.shape,"int32",m)]}var boe={kernelName:qc,backendName:"webgl",kernelFunc:xoe};function voe(e){let{inputs:t,backend:n,attrs:s}=e,{skipEmpty:r}=s,{input:a,delimiter:o}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(a.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${a.shape}`);if(o.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${o.shape}`);let i=n.readSync(a.dataId),l=n.readSync(o.dataId)[0],[c,u,d]=nJ(i,l,r),p=u.length;return[n.makeTensorInfo([p,2],"int32",c),n.makeTensorInfo([p],"string",u),n.makeTensorInfo([2],"int32",new Int32Array(d))]}var woe={kernelName:Nh,backendName:"webgl",kernelFunc:voe};function koe(e){let{inputs:t,backend:n,attrs:s}=e,{numBuckets:r}=s,{input:a}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(r<=0)throw new Error("Number of buckets must be at least 1");let o=n.readSync(a.dataId),i=sJ(o,r);return n.makeTensorInfo(a.shape,"int32",i)}var Ioe={kernelName:Eh,backendName:"webgl",kernelFunc:koe},Soe="return tan(x);",Coe=ot({opSnippet:Soe}),Toe={kernelName:Mi,backendName:"webgl",kernelFunc:Coe},Noe=` float e2x = exp(-2.0 * abs(x)); return sign(x) * (1.0 - e2x) / (1.0 + e2x); `,Eoe=ot({opSnippet:Noe}),Roe={kernelName:co,backendName:"webgl",kernelFunc:Eoe},$oe=class{constructor(e,t){this.variableNames=["A"];let n=new Array(e.length);for(let a=0;a= x1 ? float(i0) : float(i1)); } - `}};function xl(e,t){t!==null&&e.disposeIntermediateTensorInfo(t)}function F4(e){let t=1;for(;tl){let F=n.readSync(r.dataId),[R,_]=oJ(F,c,r.dtype,a,o);return[n.makeTensorInfo(R.shape,R.dtype,R.values),n.makeTensorInfo(_.shape,_.dtype,_.values)]}if(a===0)return c[c.length-1]=0,[n.makeTensorInfo(c,r.dtype,[]),n.makeTensorInfo(c,"int32",[])];if(u===1)return[r,Qd({attrs:{shape:c,dtype:"int32",value:0},backend:n})];let d=n.texData.get(r.dataId),p=d!==null&&d.isPacked,h=p?n.unpackTensor(r):r,m=v.sizeFromShape(c)/u,g=ve({inputs:{x:h},attrs:{shape:[m,u]},backend:n});p&&xl(n,h);let A=F4(a),y=F4(u),x=null,b=()=>x===null?[g,g]:[g,x],w=(F,R,_)=>{let T=b(),M=new Poe(_),H=[[u],[x===null?1:0],[Number.NEGATIVE_INFINITY],[F],[R]],z=x;x=n.runWebGLProgram(M,T,"int32",H),xl(n,z)};for(let F=1;F=1;_/=2)w(R,_,[m,y])}for(let F=y;F>A;F/=2){let R=b(),_=new Foe([m,F/2]),M=[[u],[x===null?1:0],[A]],U=x;x=n.runWebGLProgram(_,R,"int32",M),xl(n,U);let H=A/2,z=H*2;for(let X=H;X>=1;X/=2)w(z,X,x.shape)}let k=x;x=Ju({inputs:{x},backend:n,attrs:{begin:0,size:[m,a]}}),xl(n,k);let S=b4({inputs:{x:g,indices:x},backend:n,attrs:{axis:1,batchDims:1}});xl(n,g);let E=c.slice(0,-1);E.push(a),k=x,x=ve({inputs:{x},attrs:{shape:E},backend:n}),xl(n,k);let P=S;return S=ve({inputs:{x:S},attrs:{shape:E},backend:n}),xl(n,P),[S,x]}var Moe={kernelName:zi,backendName:"webgl",kernelFunc:Ooe},zoe=class{constructor(e,t,n,s,r,a){this.variableNames=["Image","Transforms"],this.outputShape=a;let o=n==="nearest"?1:2,i;switch(s){case"constant":i=1;break;case"reflect":i=2;break;case"wrap":i=3;break;case"nearest":i=4;break;default:i=1;break}this.userCode=` + `}};function xl(e,t){t!==null&&e.disposeIntermediateTensorInfo(t)}function F4(e){let t=1;for(;tl){let F=n.readSync(r.dataId),[R,P]=oJ(F,c,r.dtype,a,o);return[n.makeTensorInfo(R.shape,R.dtype,R.values),n.makeTensorInfo(P.shape,P.dtype,P.values)]}if(a===0)return c[c.length-1]=0,[n.makeTensorInfo(c,r.dtype,[]),n.makeTensorInfo(c,"int32",[])];if(u===1)return[r,Qd({attrs:{shape:c,dtype:"int32",value:0},backend:n})];let d=n.texData.get(r.dataId),p=d!==null&&d.isPacked,h=p?n.unpackTensor(r):r,m=v.sizeFromShape(c)/u,g=ve({inputs:{x:h},attrs:{shape:[m,u]},backend:n});p&&xl(n,h);let A=F4(a),y=F4(u),x=null,b=()=>x===null?[g,g]:[g,x],w=(F,R,P)=>{let T=b(),M=new Poe(P),H=[[u],[x===null?1:0],[Number.NEGATIVE_INFINITY],[F],[R]],z=x;x=n.runWebGLProgram(M,T,"int32",H),xl(n,z)};for(let F=1;F=1;P/=2)w(R,P,[m,y])}for(let F=y;F>A;F/=2){let R=b(),P=new Foe([m,F/2]),M=[[u],[x===null?1:0],[A]],U=x;x=n.runWebGLProgram(P,R,"int32",M),xl(n,U);let H=A/2,z=H*2;for(let X=H;X>=1;X/=2)w(z,X,x.shape)}let k=x;x=Ju({inputs:{x},backend:n,attrs:{begin:0,size:[m,a]}}),xl(n,k);let S=b4({inputs:{x:g,indices:x},backend:n,attrs:{axis:1,batchDims:1}});xl(n,g);let E=c.slice(0,-1);E.push(a),k=x,x=ve({inputs:{x},attrs:{shape:E},backend:n}),xl(n,k);let $=S;return S=ve({inputs:{x:S},attrs:{shape:E},backend:n}),xl(n,$),[S,x]}var Moe={kernelName:zi,backendName:"webgl",kernelFunc:Ooe},zoe=class{constructor(e,t,n,s,r,a){this.variableNames=["Image","Transforms"],this.outputShape=a;let o=n==="nearest"?1:2,i;switch(s){case"constant":i=1;break;case"reflect":i=2;break;case"wrap":i=3;break;case"nearest":i=4;break;default:i=1;break}this.userCode=` float mapCoord(float outCoord, float len) { float inCoord = outCoord; if(${i} == 2) { @@ -4614,7 +4614,7 @@ return a / b;`,lre=` } setOutput(${l}); } - `}};function joe(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,segmentIds:a}=t,{numSegments:o}=s,i=r.shape.length,l=[],c=0,u=N.getAxesPermutation([c],i),d=r;u!=null&&(d=jn({inputs:{x:r},backend:n,attrs:{perm:u}}),l.push(d),c=N.getInnerMostAxes(1,i)[0]);let p=N.segment_util.computeOutShape(d.shape,c,o),h=v.sizeFromShape([d.shape[c]]),f=ve({inputs:{x:d},backend:n,attrs:{shape:[-1,h]}});l.push(f);let m=rd(r.dtype),g=(b,w,k,S,E)=>{let P=b.shape[0],F=b.shape[1],R=N.segment_util.segOpComputeOptimalWindowSize(F,E),_={windowSize:R,inSize:F,batchSize:P,numSegments:E},T=new Hoe(_,w),M=n.compileAndRun(T,[b,k],S);if(l.push(M),M.shape[1]===E)return M;let U=E4({backend:n,attrs:{start:0,stop:E,step:1,dtype:"float32"}}),H=P4({inputs:{x:U},backend:n,attrs:{reps:[F/R]}});return l.push(U),l.push(H),g(M,w,H,S,E)},A=g(f,"unsortedSegmentSum",a,m,o),y=ve({inputs:{x:A},backend:n,attrs:{shape:p}}),x=y;if(u!=null){l.push(y);let b=N.getUndoAxesPermutation(u);x=jn({inputs:{x},backend:n,attrs:{perm:b}})}return l.forEach(b=>n.disposeIntermediateTensorInfo(b)),x}var qoe={kernelName:Xc,backendName:"webgl",kernelFunc:joe},Xoe=[wse,Sse,oQ,lQ,dQ,fQ,gQ,xQ,vQ,kQ,TQ,EQ,DQ,FQ,VQ,zQ,HQ,KQ,qQ,QQ,tee,see,iee,fee,gee,yee,Iee,Cee,Ree,_ee,WJ,zee,Xee,Zee,Vee,ete,nte,Jee,ate,lte,dte,hte,mte,yte,Ite,Cte,bte,Ete,Dte,Pte,zte,Vte,jte,Kte,Zte,Yte,Qte,tne,sne,ane,ine,dne,fne,Ane,xne,wne,Sne,Ene,_ne,BJ,Fne,Oee,zne,Wne,Gne,UJ,Xne,Jne,ese,ise,rse,dse,fse,yse,Tse,Fse,_se,Lse,Wse,Use,$se,Hse,qse,Yse,tre,are,hre,XJ,mre,yre,vre,Ire,bee,Tre,Ere,$re,Pre,zre,HJ,Bre,Wre,vee,ure,Gre,Jre,Xre,ZJ,nae,aae,uae,pae,gae,yae,vae,Iae,Cae,Eae,Dae,Pae,Mae,Bae,Uae,pee,dre,jae,Xae,Zae,Jae,eoe,noe,roe,ooe,loe,doe,hoe,moe,yoe,boe,woe,Ioe,cre,sQ,Toe,Roe,_oe,Moe,Boe,rQ,Voe,Goe,qoe,Nre];for(let e of Xoe)Kr(e);var zr=K();zr.registerFlag("WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE",()=>15);zr.registerFlag("WEBGPU_CPU_FORWARD",()=>!0);zr.registerFlag("WEBGPU_MATMUL_WORK_PER_THREAD",()=>4);zr.registerFlag("WEBGPU_USE_NAIVE_CONV2D",()=>!1);zr.registerFlag("WEBGPU_USE_NAIVE_CONV2D_TRANSPOSE",()=>!1);zr.registerFlag("WEBGPU_CONV_SEPARATE_IM2COL_SHADER",()=>!1);zr.registerFlag("WEBGPU_USE_LOW_POWER_GPU",()=>!1);zr.registerFlag("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD",()=>1e3);zr.registerFlag("WEBGPU_USE_PROFILE_TOOL",()=>!1);zr.registerFlag("WEBGPU_USE_IMPORT",()=>!1);function Koe(e,t){if(Math.max(...e)>3)throw new Error("Cannot symbolically compute strides for rank > 4 tensor.");let n=e.length,s=e.map(a=>`${t}[${a}]`),r=new Array(n-1);r[n-2]=s[n-1];for(let a=n-3;a>=0;--a)r[a]=`(${r[a+1]} * ${s[a+1]})`;return r}function Qt(e){if(e<=1)return"i32";if(e===2)return"vec2";if(e===3)return"vec3";if(e===4)return"vec4";throw Error(`GPU for rank ${e} is not yet supported`)}function _m(e,t){return e==="float32"?t?"vec4":"f32":e==="int32"||e==="bool"?t?"vec4":"i32":e}function We(){return` + `}};function joe(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,segmentIds:a}=t,{numSegments:o}=s,i=r.shape.length,l=[],c=0,u=N.getAxesPermutation([c],i),d=r;u!=null&&(d=jn({inputs:{x:r},backend:n,attrs:{perm:u}}),l.push(d),c=N.getInnerMostAxes(1,i)[0]);let p=N.segment_util.computeOutShape(d.shape,c,o),h=v.sizeFromShape([d.shape[c]]),f=ve({inputs:{x:d},backend:n,attrs:{shape:[-1,h]}});l.push(f);let m=rd(r.dtype),g=(b,w,k,S,E)=>{let $=b.shape[0],F=b.shape[1],R=N.segment_util.segOpComputeOptimalWindowSize(F,E),P={windowSize:R,inSize:F,batchSize:$,numSegments:E},T=new Hoe(P,w),M=n.compileAndRun(T,[b,k],S);if(l.push(M),M.shape[1]===E)return M;let U=E4({backend:n,attrs:{start:0,stop:E,step:1,dtype:"float32"}}),H=P4({inputs:{x:U},backend:n,attrs:{reps:[F/R]}});return l.push(U),l.push(H),g(M,w,H,S,E)},A=g(f,"unsortedSegmentSum",a,m,o),y=ve({inputs:{x:A},backend:n,attrs:{shape:p}}),x=y;if(u!=null){l.push(y);let b=N.getUndoAxesPermutation(u);x=jn({inputs:{x},backend:n,attrs:{perm:b}})}return l.forEach(b=>n.disposeIntermediateTensorInfo(b)),x}var qoe={kernelName:Xc,backendName:"webgl",kernelFunc:joe},Xoe=[wse,Sse,oQ,lQ,dQ,fQ,gQ,xQ,vQ,kQ,TQ,EQ,DQ,FQ,VQ,zQ,HQ,KQ,qQ,QQ,tee,see,iee,fee,gee,yee,Iee,Cee,Ree,_ee,WJ,zee,Xee,Zee,Vee,ete,nte,Jee,ate,lte,dte,hte,mte,yte,Ite,Cte,bte,Ete,Dte,Pte,zte,Vte,jte,Kte,Zte,Yte,Qte,tne,sne,ane,ine,dne,fne,Ane,xne,wne,Sne,Ene,_ne,BJ,Fne,Oee,zne,Wne,Gne,UJ,Xne,Jne,ese,ise,rse,dse,fse,yse,Tse,Fse,_se,Lse,Wse,Use,$se,Hse,qse,Yse,tre,are,hre,XJ,mre,yre,vre,Ire,bee,Tre,Ere,$re,Pre,zre,HJ,Bre,Wre,vee,ure,Gre,Jre,Xre,ZJ,nae,aae,uae,pae,gae,yae,vae,Iae,Cae,Eae,Dae,Pae,Mae,Bae,Uae,pee,dre,jae,Xae,Zae,Jae,eoe,noe,roe,ooe,loe,doe,hoe,moe,yoe,boe,woe,Ioe,cre,sQ,Toe,Roe,_oe,Moe,Boe,rQ,Voe,Goe,qoe,Nre];for(let e of Xoe)Kr(e);var zr=K();zr.registerFlag("WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE",()=>15);zr.registerFlag("WEBGPU_CPU_FORWARD",()=>!0);zr.registerFlag("WEBGPU_MATMUL_WORK_PER_THREAD",()=>4);zr.registerFlag("WEBGPU_USE_NAIVE_CONV2D",()=>!1);zr.registerFlag("WEBGPU_USE_NAIVE_CONV2D_TRANSPOSE",()=>!1);zr.registerFlag("WEBGPU_CONV_SEPARATE_IM2COL_SHADER",()=>!1);zr.registerFlag("WEBGPU_USE_LOW_POWER_GPU",()=>!1);zr.registerFlag("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD",()=>1e3);zr.registerFlag("WEBGPU_USE_PROFILE_TOOL",()=>!1);zr.registerFlag("WEBGPU_USE_IMPORT",()=>!1);function Koe(e,t){if(Math.max(...e)>3)throw new Error("Cannot symbolically compute strides for rank > 4 tensor.");let n=e.length,s=e.map(a=>`${t}[${a}]`),r=new Array(n-1);r[n-2]=s[n-1];for(let a=n-3;a>=0;--a)r[a]=`(${r[a+1]} * ${s[a+1]})`;return r}function Qt(e){if(e<=1)return"i32";if(e===2)return"vec2";if(e===3)return"vec3";if(e===4)return"vec4";throw Error(`GPU for rank ${e} is not yet supported`)}function _m(e,t){return e==="float32"?t?"vec4":"f32":e==="int32"||e==="bool"?t?"vec4":"i32":e}function We(){return` let index = getGlobalIndex(globalId, localId); `}function Fe(){return` [[stage(compute), workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)]] @@ -5446,7 +5446,7 @@ return a / b;`,lre=` } } ${ole(this.workGroupSize)} - `}};function je(e){let{inputs:t,attrs:n}=e,{x:s}=t,{shape:r}=n,a=v.sizeFromShape(s.shape),o=v.inferFromImplicitShape(r,a),i=v.sizeFromShape(o);return v.assert(a===i,()=>`The new shape (${o}) has ${i} elements and the old shape (${s.shape}) has ${a} elements. The new shape and old shape must have the same number of elements.`),e.backend.incRef(s.dataId),{dataId:s.dataId,shape:o,dtype:s.dtype}}var lle={kernelName:Ti,backendName:"webgpu",kernelFunc:je};function ox({a:e,b:t,transposeA:n,transposeB:s,backend:r,bias:a=null,preluActivationWeights:o=null,leakyreluAlpha:i=0,activation:l=null}){let c=e.shape.length,u=t.shape.length,d=n?e.shape[c-2]:e.shape[c-1],p=s?t.shape[u-1]:t.shape[u-2],h=n?e.shape[c-1]:e.shape[c-2],f=s?t.shape[u-2]:t.shape[u-1],m=e.shape.slice(0,-2),g=t.shape.slice(0,-2),A=v.sizeFromShape(m),y=v.sizeFromShape(g),x=A===y||A===1||y===1;v.assert(c>=2&&u>=2&&x,()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${m}) and (${g}).`);let w=(A>y?e.shape.slice(0,-2):t.shape.slice(0,-2)).concat([h,f]);v.assert(d===p,()=>`Error in matMul: inner shapes (${d}) and (${p}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${n} and transposeB=${s} must match.`);let k=n?[A,d,h]:[A,h,d],S=s?[y,f,p]:[y,p,f],E=je({inputs:{x:e},backend:r,attrs:{shape:k}}),P=je({inputs:{x:t},backend:r,attrs:{shape:S}}),F=[E,P],R=Math.max(A,y),_=d%4==0&&f%4==0&&!n&&!s&&f>=32,T;!n&&!s&&(h<=16&&(f<=512||p>=2*f)||f<=16&&(h<=512||d>=2*h))?T=new ile(k,S,[R,h,f],a,l,o):_?T=new rle(k,[R,h,f],K().get("WEBGPU_MATMUL_WORK_PER_THREAD"),a,l,o):T=new G4(k,[R,h,f],K().get("WEBGPU_MATMUL_WORK_PER_THREAD"),n,s,a,l,o);let M=[E,P];a&&M.push(a),o&&M.push(o);let U=[{type:"int32",data:[h]},{type:"int32",data:[f]},{type:"int32",data:[d]}],H=r.runWebGPUProgram(T,M,e.dtype,U),z=je({inputs:{x:H},backend:r,attrs:{shape:w}});F.push(H);for(let X of F)r.disposeData(X.dataId);return z}function ule(e){let{inputs:t,backend:n,attrs:s}=e,{a:r,b:a,bias:o,preluActivationWeights:i}=t,{transposeA:l,transposeB:c,activation:u,leakyreluAlpha:d}=s;return ox({a:r,b:a,transposeA:l,transposeB:c,backend:n,bias:o,preluActivationWeights:i,leakyreluAlpha:d,activation:u})}var cle={kernelName:fo,backendName:"webgpu",kernelFunc:ule},H4=class{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.workGroupSize=[128,1,1],this.outputShape=N.assertAndGetBroadcastShape(t,n),this.dispatchLayout=Ke(this.outputShape),this.dispatch=Me(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey=`binaryOpComplex_${e}`,this.op=e,this.size=v.sizeFromShape(this.outputShape)}getUserCode(){return` + `}};function je(e){let{inputs:t,attrs:n}=e,{x:s}=t,{shape:r}=n,a=v.sizeFromShape(s.shape),o=v.inferFromImplicitShape(r,a),i=v.sizeFromShape(o);return v.assert(a===i,()=>`The new shape (${o}) has ${i} elements and the old shape (${s.shape}) has ${a} elements. The new shape and old shape must have the same number of elements.`),e.backend.incRef(s.dataId),{dataId:s.dataId,shape:o,dtype:s.dtype}}var lle={kernelName:Ti,backendName:"webgpu",kernelFunc:je};function ox({a:e,b:t,transposeA:n,transposeB:s,backend:r,bias:a=null,preluActivationWeights:o=null,leakyreluAlpha:i=0,activation:l=null}){let c=e.shape.length,u=t.shape.length,d=n?e.shape[c-2]:e.shape[c-1],p=s?t.shape[u-1]:t.shape[u-2],h=n?e.shape[c-1]:e.shape[c-2],f=s?t.shape[u-2]:t.shape[u-1],m=e.shape.slice(0,-2),g=t.shape.slice(0,-2),A=v.sizeFromShape(m),y=v.sizeFromShape(g),x=A===y||A===1||y===1;v.assert(c>=2&&u>=2&&x,()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${m}) and (${g}).`);let w=(A>y?e.shape.slice(0,-2):t.shape.slice(0,-2)).concat([h,f]);v.assert(d===p,()=>`Error in matMul: inner shapes (${d}) and (${p}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${n} and transposeB=${s} must match.`);let k=n?[A,d,h]:[A,h,d],S=s?[y,f,p]:[y,p,f],E=je({inputs:{x:e},backend:r,attrs:{shape:k}}),$=je({inputs:{x:t},backend:r,attrs:{shape:S}}),F=[E,$],R=Math.max(A,y),P=d%4==0&&f%4==0&&!n&&!s&&f>=32,T;!n&&!s&&(h<=16&&(f<=512||p>=2*f)||f<=16&&(h<=512||d>=2*h))?T=new ile(k,S,[R,h,f],a,l,o):P?T=new rle(k,[R,h,f],K().get("WEBGPU_MATMUL_WORK_PER_THREAD"),a,l,o):T=new G4(k,[R,h,f],K().get("WEBGPU_MATMUL_WORK_PER_THREAD"),n,s,a,l,o);let M=[E,$];a&&M.push(a),o&&M.push(o);let U=[{type:"int32",data:[h]},{type:"int32",data:[f]},{type:"int32",data:[d]}],H=r.runWebGPUProgram(T,M,e.dtype,U),z=je({inputs:{x:H},backend:r,attrs:{shape:w}});F.push(H);for(let X of F)r.disposeData(X.dataId);return z}function ule(e){let{inputs:t,backend:n,attrs:s}=e,{a:r,b:a,bias:o,preluActivationWeights:i}=t,{transposeA:l,transposeB:c,activation:u,leakyreluAlpha:d}=s;return ox({a:r,b:a,transposeA:l,transposeB:c,backend:n,bias:o,preluActivationWeights:i,leakyreluAlpha:d,activation:u})}var cle={kernelName:fo,backendName:"webgpu",kernelFunc:ule},H4=class{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.workGroupSize=[128,1,1],this.outputShape=N.assertAndGetBroadcastShape(t,n),this.dispatchLayout=Ke(this.outputShape),this.dispatch=Me(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey=`binaryOpComplex_${e}`,this.op=e,this.size=v.sizeFromShape(this.outputShape)}getUserCode(){return` fn binaryOpComplex( areal : f32, aimag : f32, breal : f32, bimag : f32) -> f32 { ${ep(this.op,!1)} @@ -5840,7 +5840,7 @@ return a / b;`,lre=` } } } - `}};function Q4({x:e,filter:t,convInfo:n,backend:s,bias:r=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let l=e.shape,c=n.dataFormat==="channelsLast",u=!1,d=!1,p=c?l[0]*l[1]*l[2]:l[0]*l[2]*l[3],h=je({inputs:{x:e},backend:s,attrs:{shape:[1,p,n.inChannels]}}),f=je({inputs:{x:t},backend:s,attrs:{shape:[1,n.inChannels,n.outChannels]}}),m=ox({a:h,b:f,transposeA:u,transposeB:d,backend:s,bias:r,activation:i,preluActivationWeights:a,leakyreluAlpha:o}),g=je({inputs:{x:m},backend:s,attrs:{shape:n.outShape}});return s.disposeData(h.dataId),s.disposeData(f.dataId),s.disposeData(m.dataId),g}function $ue({x:e,filter:t,convInfo:n,backend:s,bias:r=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let{filterWidth:l,filterHeight:c,inChannels:u,strideWidth:d,strideHeight:p,padInfo:h,outWidth:f,outHeight:m,dilationWidth:g,dilationHeight:A,dataFormat:y}=n,x=y==="channelsLast",b=l*c*u,w=m*f,k=[w,b],S=!1,E=!1,P=[],F=je({inputs:{x:e},backend:s,attrs:{shape:e.shape.slice(1)}}),R=je({inputs:{x:t},backend:s,attrs:{shape:[1,b,-1]}});P.push(F),P.push(R);let _=new Rue(k,x),T=[{type:"int32",data:[h.left,h.top]},{type:"int32",data:[d,p]},{type:"int32",data:[g,A]},{type:"int32",data:[f]},{type:"int32",data:[u*l]},{type:"int32",data:[u]}],M=s.runWebGPUProgram(_,[F],F.dtype,T),U=je({inputs:{x:M},backend:s,attrs:{shape:[1,k[0],k[1]]}});P.push(M),P.push(U);let H=[1,k[0],k[1]],z=new G4(H,[1,w,n.outChannels],K().get("WEBGPU_MATMUL_WORK_PER_THREAD"),S,E),X=H[1],ee=H[2],Y=n.outChannels,se=[{type:"int32",data:[X]},{type:"int32",data:[Y]},{type:"int32",data:[ee]}],ne=s.runWebGPUProgram(z,[U,R],U.dtype,se),J=x?[1,m,f,n.outChannels]:[1,n.outChannels,m,f],te=je({inputs:{x:ne},backend:s,attrs:{shape:J}});P.push(ne);for(let ue of P)s.disposeData(ue.dataId);return te}var eC=class{constructor(e,t=!1,n=null,s=!1,r=!1){this.variableNames=["x","W"],this.uniforms=`filterDims : vec2; pad : vec2; stride : vec2; dilation : vec2; + `}};function Q4({x:e,filter:t,convInfo:n,backend:s,bias:r=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let l=e.shape,c=n.dataFormat==="channelsLast",u=!1,d=!1,p=c?l[0]*l[1]*l[2]:l[0]*l[2]*l[3],h=je({inputs:{x:e},backend:s,attrs:{shape:[1,p,n.inChannels]}}),f=je({inputs:{x:t},backend:s,attrs:{shape:[1,n.inChannels,n.outChannels]}}),m=ox({a:h,b:f,transposeA:u,transposeB:d,backend:s,bias:r,activation:i,preluActivationWeights:a,leakyreluAlpha:o}),g=je({inputs:{x:m},backend:s,attrs:{shape:n.outShape}});return s.disposeData(h.dataId),s.disposeData(f.dataId),s.disposeData(m.dataId),g}function $ue({x:e,filter:t,convInfo:n,backend:s,bias:r=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let{filterWidth:l,filterHeight:c,inChannels:u,strideWidth:d,strideHeight:p,padInfo:h,outWidth:f,outHeight:m,dilationWidth:g,dilationHeight:A,dataFormat:y}=n,x=y==="channelsLast",b=l*c*u,w=m*f,k=[w,b],S=!1,E=!1,$=[],F=je({inputs:{x:e},backend:s,attrs:{shape:e.shape.slice(1)}}),R=je({inputs:{x:t},backend:s,attrs:{shape:[1,b,-1]}});$.push(F),$.push(R);let P=new Rue(k,x),T=[{type:"int32",data:[h.left,h.top]},{type:"int32",data:[d,p]},{type:"int32",data:[g,A]},{type:"int32",data:[f]},{type:"int32",data:[u*l]},{type:"int32",data:[u]}],M=s.runWebGPUProgram(P,[F],F.dtype,T),U=je({inputs:{x:M},backend:s,attrs:{shape:[1,k[0],k[1]]}});$.push(M),$.push(U);let H=[1,k[0],k[1]],z=new G4(H,[1,w,n.outChannels],K().get("WEBGPU_MATMUL_WORK_PER_THREAD"),S,E),X=H[1],ee=H[2],Y=n.outChannels,ne=[{type:"int32",data:[X]},{type:"int32",data:[Y]},{type:"int32",data:[ee]}],se=s.runWebGPUProgram(z,[U,R],U.dtype,ne),J=x?[1,m,f,n.outChannels]:[1,n.outChannels,m,f],te=je({inputs:{x:se},backend:s,attrs:{shape:J}});$.push(se);for(let ue of $)s.disposeData(ue.dataId);return te}var eC=class{constructor(e,t=!1,n=null,s=!1,r=!1){this.variableNames=["x","W"],this.uniforms=`filterDims : vec2; pad : vec2; stride : vec2; dilation : vec2; dimAOuter : i32; dimBOuter : i32; dimInner : i32;`,this.isVec4=!0,this.outputShape=e.outShape,v.assert(e.dataFormat==="channelsLast",()=>"TODO: NCHW is unimplemented"),this.dispatchLayout={x:[3],y:[1,2],z:[0]},this.workGroupSize=[8,8,1];let a=[4,4,1];this.dispatch=Me(this.dispatchLayout,this.outputShape,this.workGroupSize,a),this.convInfo=e,this.addBias=t,this.activation=n,this.hasPreluActivationWeights=s,this.hasLeakyreluAlpha=r,this.addBias&&this.variableNames.push("bias"),this.hasPreluActivationWeights&&this.variableNames.push("preluActivationWeights"),this.hasLeakyreluAlpha&&this.variableNames.push("leakyreluAlpha"),[this.fitA,this.fitB]=this.getShapeFit(a),this.shaderKey=`conv2DMMVec4_${this.activation}_${this.fitA}_${this.fitB}`}getShapeFit(e){let t=this.workGroupSize[1]*e[1],n=this.workGroupSize[0]*e[0],s=n,r=[t,s],a=[s,n],o=this.outputShape[1]*this.outputShape[2],i=this.outputShape[3],l=this.convInfo.filterHeight*this.convInfo.filterWidth*this.convInfo.inChannels;return[ia(r,[o,l]),ia(a,[l,i])]}getSampleAWithRemainder(e){return`let flatIndex${e} = getFlatIndex4D(coord, uniforms.xShape); let divBy4Remainder${e} = flatIndex${e} % 4; let divBy4Index${e} = flatIndex${e} / 4; @@ -6474,7 +6474,7 @@ return a / b;`,lre=` let inv = scaleValue * inverseSqrt(varianValue + f32(uniforms.varianceEpsilon)); writeResult(coords,dot(vec3(xValue, -meanValue, offsetValue), vec3(inv, inv, 1.0))); } - `}},vce={kernelName:za,backendName:"webgpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:s,scale:r,offset:a,mean:o,variance:i}=e,{varianceEpsilon:l}=t,c=n,u=[s,o,i],d=null;a!=null&&(d=a.shape,u.push(a));let p=null;r!=null&&(p=r.shape,u.push(r));let h=new bce(s.shape,o.shape,i.shape,d,p),f=[{type:"float32",data:[l]}];return c.runWebGPUProgram(h,u,s.dtype,f)}};function wce(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:c,dataFormat:u,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=s,m=N.convertConv2DDataFormat(u),g=N.computeConv2DInfo(r.shape,a.shape,l,d,c,p,!1,m),A=o!=null,y=i!=null,x;if(g.filterHeight===1&&g.filterWidth===1&&g.dilationHeight===1&&g.dilationWidth===1&&g.strideHeight===1&&g.strideWidth===1&&(g.padInfo.type==="SAME"||g.padInfo.type==="VALID"))return Q4({x:r,filter:a,convInfo:g,backend:n,bias:o,activation:h,preluActivationWeights:i,leakyreluAlpha:f});let b=K().getBool("WEBGPU_USE_NAIVE_CONV2D"),w=g.inChannels%4==0&&g.outChannels%4==0,k=[g.padInfo.top,g.padInfo.left],S=[{type:"int32",data:[g.filterHeight,g.filterWidth]},{type:"int32",data:[...k]},{type:"int32",data:[g.strideHeight,g.strideWidth]},{type:"int32",data:[g.dilationHeight,g.dilationWidth]}];if(b)x=new nC(g,A,h,y);else{w?x=new eC(g,A,h,y):x=new tC(g,A,h,y);let P=g.outShape[1]*g.outShape[2],F=g.outShape[3],R=g.filterHeight*g.filterWidth*g.inShape[3];S.push({type:"int32",data:[P]},{type:"int32",data:[F]},{type:"int32",data:[R]})}let E=[r,a];return A&&E.push(o),y&&E.push(i),n.runWebGPUProgram(x,E,r.dtype,S)}var kce={kernelName:mo,backendName:"webgpu",kernelFunc:wce};function Ice(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:c,dilations:u,dimRoundingMode:d,activation:p}=s,h=u;h==null&&(h=[1,1]),v.assert(N.eitherStridesOrDilationsAreOne(l,h),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${h}'`);let f=N.computeConv2DInfo(r.shape,a.shape,l,h,c,d,!0),m=[r,a],g=o!=null,A=i!=null;g&&m.push(o),A&&m.push(i);let y;f.batchSize===1&&f.inHeight===f.outHeight&&f.inWidth===f.outWidth&&f.strideHeight===1&&f.strideWidth===1&&f.filterHeight===f.filterWidth&&f.inChannels===f.outChannels&&f.filterHeight===3&&f.inChannels%4==0?y=new sC(f,g,p,A):y=new rC(f,g,p,A);let x=[{type:"int32",data:[f.padInfo.top,f.padInfo.left]},{type:"int32",data:[f.strideHeight,f.strideWidth]},{type:"int32",data:[f.dilationHeight,f.dilationWidth]},{type:"int32",data:[f.inHeight,f.inWidth]}];return n.runWebGPUProgram(y,m,"float32",x)}var Sce={kernelName:go,backendName:"webgpu",kernelFunc:Ice},Cce=class{constructor(e,t){this.variableNames=["A","indices"],this.workGroupSize=[64,1,1],this.outputShape=t,this.dispatchLayout=Ke(this.outputShape),this.dispatch=Me(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey=`gathernd_${e}`,this.size=v.sizeFromShape(this.outputShape),this.sliceDim=e,this.uniforms=`sliceDim : i32; strides : ${Qt(e)};`}getUserCode(){let e;return this.sliceDim>1?e="uniforms.strides[j]":e="uniforms.strides",` + `}},vce={kernelName:za,backendName:"webgpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:s,scale:r,offset:a,mean:o,variance:i}=e,{varianceEpsilon:l}=t,c=n,u=[s,o,i],d=null;a!=null&&(d=a.shape,u.push(a));let p=null;r!=null&&(p=r.shape,u.push(r));let h=new bce(s.shape,o.shape,i.shape,d,p),f=[{type:"float32",data:[l]}];return c.runWebGPUProgram(h,u,s.dtype,f)}};function wce(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:c,dataFormat:u,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=s,m=N.convertConv2DDataFormat(u),g=N.computeConv2DInfo(r.shape,a.shape,l,d,c,p,!1,m),A=o!=null,y=i!=null,x;if(g.filterHeight===1&&g.filterWidth===1&&g.dilationHeight===1&&g.dilationWidth===1&&g.strideHeight===1&&g.strideWidth===1&&(g.padInfo.type==="SAME"||g.padInfo.type==="VALID"))return Q4({x:r,filter:a,convInfo:g,backend:n,bias:o,activation:h,preluActivationWeights:i,leakyreluAlpha:f});let b=K().getBool("WEBGPU_USE_NAIVE_CONV2D"),w=g.inChannels%4==0&&g.outChannels%4==0,k=[g.padInfo.top,g.padInfo.left],S=[{type:"int32",data:[g.filterHeight,g.filterWidth]},{type:"int32",data:[...k]},{type:"int32",data:[g.strideHeight,g.strideWidth]},{type:"int32",data:[g.dilationHeight,g.dilationWidth]}];if(b)x=new nC(g,A,h,y);else{w?x=new eC(g,A,h,y):x=new tC(g,A,h,y);let $=g.outShape[1]*g.outShape[2],F=g.outShape[3],R=g.filterHeight*g.filterWidth*g.inShape[3];S.push({type:"int32",data:[$]},{type:"int32",data:[F]},{type:"int32",data:[R]})}let E=[r,a];return A&&E.push(o),y&&E.push(i),n.runWebGPUProgram(x,E,r.dtype,S)}var kce={kernelName:mo,backendName:"webgpu",kernelFunc:wce};function Ice(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:c,dilations:u,dimRoundingMode:d,activation:p}=s,h=u;h==null&&(h=[1,1]),v.assert(N.eitherStridesOrDilationsAreOne(l,h),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${h}'`);let f=N.computeConv2DInfo(r.shape,a.shape,l,h,c,d,!0),m=[r,a],g=o!=null,A=i!=null;g&&m.push(o),A&&m.push(i);let y;f.batchSize===1&&f.inHeight===f.outHeight&&f.inWidth===f.outWidth&&f.strideHeight===1&&f.strideWidth===1&&f.filterHeight===f.filterWidth&&f.inChannels===f.outChannels&&f.filterHeight===3&&f.inChannels%4==0?y=new sC(f,g,p,A):y=new rC(f,g,p,A);let x=[{type:"int32",data:[f.padInfo.top,f.padInfo.left]},{type:"int32",data:[f.strideHeight,f.strideWidth]},{type:"int32",data:[f.dilationHeight,f.dilationWidth]},{type:"int32",data:[f.inHeight,f.inWidth]}];return n.runWebGPUProgram(y,m,"float32",x)}var Sce={kernelName:go,backendName:"webgpu",kernelFunc:Ice},Cce=class{constructor(e,t){this.variableNames=["A","indices"],this.workGroupSize=[64,1,1],this.outputShape=t,this.dispatchLayout=Ke(this.outputShape),this.dispatch=Me(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey=`gathernd_${e}`,this.size=v.sizeFromShape(this.outputShape),this.sliceDim=e,this.uniforms=`sliceDim : i32; strides : ${Qt(e)};`}getUserCode(){let e;return this.sliceDim>1?e="uniforms.strides[j]":e="uniforms.strides",` ${Fe()} { ${We()} let coords = getOutputCoords(globalId, index); @@ -6496,7 +6496,7 @@ return a / b;`,lre=` setOutputFlat(index, getA(${e})); } } - `}};function Rce(e,t="int"){let n=["resRC.x","resRC.y","resRC.z","resRC.w"],s=[];for(let r=0;rn.disposeData(P.dataId)),n.makeTensorInfo(c.outputShape,E.dtype,E.values)}let m=new Ece(p.shape,f),g=n.runWebGPUProgram(m,[p,h],p.dtype);d.push(g);let A=je({inputs:{x:g},backend:n,attrs:{shape:c.outputShape}});return d.forEach(y=>n.disposeData(y.dataId)),A}var $ce={kernelName:pi,backendName:"webgpu",kernelFunc:cC},Dce=qn({opSnippet:Vt.GREATER,cpuKernelImpl:Sle,dtype:"bool"}),_ce={kernelName:fi,backendName:"webgpu",kernelFunc:Dce},Pce=qn({opSnippet:Vt.GREATER_EQUAL,dtype:"bool",cpuKernelImpl:Ile}),Fce={kernelName:La,backendName:"webgpu",kernelFunc:Pce},Oce=qn({opSnippet:Vt.LESS,dtype:"bool",cpuKernelImpl:Tle}),Mce={kernelName:gi,backendName:"webgpu",kernelFunc:Oce},zce=qn({opSnippet:Vt.LESS_EQUAL,dtype:"bool",cpuKernelImpl:Cle}),Lce={kernelName:Ai,backendName:"webgpu",kernelFunc:zce},Bce=Nn({opType:wt.LOG,cpuKernelImpl:Nle}),Wce={kernelName:Wa,backendName:"webgpu",kernelFunc:Bce},Vce=qn({opSnippet:Vt.LOGICAL_AND,dtype:"bool"}),Uce={kernelName:yi,backendName:"webgpu",kernelFunc:Vce},Gce=Nn({opType:wt.LOGICAL_NOT}),Hce={kernelName:ru,backendName:"webgpu",kernelFunc:Gce};function dC(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{reductionIndices:a,keepDims:o}=s;return np(r,a,o,"max",n)}var jce={kernelName:Va,backendName:"webgpu",kernelFunc:dC},qce=qn({opSnippet:Vt.MAX,cpuKernelImpl:Rle}),Xce={kernelName:Ua,backendName:"webgpu",kernelFunc:qce};function Kce(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:l}=s,c=1,u=N.computePool2DInfo(r.shape,a,o,c,i,l),d,p=[];if(u.filterHeight===1&&u.filterWidth===1){if(v.arraysEqual(u.inShape,u.outShape))return Js({inputs:{x:r},backend:n});d=new Z4(u),p.push({type:"int32",data:[u.strideHeight,u.strideWidth]})}else d=new K4(u,"max"),p.push({type:"int32",data:[u.strideHeight,u.strideWidth]},{type:"int32",data:[u.padInfo.top,u.padInfo.left]},{type:"int32",data:[u.dilationHeight,u.dilationWidth]},{type:"int32",data:[u.inHeight,u.inWidth]},{type:"int32",data:[u.effectiveFilterHeight,u.effectiveFilterWidth]});return n.runWebGPUProgram(d,[r],r.dtype,p)}var Zce={kernelName:Ga,backendName:"webgpu",kernelFunc:Kce};function Yce(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{keepDims:a,axis:o}=s;return np(r,o,a,"mean",n)}var Jce={kernelName:Ha,backendName:"webgpu",kernelFunc:Yce};function Qce(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s;return np(r,a,o,"min",n)}var ede={kernelName:ja,backendName:"webgpu",kernelFunc:Qce},tde=qn({opSnippet:Vt.MIN,cpuKernelImpl:$le}),nde={kernelName:qa,backendName:"webgpu",kernelFunc:tde},sde=class{constructor(e,t,n){this.uniforms="",this.variableNames=["x"],this.workGroupSize=[64,1,1],this.outputShape=t.map((s,r)=>s[0]+e[r]+s[1]),this.dispatchLayout=Ke(this.outputShape),this.dispatch=Me(this.dispatchLayout,this.outputShape,this.workGroupSize),this.xShape=e,t.map((s,r)=>{this.uniforms+=` pad${r} : vec2;`}),this.offset=n==="reflect"?0:1,this.shaderKey=`mirrorPad_${n}`,this.size=v.sizeFromShape(this.outputShape)}getUserCode(){let e=this.xShape.length,t=this.xShape.map((l,c)=>`uniforms.pad${c}[0]`).join(","),n=this.xShape.map((l,c)=>`uniforms.pad${c}[0] + uniforms.xShape${e>1?`[${c}]`:""}`).join(","),s=e===1?"start":"start[i]",r=e===1?"end":"end[i]",a=e===1?"outC":"outC[i]",o=Qt(e),i=e>1?["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,e):"coords";return` + `}};function Rce(e,t="int"){let n=["resRC.x","resRC.y","resRC.z","resRC.w"],s=[];for(let r=0;rn.disposeData($.dataId)),n.makeTensorInfo(c.outputShape,E.dtype,E.values)}let m=new Ece(p.shape,f),g=n.runWebGPUProgram(m,[p,h],p.dtype);d.push(g);let A=je({inputs:{x:g},backend:n,attrs:{shape:c.outputShape}});return d.forEach(y=>n.disposeData(y.dataId)),A}var $ce={kernelName:pi,backendName:"webgpu",kernelFunc:cC},Dce=qn({opSnippet:Vt.GREATER,cpuKernelImpl:Sle,dtype:"bool"}),_ce={kernelName:fi,backendName:"webgpu",kernelFunc:Dce},Pce=qn({opSnippet:Vt.GREATER_EQUAL,dtype:"bool",cpuKernelImpl:Ile}),Fce={kernelName:La,backendName:"webgpu",kernelFunc:Pce},Oce=qn({opSnippet:Vt.LESS,dtype:"bool",cpuKernelImpl:Tle}),Mce={kernelName:gi,backendName:"webgpu",kernelFunc:Oce},zce=qn({opSnippet:Vt.LESS_EQUAL,dtype:"bool",cpuKernelImpl:Cle}),Lce={kernelName:Ai,backendName:"webgpu",kernelFunc:zce},Bce=Nn({opType:wt.LOG,cpuKernelImpl:Nle}),Wce={kernelName:Wa,backendName:"webgpu",kernelFunc:Bce},Vce=qn({opSnippet:Vt.LOGICAL_AND,dtype:"bool"}),Uce={kernelName:yi,backendName:"webgpu",kernelFunc:Vce},Gce=Nn({opType:wt.LOGICAL_NOT}),Hce={kernelName:ru,backendName:"webgpu",kernelFunc:Gce};function dC(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{reductionIndices:a,keepDims:o}=s;return np(r,a,o,"max",n)}var jce={kernelName:Va,backendName:"webgpu",kernelFunc:dC},qce=qn({opSnippet:Vt.MAX,cpuKernelImpl:Rle}),Xce={kernelName:Ua,backendName:"webgpu",kernelFunc:qce};function Kce(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:l}=s,c=1,u=N.computePool2DInfo(r.shape,a,o,c,i,l),d,p=[];if(u.filterHeight===1&&u.filterWidth===1){if(v.arraysEqual(u.inShape,u.outShape))return Js({inputs:{x:r},backend:n});d=new Z4(u),p.push({type:"int32",data:[u.strideHeight,u.strideWidth]})}else d=new K4(u,"max"),p.push({type:"int32",data:[u.strideHeight,u.strideWidth]},{type:"int32",data:[u.padInfo.top,u.padInfo.left]},{type:"int32",data:[u.dilationHeight,u.dilationWidth]},{type:"int32",data:[u.inHeight,u.inWidth]},{type:"int32",data:[u.effectiveFilterHeight,u.effectiveFilterWidth]});return n.runWebGPUProgram(d,[r],r.dtype,p)}var Zce={kernelName:Ga,backendName:"webgpu",kernelFunc:Kce};function Yce(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{keepDims:a,axis:o}=s;return np(r,o,a,"mean",n)}var Jce={kernelName:Ha,backendName:"webgpu",kernelFunc:Yce};function Qce(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s;return np(r,a,o,"min",n)}var ede={kernelName:ja,backendName:"webgpu",kernelFunc:Qce},tde=qn({opSnippet:Vt.MIN,cpuKernelImpl:$le}),nde={kernelName:qa,backendName:"webgpu",kernelFunc:tde},sde=class{constructor(e,t,n){this.uniforms="",this.variableNames=["x"],this.workGroupSize=[64,1,1],this.outputShape=t.map((s,r)=>s[0]+e[r]+s[1]),this.dispatchLayout=Ke(this.outputShape),this.dispatch=Me(this.dispatchLayout,this.outputShape,this.workGroupSize),this.xShape=e,t.map((s,r)=>{this.uniforms+=` pad${r} : vec2;`}),this.offset=n==="reflect"?0:1,this.shaderKey=`mirrorPad_${n}`,this.size=v.sizeFromShape(this.outputShape)}getUserCode(){let e=this.xShape.length,t=this.xShape.map((l,c)=>`uniforms.pad${c}[0]`).join(","),n=this.xShape.map((l,c)=>`uniforms.pad${c}[0] + uniforms.xShape${e>1?`[${c}]`:""}`).join(","),s=e===1?"start":"start[i]",r=e===1?"end":"end[i]",a=e===1?"outC":"outC[i]",o=Qt(e),i=e>1?["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,e):"coords";return` ${Fe()} { ${We()} let start = ${o}(${t}); @@ -6716,7 +6716,7 @@ return a / b;`,lre=` setOutputFlat(index, getX(${t})); } } - `}};function fpe(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,end:o,strides:i,beginMask:l,endMask:c,ellipsisMask:u,newAxisMask:d,shrinkAxisMask:p}=s,{nonStrided:h,$begin:f,$strides:m,size:g,newShape:A,outShape:y}=An.sliceInfo(r.shape,a,o,i,l,c,u,d,p),x=je({inputs:{x:r},backend:n,attrs:{shape:A}}),b;if(h){let k=rc({inputs:{x},backend:n,attrs:{begin:f,size:g}});b=je({inputs:{x:k},backend:n,attrs:{shape:y}}),n.disposeData(k.dataId)}else if(y.some(k=>k===0))b=n.makeTensorInfo(y,r.dtype,[]);else if(n.shouldExecuteOnCPU([x])){let E=n.tensorMap.get(x.dataId).values,P=Le(x.shape,x.dtype,E),F=Ble(y,P,m,f);b=n.makeTensorInfo(y,x.dtype,F.values)}else{let S=new hpe(y),E=[{type:"int32",data:f},{type:"int32",data:m}];b=n.runWebGPUProgram(S,[x],x.dtype,E)}let w=je({inputs:{x:b},backend:n,attrs:{shape:y}});return n.disposeData(x.dataId),n.disposeData(b.dataId),w}var mpe={kernelName:Oi,backendName:"webgpu",kernelFunc:fpe};function gpe(e){let{inputs:t,backend:n,attrs:s}=e,{separator:r,nGramWidths:a,leftPad:o,rightPad:i,padWidth:l,preserveShortSequences:c}=s,{data:u,dataSplits:d}=t,p=n.readSync(u.dataId),h=n.readSync(d.dataId),[f,m]=Wle(p,h,r,a,o,i,l,c);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(d.shape,"int32",m)]}var Ape={kernelName:qc,backendName:"webgpu",kernelFunc:gpe},ype=Nn({opType:wt.TANH}),xpe={kernelName:co,backendName:"webgpu",kernelFunc:ype},bpe=class{constructor(e,t){this.variableNames=["A"],this.workGroupSize=[64,1,1];let n=new Array(e.length);for(let s=0;sk===0))b=n.makeTensorInfo(y,r.dtype,[]);else if(n.shouldExecuteOnCPU([x])){let E=n.tensorMap.get(x.dataId).values,$=Le(x.shape,x.dtype,E),F=Ble(y,$,m,f);b=n.makeTensorInfo(y,x.dtype,F.values)}else{let S=new hpe(y),E=[{type:"int32",data:f},{type:"int32",data:m}];b=n.runWebGPUProgram(S,[x],x.dtype,E)}let w=je({inputs:{x:b},backend:n,attrs:{shape:y}});return n.disposeData(x.dataId),n.disposeData(b.dataId),w}var mpe={kernelName:Oi,backendName:"webgpu",kernelFunc:fpe};function gpe(e){let{inputs:t,backend:n,attrs:s}=e,{separator:r,nGramWidths:a,leftPad:o,rightPad:i,padWidth:l,preserveShortSequences:c}=s,{data:u,dataSplits:d}=t,p=n.readSync(u.dataId),h=n.readSync(d.dataId),[f,m]=Wle(p,h,r,a,o,i,l,c);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(d.shape,"int32",m)]}var Ape={kernelName:qc,backendName:"webgpu",kernelFunc:gpe},ype=Nn({opType:wt.TANH}),xpe={kernelName:co,backendName:"webgpu",kernelFunc:ype},bpe=class{constructor(e,t){this.variableNames=["A"],this.workGroupSize=[64,1,1];let n=new Array(e.length);for(let s=0;sf===null?[d,d]:[d,f],g=(w,k,S)=>{let E=m(),P=new Ipe(S),R=[{type:"int32",data:[l]},{type:"int32",data:[f===null?1:0]},{type:"float32",data:[Number.NEGATIVE_INFINITY]},{type:"int32",data:[w]},{type:"int32",data:[k]}],_=f;f=n.runWebGPUProgram(P,E,"int32",R),ic(n,_)};for(let w=1;w=1;S/=2)g(k,S,[u,h])}for(let w=h;w>p;w/=2){let k=m(),S=new Spe([u,w/2]),P=[{type:"int32",data:[l]},{type:"int32",data:[f===null?1:0]},{type:"int32",data:[p]}],F=f;f=n.runWebGPUProgram(S,k,"int32",P),ic(n,F);let R=p/2,_=R*2;for(let T=R;T>=1;T/=2)g(_,T,f.shape)}let A=f;f=rc({inputs:{x:f},backend:n,attrs:{begin:0,size:[u,a]}}),ic(n,A);let y=cC({inputs:{x:d,indices:f},backend:n,attrs:{axis:1,batchDims:1}});ic(n,d);let x=i.slice(0,-1);x.push(a),A=f,f=je({inputs:{x:f},attrs:{shape:x},backend:n}),ic(n,A);let b=y;return y=je({inputs:{x:y},attrs:{shape:x},backend:n}),ic(n,b),[y,f]}var Tpe={kernelName:zi,backendName:"webgpu",kernelFunc:Cpe},Npe=class{constructor(e){this.variableNames=["Image","Transforms"],this.uniforms="interpolationModeId : i32; fillModeId : i32; fillValue : f32;",this.workGroupSize=[64,1,1],this.outputShape=e,this.dispatchLayout=Ke(this.outputShape),this.dispatch=Me(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="transform"}getUserCode(){return` + `}};function ic(e,t){t!==null&&e.disposeData(t.dataId)}function gC(e){let t=1;for(;tf===null?[d,d]:[d,f],g=(w,k,S)=>{let E=m(),$=new Ipe(S),R=[{type:"int32",data:[l]},{type:"int32",data:[f===null?1:0]},{type:"float32",data:[Number.NEGATIVE_INFINITY]},{type:"int32",data:[w]},{type:"int32",data:[k]}],P=f;f=n.runWebGPUProgram($,E,"int32",R),ic(n,P)};for(let w=1;w=1;S/=2)g(k,S,[u,h])}for(let w=h;w>p;w/=2){let k=m(),S=new Spe([u,w/2]),$=[{type:"int32",data:[l]},{type:"int32",data:[f===null?1:0]},{type:"int32",data:[p]}],F=f;f=n.runWebGPUProgram(S,k,"int32",$),ic(n,F);let R=p/2,P=R*2;for(let T=R;T>=1;T/=2)g(P,T,f.shape)}let A=f;f=rc({inputs:{x:f},backend:n,attrs:{begin:0,size:[u,a]}}),ic(n,A);let y=cC({inputs:{x:d,indices:f},backend:n,attrs:{axis:1,batchDims:1}});ic(n,d);let x=i.slice(0,-1);x.push(a),A=f,f=je({inputs:{x:f},attrs:{shape:x},backend:n}),ic(n,A);let b=y;return y=je({inputs:{x:y},attrs:{shape:x},backend:n}),ic(n,b),[y,f]}var Tpe={kernelName:zi,backendName:"webgpu",kernelFunc:Cpe},Npe=class{constructor(e){this.variableNames=["Image","Transforms"],this.uniforms="interpolationModeId : i32; fillModeId : i32; fillValue : f32;",this.workGroupSize=[64,1,1],this.outputShape=e,this.dispatchLayout=Ke(this.outputShape),this.dispatch=Me(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="transform"}getUserCode(){return` fn mapCoord(outCoord : f32, len : f32) -> f32{ var inCoord = outCoord; if(uniforms.fillModeId == 2) { @@ -6985,7 +6985,7 @@ return a / b;`,lre=` } } } - `}getUserCode(){return this.makeFromPixelsSource()}setPipeline(e){this.pipeline=e}setUniform(e,t){if(!this.uniform){let n=e.createBuffer({size:t.length*4,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});this.uniform=n}!t||t.length===this.lastUniformData.length&&t.every((n,s)=>n===this.lastUniformData[s])||(e.queue.writeBuffer(this.uniform,0,new Uint32Array(t)),this.lastUniformData=t)}makeInputTexture(e,t,n){return(!this.inputTexture||this.lastPixelSize.width!==t||this.lastPixelSize.height!==n)&&(this.inputTexture&&this.inputTexture.destroy(),this.inputTexture=e.createTexture({size:[t,n],format:"rgba8unorm",usage:GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),this.lastPixelSize.width=t,this.lastPixelSize.height=n),this.inputTexture}dispose(){this.disposed||(this.uniform&&this.uniform.destroy(),this.inputTexture&&this.inputTexture.destroy(),this.disposed=!0)}getLayout(e){return this.layout===null&&(this.layout=this.createTextureLayout(e)),this.layout}createTextureLayout(e){let t=[];t.push({binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}}),t.push({binding:1,visibility:GPUShaderStage.COMPUTE,texture:{}}),t.push({binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{}});let n=e.createBindGroupLayout({entries:t}),s=e.createPipelineLayout({bindGroupLayouts:[n]});return{bindGroupLayout:n,pipelineLayout:s}}},Fpe=class extends yC{constructor(){super(...arguments);this.layout=null,this.useImport=!0}getUserCode(){return this.makeFromPixelsSource()}getLayout(e){return this.layout===null&&(this.layout=this.createTextureImportLayout(e)),this.layout}createTextureImportLayout(e){let t=[];t.push({binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}}),t.push({binding:1,visibility:GPUShaderStage.COMPUTE,externalTexture:{}}),t.push({binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{}});let n=e.createBindGroupLayout({entries:t}),s=e.createPipelineLayout({bindGroupLayouts:[n]});return{bindGroupLayout:n,pipelineLayout:s}}},Ope=K().getNumber("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD"),xC=class extends Ll{constructor(e,t=!1){super();if(this.commandQueueOwnedIds=new WeakSet,this.tensorDisposalQueue=[],this.uniformDisposalQueue=[],this.disposed=!1,this.uploadWaitMs=0,this.downloadWaitMs=0,this.dispatchNumberInEncoder=0,!rx())throw new Error("WebGPU is not supported on this device");this.layoutCache={},this.pipelineCache={},this.device=e,this.queue=e.queue,this.currentCommandEncoder=null,this.currentComputePass=null,this.supportTimeQuery=t,this.bufferManager=new Ppe(this.device),this.tensorMap=new Dc(this,ss()),this.supportTimeQuery&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:2})),K().getBool("WEBGPU_USE_PROFILE_TOOL")&&(this.dummyCanvas=document.createElement("canvas"),this.dummyCanvas.width=1,this.dummyCanvas.height=1,this.dummyContext=this.dummyCanvas.getContext("webgpu"),this.dummyContext.configure({device:e,format:"bgra8unorm"}),document.body.appendChild(this.dummyCanvas))}nextDataId(){return xC.nextDataId++}floatPrecision(){return 32}defaultGpuBufferUsage(){return GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST}flushDisposalQueue(){this.tensorDisposalQueue.forEach(e=>{this.maybeReleaseBuffer(e),this.tensorMap.delete(e)}),this.uniformDisposalQueue.forEach(e=>this.bufferManager.releaseBuffer(e.buffer,e.byteSize,e.usage)),this.tensorDisposalQueue=[],this.uniformDisposalQueue=[]}disposeData(e,t=!1){if(this.tensorMap.has(e)){let n=this.tensorMap.get(e);if(n.refCount--,!t&&n.refCount>0)return!1;if(this.commandQueueOwnedIds.has(e))return this.tensorDisposalQueue.push(e),!1;this.maybeReleaseBuffer(e);let{complexTensorInfos:s}=this.tensorMap.get(e);s!=null&&(this.disposeData(s.real.dataId,!0),this.disposeData(s.imag.dataId,!0)),this.tensorMap.delete(e)}return!0}memory(){return{numBytesInGPU:this.bufferManager.numBytesUsed,numBytesAllocatedInGPU:this.bufferManager.numBytesAllocated,unreliable:!1}}getBufferManager(){return this.bufferManager}acquireBuffer(e,t=this.defaultGpuBufferUsage()){return this.bufferManager.acquireBuffer(e,t)}maybeReleaseBuffer(e){let t=this.tensorMap.get(e);t!=null&&t.bufferInfo.buffer!=null&&(this.bufferManager.releaseBuffer(t.bufferInfo.buffer,t.bufferInfo.byteSize,t.bufferInfo.usage),t.bufferInfo.buffer=null)}refCount(e){return this.tensorMap.has(e)?this.tensorMap.get(e).refCount:0}incRef(e){let t=this.tensorMap.get(e);t.refCount++}decRef(e){if(this.tensorMap.has(e)){let t=this.tensorMap.get(e);t.refCount--}}write(e,t,n){if(n==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let s={id:this.nextDataId()},r=v.sizeFromShape(t)*sx(n);return n==="bool"&&e instanceof Uint8Array&&(e=Int32Array.from(e)),this.tensorMap.set(s,{dtype:n,values:e,bufferInfo:{byteSize:r,usage:this.defaultGpuBufferUsage()},refCount:1}),s}move(e,t,n,s,r){if(s==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let a=v.sizeFromShape(n)*sx(s);this.tensorMap.set(e,{dtype:s,values:t,bufferInfo:{byteSize:a,usage:this.defaultGpuBufferUsage()},refCount:r})}submitQueue(){this.ensureComputePassEnded(),this.queue.submit([this.currentCommandEncoder.finish()]),this.currentCommandEncoder=null,this.dispatchNumberInEncoder=0,this.commandQueueOwnedIds=new WeakSet,this.flushDisposalQueue()}getBuffer(e){return this.uploadToGPU(e),this.tensorMap.get(e).bufferInfo.buffer}getFromPixelsProgram(e){switch(e){case"copyExternal":return this.fromPixelProgram||(this.fromPixelProgram=new yC),this.fromPixelProgram;case"import":return this.fromPixelImportProgram||(this.fromPixelImportProgram=new Fpe),this.fromPixelImportProgram;default:v.assert(!1,()=>"Unsupported fromPixels shape");return}}ensureCommandEncoderReady(){this.currentCommandEncoder||(this.currentCommandEncoder=this.device.createCommandEncoder())}ensureComputePassEnded(){this.currentComputePass&&(this.currentComputePass.endPass(),this.currentComputePass=null)}getComputePass(){return this.currentComputePass||(this.currentComputePass=this.currentCommandEncoder.beginComputePass()),this.currentComputePass}async getBufferData(e){if(e.values!=null)return e.values;let t=this.acquireBuffer(e.bufferInfo.byteSize,GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ);this.ensureCommandEncoderReady(),this.ensureComputePassEnded(),this.currentCommandEncoder.copyBufferToBuffer(e.bufferInfo.buffer,0,t,0,e.bufferInfo.byteSize),this.submitQueue(),await t.mapAsync(GPUMapMode.READ);let n=t.getMappedRange().slice(0);return t.unmap(),t!=null&&this.bufferManager.releaseBuffer(t,e.bufferInfo.byteSize,GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ),K().getBool("WEBGPU_USE_PROFILE_TOOL")&&(v.assert(this.dummyContext!==void 0,()=>"Fail to get context for profiling tool"),this.dummyContext.getCurrentTexture()),n}convertAndCacheOnCPU(e,t){let n=this.tensorMap.get(e);return this.maybeReleaseBuffer(e),n.values=t,n.values}readSync(e){let t=this.tensorMap.get(e),{values:n}=t;if(n==null)throw new Error("WebGPU readSync is only available for CPU-resident tensors.");return n}async read(e){if(!this.tensorMap.has(e))throw new Error(`Tensor ${e} was not registered!`);let t=this.tensorMap.get(e),{values:n}=t;if(n!=null)return this.convertAndCacheOnCPU(e,n);let s;if(t.dtype==="complex64"){let r=await Promise.all([this.read(t.complexTensorInfos.real.dataId),this.read(t.complexTensorInfos.imag.dataId)]),a=r[0],o=r[1];s=N.mergeRealAndImagArrays(a,o)}else{let r=await this.getBufferData(t);s=B4(r,t.dtype)}return this.convertAndCacheOnCPU(e,s),s}bufferSync(e){let t=this.readSync(e.dataId),n=t;if(e.dtype==="string")try{n=t.map(s=>v.decodeString(s))}catch(s){throw new Error("Failed to decode encoded string bytes into utf-8")}return Le(e.shape,e.dtype,n)}async time(e){let t=this.activeTimers,n=[],s=!1;this.programTimersStack==null?(this.programTimersStack=n,s=!0):this.activeTimers.push(n),this.activeTimers=n,e();let r=v.flatten(this.activeTimers.map(l=>l.query)).filter(l=>l!=null),a=v.flatten(this.activeTimers.map(l=>l.name)).filter(l=>l!=null);this.activeTimers=t,s&&(this.programTimersStack=null);let o={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null},i=await Promise.all(r);return o.kernelMs=v.sum(i),o.getExtraProfileInfo=()=>i.map((l,c)=>({name:a[c],ms:l})).map(l=>`${l.name}: ${l.ms}`).join(", "),this.uploadWaitMs=0,this.downloadWaitMs=0,o}getAndSavePipeline(e,t){return e in this.pipelineCache||(this.pipelineCache[e]=t()),this.pipelineCache[e]}makeTensorInfo(e,t,n){let s;if(t==="string"&&n!=null&&n.length>0&&v.isString(n[0])){let r=n.map(a=>v.encodeString(a));s=this.write(r,e,t)}else s=this.write(n,e,t);return{dataId:s,shape:e,dtype:t}}tensorToBinding(e){if(!e)return null;let t=this.tensorMap.get(e.dataId);return{offset:0,size:t.bufferInfo.byteSize,buffer:t.bufferInfo.buffer}}async getQueryTime(e){return this.supportTimeQuery?this.getTimeFromQuerySet(e):0}uploadToGPU(e){let t=this.tensorMap.get(e);t.bufferInfo.buffer==null&&(t.bufferInfo.buffer=this.acquireBuffer(t.bufferInfo.byteSize),t.values&&this.queue.writeBuffer(t.bufferInfo.buffer,0,t.values))}makeUniformsDataView(e){let t=this.acquireBuffer(e.byteLength,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);return this.queue.writeBuffer(t,0,e),{offset:0,size:e.byteLength,buffer:t}}arrayToDataView(e,t){let n=4,s=new DataView(new ArrayBuffer(t*n)),r=0;return e.forEach(a=>{let o=a.data;if(a.type!=="int32"&&a.type!=="float32"&&a.type!=="uint32")throw new Error(`${a.type} not supported!`);a.type==="int32"?o.forEach(i=>{s.setInt32(r*n,i,!0),r++}):a.type==="uint32"?o.forEach(i=>{s.setUint32(r*n,i,!0),r++}):o.forEach(i=>{s.setFloat32(r*n,i,!0),r++})}),s}computePadding(e){let t=0,n=0,s=0,r=[];return e.forEach((a,o)=>{a.data.length===0&&(a.data=[1]);let i;switch(a.data.length){case 0:i=1;break;case 1:i=1;break;case 2:i=2;break;case 3:i=4;break;case 4:i=4;break;default:v.assert(!1,()=>`Unsupported ${a.data.length}D shape`)}n=Math.ceil(t/i)*i-t;for(let l=0;lE.shape),i="int32";o.map(E=>{a.push({type:i,data:E})});let l=v.computeStrides(r.shape);a.push({type:i,data:l}),e.size!=null&&a.push({type:i,data:[e.size]}),a.push({type:"uint32",data:e.dispatch}),s&&(a=[...a,...s]);let c=null,u=this.computePadding(a),d=u.byteLength;c=this.makeUniformsDataView(u);let p=t.map((E,P)=>{if(E.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");return this.uploadToGPU(E.dataId),{dtype:this.tensorMap.get(E.dataId).dtype,shape:E.shape,name:e.variableNames[P]}}),h=p.map(E=>E.dtype).concat(r.dtype),f=p.map(E=>N.getBroadcastDims(E.shape,r.shape)),m=p.map(E=>v.arraysEqual(E.shape,r.shape)).join("_"),g=f.map(E=>E.join("_")).join(";"),A=lC(e,o,h,g,m),{bindGroupLayout:y,pipelineLayout:x}=this.getCachedOrCreateLayout(e.variableNames.length),b=this.getAndSavePipeline(A,()=>iC(this.device,e,x,p,r)),w=this.activeTimers!=null,k=Ace(this.device,y,t.map(E=>this.tensorToBinding(E)),this.tensorToBinding(r),c);this.ensureCommandEncoderReady();let S=this.getComputePass();if(w&&this.supportTimeQuery&&S.writeTimestamp(this.querySet,0),S.setPipeline(b),S.setBindGroup(0,k),S.dispatch(e.dispatch[0],e.dispatch[1],e.dispatch[2]),w&&this.supportTimeQuery&&S.writeTimestamp(this.querySet,1),this.dispatchNumberInEncoder++,t.forEach(E=>{this.commandQueueOwnedIds.add(E.dataId)}),this.commandQueueOwnedIds.add(r.dataId),c){let E={byteSize:d,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM,buffer:c.buffer};this.uniformDisposalQueue.push(E)}return K().get("WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE")<=this.dispatchNumberInEncoder&&this.submitQueue(),w&&this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(this.querySet)}),r}runFromPixelsProgram(e,t,n,s,r){let a=this.device.createBindGroup({layout:n.bindGroupLayout,entries:[{binding:0,resource:{buffer:t}},{binding:1,resource:s},{binding:2,resource:{buffer:e.uniform}}]});this.ensureCommandEncoderReady();let o=this.getComputePass(),i=this.activeTimers!=null;i&&this.supportTimeQuery&&o.writeTimestamp(this.querySet,0),o.setPipeline(e.pipeline),o.setBindGroup(0,a),o.dispatch(e.dispatch[0],e.dispatch[1],e.dispatch[2]),i&&this.supportTimeQuery&&o.writeTimestamp(this.querySet,1),this.commandQueueOwnedIds.add(r),this.submitQueue(),i&&this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(this.querySet)})}async getTimeFromQuerySet(e){let t=this.acquireBuffer(16,GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE),n=this.acquireBuffer(16,GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST);this.ensureCommandEncoderReady(),this.ensureComputePassEnded(),this.currentCommandEncoder.resolveQuerySet(e,0,2,t,0),this.currentCommandEncoder.copyBufferToBuffer(t,0,n,0,16),this.submitQueue(),await n.mapAsync(GPUMapMode.READ);let s=new BigUint64Array(n.getMappedRange()),r=Number(s[1]-s[0]);return n.unmap(),this.bufferManager.releaseBuffer(n,16,GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST),this.bufferManager.releaseBuffer(t,16,GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE),r/1e6}shouldExecuteOnCPU(e,t=Ope){return K().getBool("WEBGPU_CPU_FORWARD")&&e.every(n=>this.tensorMap.get(n.dataId).bufferInfo.buffer==null&&v.sizeFromShape(n.shape)px,webgpu_util:()=>L4});gu.isBrowser()&&rx()&&Ki("webgpu",async()=>{K().set("CHECK_COMPUTATION_FOR_ERRORS",!1);let e={powerPreference:K().get("WEBGPU_USE_LOW_POWER_GPU")?"low-power":"high-performance"},t=await navigator.gpu.requestAdapter(e),n={},s=t.features.has("timestamp-query");s?n={requiredFeatures:["timestamp-query"]}:console.warn("This device doesn't support timestamp-query extension. Start Chrome browser with flag --disable-dawn-features=disallow_unsafe_apis then try again. Or zero will shown for the kernel time when profiling mode isenabled. Using performance.now is not workable for webgpu sinceit doesn't support synchronously to read data from GPU.");let r=await t.requestDevice(n);return new px(r,s)},3);var en;(function(e){e[e.float32=0]="float32",e[e.int32=1]="int32",e[e.bool=2]="bool",e[e.string=3]="string",e[e.complex64=4]="complex64"})(en||(en={}));var sp;(function(e){e[e.linear=0]="linear",e[e.relu=1]="relu",e[e.relu6=2]="relu6",e[e.prelu=3]="prelu",e[e.leakyrelu=4]="leakyrelu",e[e.sigmoid=5]="sigmoid",e[e.elu=6]="elu"})(sp||(sp={}));var vC;function Mpe(e){vC=e.wasm.cwrap(fo,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function zpe(e){let{inputs:t,backend:n,attrs:s}=e,{a:r,b:a,bias:o,preluActivationWeights:i}=t;if(r.dtype!=="float32"||a.dtype!=="float32")throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");let{transposeA:l,transposeB:c,activation:u,leakyreluAlpha:d}=s,p=n.dataIdMap.get(r.dataId).id,h=n.dataIdMap.get(a.dataId).id,f=0;if(o!=null){let E=n.dataIdMap.get(o.dataId);if(E.shape.length!==1)throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${E.shape.length}.`);f=E.id}let m=i==null?0:n.dataIdMap.get(i.dataId).id,g=sp[u];if(g==null)throw new Error(`${u} activation not yet supported for FusedConv2D in the wasm backend.`);let A=l?r.shape[2]:r.shape[1],y=c?a.shape[1]:a.shape[2],x=r.shape[0],b=n.makeOutput([x,A,y],r.dtype),w=n.dataIdMap.get(b.dataId).id,k=new Uint8Array(new Int32Array(r.shape).buffer),S=new Uint8Array(new Int32Array(a.shape).buffer);return vC(p,k,r.shape.length,h,S,a.shape.length,l,c,g,f,m,d||0,w),b}var Lpe={kernelName:fo,backendName:"wasm",setupFunc:Mpe,kernelFunc:zpe};function En(e,t){let n;function s(a){n=a.wasm.cwrap(e,null,["number","number","number"])}function r(a){let{backend:o,inputs:{x:i}}=a,l=o.dataIdMap.get(i.dataId).id,c=o.makeOutput(i.shape,t||i.dtype),u=o.dataIdMap.get(c.dataId).id;return v.sizeFromShape(c.shape)===0||n(l,en[i.dtype],u),c}return{kernelName:e,backendName:"wasm",setupFunc:s,kernelFunc:r}}var Bpe=En(ni);function Xn(e,t,n){let s;function r(o){s=o.wasm.cwrap(e,null,["number","array","number","number","array","number","number","number"])}function a(o){let{backend:i,inputs:l}=o,{a:c,b:u}=l,d=i.dataIdMap.get(c.dataId).id,p=i.dataIdMap.get(u.dataId).id,h=n!=null?n:c.dtype,f=N.assertAndGetBroadcastShape(c.shape,u.shape),m=i.makeOutput(f,h);if(v.sizeFromShape(f)===0)return m;let g=new Uint8Array(new Int32Array(c.shape).buffer),A=new Uint8Array(new Int32Array(u.shape).buffer),y=i.dataIdMap.get(m.dataId).id,x=()=>s(d,g,c.shape.length,p,A,u.shape.length,en[c.dtype],y);if(t&&c.dtype==="float32")return x(),m;let b=N.getBroadcastDims(c.shape,f),w=N.getBroadcastDims(u.shape,f),k=b.every((E,P)=>E===P),S=w.every((E,P)=>E===P);if(k&&S)return x(),m;throw new Error(`Broadcasting along outer dims is not yet supported for ${c.dtype} ${e}.`)}return{kernelName:e,backendName:"wasm",setupFunc:r,kernelFunc:a}}var Wpe=!0,Vpe=Xn(Hr,Wpe),wC;function Upe(e){wC=e.wasm.cwrap(wa,null,["array","number","number","number"])}function Gpe(e){let{inputs:t,backend:n}=e,s=n.makeOutput(t[0].shape,t[0].dtype);if(v.sizeFromShape(s.shape)===0)return s;let r=t.map(i=>n.dataIdMap.get(i.dataId).id),a=new Uint8Array(new Int32Array(r).buffer),o=n.dataIdMap.get(s.dataId).id;return wC(a,r.length,en[s.dtype],o),s}var Hpe={kernelName:wa,backendName:"wasm",setupFunc:Upe,kernelFunc:Gpe};function Mm(e){let{inputs:{x:t},backend:n}=e,s=n.makeOutput(t.shape,t.dtype),r=n.typedArrayFromHeap(t);return n.typedArrayFromHeap(s).set(r),s}var jpe={kernelName:Ba,backendName:"wasm",kernelFunc:Mm},kC;function qpe(e){kC=e.wasm.cwrap(po,null,["number","array","number","number","number","array","number"])}function lc(e){let{inputs:t,backend:n,attrs:s}=e,[r,a]=Kpe(t.x.shape,s.perm),o=!0;for(let f=0;f=r&&(a===-1||s[a]>s[o])&&(a=o);s[a]=r}return[n,s]}var Zpe={kernelName:po,backendName:"wasm",kernelFunc:lc,setupFunc:qpe};function zo(e,t,n){let s=e.shape,r=e.shape.length,a=v.parseAxisParam(t,s),o=a,i=N.getAxesPermutation(o,r),l=null,c=!1;if(i!=null){let u=new Array(r);for(let h=0;h`new shape: ${o}, old shape: ${s.shape}. New shape and old shape must have the same number of elements.`),e.backend.incRef(s.dataId),{dataId:s.dataId,shape:o,dtype:s.dtype}}var uhe={kernelName:Ti,backendName:"wasm",kernelFunc:us},NC;function che(e){NC=e.wasm.cwrap(Sa,null,["number","array","number","number","array","number","number","number","number"])}function dhe(e){let{inputs:t,backend:n,attrs:s}=e,{a:r,b:a}=t,{transposeA:o,transposeB:i}=s;if(r.dtype!=="float32"||a.dtype!=="float32")throw new Error("BatchMatMul for non non-float32 tensors not yet supported.");let l=r.shape.length,c=a.shape.length,u=o?r.shape[l-2]:r.shape[l-1],d=i?a.shape[c-1]:a.shape[c-2],p=o?r.shape[l-1]:r.shape[l-2],h=i?a.shape[c-2]:a.shape[c-1],f=r.shape.slice(0,-2),m=a.shape.slice(0,-2),g=v.sizeFromShape(f),A=v.sizeFromShape(m),y=g===A||g===1||A===1;v.assert(l>=2&&c>=2&&y,()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${f}) and (${m}).`);let b=(g>A?r.shape.slice(0,-2):a.shape.slice(0,-2)).concat([p,h]);v.assert(u===d,()=>`Error in matMul: inner shapes (${u}) and (${d}) of Tensors with shapes ${r.shape} and ${a.shape} and transposeA=${o} and transposeB=${i} must match.`);let w=o?[g,u,p]:[g,p,u],k=i?[A,h,d]:[A,d,h],S=us({inputs:{x:r},backend:n,attrs:{shape:w}}),E=us({inputs:{x:a},backend:n,attrs:{shape:k}}),P=n.dataIdMap.get(S.dataId).id,F=n.dataIdMap.get(E.dataId).id,R=o?S.shape[2]:S.shape[1],_=i?E.shape[1]:E.shape[2],T=Math.max(g,A),M=n.makeOutput([T,R,_],S.dtype),U=n.dataIdMap.get(M.dataId).id,H=new Uint8Array(new Int32Array(S.shape).buffer),z=new Uint8Array(new Int32Array(E.shape).buffer);return NC(P,H,S.shape.length,F,z,E.shape.length,o,i,U),n.disposeData(S.dataId),n.disposeData(E.dataId),M.shape=b,M}var phe={kernelName:Sa,backendName:"wasm",setupFunc:che,kernelFunc:dhe};function rp(e){let{inputs:{x:t},attrs:{begin:n,size:s},backend:r}=e,[a,o]=An.parseSliceParams(t,n,s),i=An.isSliceContinous(t.shape,a,o),l=r.readSync(t.dataId),c=r.makeOutput(o,t.dtype),u=v.computeStrides(t.shape),d=r.dataIdMap.get(c.dataId);if(i){let f=An.computeFlatOffset(a,u);return t.dtype==="string"?d.stringBytes=l.slice(f,f+v.sizeFromShape(o)):r.typedArrayFromHeap(c).set(l.subarray(f,f+v.sizeFromShape(o))),c}if(t.dtype==="string"){let f=um(l,a,o,t.shape,t.dtype);return d.stringBytes=f,c}let p=r.typedArrayFromHeap(c),h=t.shape.length;if(h===2)hhe(l,u[0],p,a,o);else if(h===3)fhe(l,u[0],u[1],p,a,o);else if(h===4)mhe(l,u[0],u[1],u[2],p,a,o);else{let f=um(l,a,o,t.shape,t.dtype);p.set(f)}return c}function hhe(e,t,n,s,r){let a=0,o=s[0],i=s[1],l=o+r[0];for(let c=o;cA*y),l=N.getReshaped(r.shape,a,i),c=N.getPermuted(l.length,a.length),u=N.getReshapedPermuted(r.shape,a,i),d=N.getSliceBeginCoords(o,a.length),p=N.getSliceSize(u,o,a.length),h=us({inputs:{x:r},backend:n,attrs:{shape:l}}),f=lc({inputs:{x:h},backend:n,attrs:{perm:c}}),m=us({inputs:{x:f},backend:n,attrs:{shape:u}}),g=rp({inputs:{x:m},backend:n,attrs:{begin:d,size:p}});return n.disposeData(h.dataId),n.disposeData(f.dataId),n.disposeData(h.dataId),g}var yhe={kernelName:si,backendName:"wasm",kernelFunc:Ahe};function ap(e){let{inputs:{x:t},attrs:{dtype:n},backend:s}=e,r=s.makeOutput(t.shape,n),a=s.typedArrayFromHeap(t);return s.typedArrayFromHeap(r).set(a),r}var xhe={kernelName:Ca,backendName:"wasm",kernelFunc:ap},bhe=En(Ta),EC;function vhe(e){EC=e.wasm.cwrap(jr,null,["number","number","number","number"])}function whe(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{clipValueMin:a,clipValueMax:o}=s,i=n.dataIdMap.get(r.dataId).id,l=n.makeOutput(r.shape,r.dtype),c=n.dataIdMap.get(l.dataId).id;return EC(i,a,o,c),l}var khe={kernelName:jr,backendName:"wasm",setupFunc:vhe,kernelFunc:whe};function RC(e){let{inputs:t,backend:n}=e,s=v.parseAxisParam(e.attrs.axis,t[0].shape)[0],r=N.computeOutShape(t.map(h=>h.shape),s),a=t.filter(h=>v.sizeFromShape(h.shape)>0);if(a.length===1)return Mm({inputs:{x:a[0]},backend:n});let o=n.makeOutput(r,t[0].dtype);if(v.sizeFromShape(r)===0)return o;let i=a.map(h=>h.shape);if(N.assertParamsConsistent(i,s),a[0].dtype==="string"){let h=a.map(x=>{let b=v.sizeFromShape(x.shape.slice(s));return us({inputs:{x},backend:n,attrs:{shape:[-1,b]}})}),f=h.map(x=>({vals:n.readSync(x.dataId),shape:x.shape}));r=N.computeOutShape(h.map(x=>x.shape),1);let m=h[0].shape[0]===1,g=wy(f,r,t[0].dtype,m),A=N.computeOutShape(a.map(x=>x.shape),s);o.shape=A;let y=n.dataIdMap.get(o.dataId);return y.stringBytes=N.fromStringArrayToUint8(g),h.forEach(x=>n.disposeData(x.dataId)),o}let l=v.sizeFromShape(a[0].shape.slice(0,s)),c=0,u=a.map(h=>{let f=v.sizeFromShape(h.shape.slice(s));return c+=f,f}),d=a.map(h=>n.typedArrayFromHeap(h)),p=n.typedArrayFromHeap(o);for(let h=0;h`cumsum does not support ${r.dtype} tensors in the WASM backend`);let c=N.getAxesPermutation([a],l),u=r;c!==null&&(u=lc({inputs:{x:r},attrs:{perm:c},backend:n}));let d=N.getInnerMostAxes(1,l)[0];N.assertAxesAreInnerMostDims("cumsum",[d],l);let p=n.makeOutput(u.shape,u.dtype),h=u.shape[d],f=n.dataIdMap.get(u.dataId).id,m=n.dataIdMap.get(p.dataId).id;PC(f,o?1:0,i?1:0,h,m,en[r.dtype]);let g=p;if(c!==null){let A=N.getUndoAxesPermutation(c);g=lc({inputs:{x:p},attrs:{perm:A},backend:n}),n.disposeData(u.dataId),n.disposeData(p.dataId)}return g}var zhe={kernelName:ai,backendName:"wasm",setupFunc:Ohe,kernelFunc:Mhe},FC;function Lhe(e){FC=e.wasm.cwrap(ii,null,["number","number","number","array","number","array","array","number","number"])}function Bhe(e){let{backend:t,inputs:n,attrs:s}=e,{x:r}=n,{blockSize:a,dataFormat:o}=s,i=r.shape[0],l=o==="NHWC"?r.shape[1]:r.shape[2],c=o==="NHWC"?r.shape[2]:r.shape[3],u=o==="NHWC"?r.shape[3]:r.shape[1],d=l*a,p=c*a,h=u/(a*a),f=o==="NHWC"?[i,d,p,h]:[i,h,d,p],m=t.makeOutput(f,"float32"),A=t.dataIdMap.get(r.dataId).id,y=new Uint8Array(new Int32Array(v.computeStrides(r.shape)).buffer),x=new Uint8Array(new Int32Array(f).buffer),b=new Uint8Array(new Int32Array(v.computeStrides(f)).buffer),w=t.dataIdMap.get(m.dataId).id;return FC(A,a,o==="NHWC"?1:0,y,r.shape.length-1,x,b,f.length,w),m}var Whe={kernelName:ii,backendName:"wasm",setupFunc:Lhe,kernelFunc:Bhe},OC;function Vhe(e){OC=e.wasm.cwrap(Da,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Uhe(e){let{inputs:t,attrs:n,backend:s}=e,{x:r,filter:a}=t,o=s.dataIdMap.get(r.dataId).id,i=s.dataIdMap.get(a.dataId).id,{strides:l,dilations:c,pad:u,dimRoundingMode:d}=n,p=c==null?[1,1]:c,h=N.computeConv2DInfo(r.shape,a.shape,l,p,u,d,!0),f=h.filterHeight,m=h.filterWidth,g=h.padInfo.top,A=h.padInfo.right,y=h.padInfo.bottom,x=h.padInfo.left,b=h.dilationHeight,w=h.dilationWidth,k=h.strideHeight,S=h.strideWidth,E=h.inChannels,P=h.outChannels,F=h.padInfo.type==="SAME"?1:0;if(h.dataFormat!=="channelsLast")throw new Error(`wasm backend DepthwiseConv2dNative does not support dataFormat:'${h.dataFormat}'. Please use 'channelsLast'.`);let R=s.makeOutput(h.outShape,"float32"),_=s.dataIdMap.get(R.dataId).id;return OC(o,r.shape[0],r.shape[1],r.shape[2],i,f,m,g,A,y,x,F,b,w,k,S,E,P,_),R}var Ghe={kernelName:Da,backendName:"wasm",setupFunc:Vhe,kernelFunc:Uhe},Hhe=En(Pa),jhe=!1,qhe=Xn(li,jhe,"bool"),Xhe=En(Fa,"float32");function fx(e){let{inputs:t,attrs:n,backend:s}=e,{input:r}=t,{dim:a}=n,o=r.shape.length,i=r.shape.slice(),l=a;return a<0&&(v.assert(-(o+1)<=a,()=>`Axis must be in the interval [${-(o+1)}, ${o}]`),l=o+a+1),i.splice(l,0,1),us({inputs:{x:r},backend:s,attrs:{shape:i}})}var Khe={kernelName:ui,backendName:"wasm",kernelFunc:fx};function MC(e){let{attrs:{shape:t,value:n,dtype:s},backend:r}=e,a=r.makeOutput(t,s);return r.typedArrayFromHeap(a).fill(n),a}var Zhe={kernelName:Ql,backendName:"wasm",kernelFunc:MC},zC;function Yhe(e){zC=e.wasm.cwrap(di,null,["number","number","number","number","number","number"])}function Jhe(e){let{inputs:t,backend:n}=e,{image:s}=t,r=n.makeOutput(s.shape,s.dtype),a=n.dataIdMap.get(s.dataId).id,o=n.dataIdMap.get(r.dataId).id,[i,l,c,u]=s.shape;return zC(a,i,l,c,u,o),r}var Qhe={kernelName:di,backendName:"wasm",kernelFunc:Jhe,setupFunc:Yhe},efe=En(Oa),tfe=!1,nfe=Xn(Ma,tfe),LC;function sfe(e){LC=e.wasm.cwrap(za,null,["number","number","number","number","number","number","number"])}function rfe(e){let{backend:t,inputs:n,attrs:s}=e,{varianceEpsilon:r}=s,{x:a,mean:o,variance:i,offset:l,scale:c}=n,u=t.dataIdMap.get(a.dataId).id,d=t.dataIdMap.get(o.dataId).id,p=t.dataIdMap.get(i.dataId).id,h=l!=null?t.dataIdMap.get(l.dataId).id:0,f=c!=null?t.dataIdMap.get(c.dataId).id:0,m=t.makeOutput(a.shape,a.dtype);if(v.sizeFromShape(a.shape)===0)return m;let g=t.dataIdMap.get(m.dataId).id;return LC(u,d,p,h,f,r,g),m}var afe={kernelName:za,backendName:"wasm",setupFunc:sfe,kernelFunc:rfe},BC;function ofe(e){BC=e.wasm.cwrap(mo,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function ife(e){let{inputs:t,attrs:n,backend:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:c,dilations:u,dataFormat:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=n,m=N.computeConv2DInfo(r.shape,a.shape,l,u,c,p),g=sp[h];if(g==null)throw new Error(`${h} activation not yet supported for FusedConv2D in the wasm backend.`);let A=s.dataIdMap.get(r.dataId).id,y=s.dataIdMap.get(a.dataId).id,x=m.outChannels,b=0;if(o!=null){let J=s.dataIdMap.get(o.dataId);if(J.shape.length!==1)throw new Error(`FusedConv2D only supports rank-1 bias but got rank ${J.shape.length}.`);if(J.shape[0]!==x)throw new Error(`FusedConv2D bias shape (${J.shape}) does not match the number of output channels (${x})`);b=J.id}let w=m.filterHeight,k=m.filterWidth,S=m.padInfo.top,E=m.padInfo.right,P=m.padInfo.bottom,F=m.padInfo.left,R=m.dilationHeight,_=m.dilationWidth,T=m.strideHeight,M=m.strideWidth,U=m.inChannels,H=m.padInfo.type==="SAME"?1:0,z=m.batchSize,X=m.inHeight,ee=m.inWidth;if(d!=="NHWC")throw new Error(`wasm backend FusedConv2D does not support dataFormat:'${d}'. Please use 'NHWC'.`);let Y=s.makeOutput(m.outShape,"float32"),se=s.dataIdMap.get(Y.dataId).id,ne=i==null?0:s.dataIdMap.get(i.dataId).id;return BC(A,z,X,ee,y,w,k,b,S,E,P,F,H,R,_,T,M,U,x,g,ne,f||0,se),Y}var lfe={kernelName:mo,backendName:"wasm",setupFunc:ofe,kernelFunc:ife},WC;function ufe(e){WC=e.wasm.cwrap(go,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function cfe(e){let{inputs:t,attrs:n,backend:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:c,dilations:u,dataFormat:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=n,m=N.computeConv2DInfo(r.shape,a.shape,l,u,c,p,!0),g=sp[h];if(g==null)throw new Error(`${h} activation not yet supported for FusedDepthwiseConv2D in the wasm backend.`);let A=s.dataIdMap.get(r.dataId).id,y=s.dataIdMap.get(a.dataId).id,x=m.outChannels,b=0;if(o!=null){let J=s.dataIdMap.get(o.dataId);if(J.shape.length!==1)throw new Error(`FusedDepthwiseConv2D only supports rank-1 bias but got rank ${J.shape.length}.`);if(J.shape[0]!==x)throw new Error(`FusedDepthwiseConv2D bias shape (${J.shape}) does not match the number of output channels (${x})`);b=J.id}let w=m.filterHeight,k=m.filterWidth,S=m.padInfo.top,E=m.padInfo.right,P=m.padInfo.bottom,F=m.padInfo.left,R=m.dilationHeight,_=m.dilationWidth,T=m.strideHeight,M=m.strideWidth,U=m.inChannels,H=m.padInfo.type==="SAME"?1:0,z=m.batchSize,X=m.inHeight,ee=m.inWidth;if(d!=="NHWC")throw new Error(`wasm backend FusedDepthwiseConv2D does not support dataFormat:'${d}'. Please use 'NHWC'.`);let Y=s.makeOutput(m.outShape,"float32"),se=s.dataIdMap.get(Y.dataId).id,ne=i==null?0:s.dataIdMap.get(i.dataId).id;return WC(A,z,X,ee,y,w,k,b,S,E,P,F,H,R,_,T,M,U,x,g,ne,f||0,se),Y}var dfe={kernelName:go,backendName:"wasm",setupFunc:ufe,kernelFunc:cfe},VC;function pfe(e){VC=e.wasm.cwrap(hi,null,["number","number","number","number","number","number","array","number"])}function hfe(e){let{backend:t,inputs:n}=e,{params:s,indices:r}=n,[a,o,i,l]=A2.prepareAndValidate(s,r),c=t.makeOutput(a,s.dtype);if(o===0)return c;let u=r.shape,d=u[u.length-1],h=t.dataIdMap.get(s.dataId).id,m=t.dataIdMap.get(r.dataId).id,g=new Uint8Array(new Int32Array(l).buffer),A=t.dataIdMap.get(c.dataId).id;return VC(h,en[s.dtype],m,o,d,i,g,A),c}var ffe={kernelName:hi,backendName:"wasm",setupFunc:pfe,kernelFunc:hfe},UC;function mfe(e){UC=e.wasm.cwrap("Gather",null,["number","number","array","number","number","number","array","number"])}function gfe(e){let{backend:t,inputs:n,attrs:s}=e,{x:r,indices:a}=n,{axis:o,batchDims:i}=s,l=v.parseAxisParam(o,r.shape)[0],c=t.readSync(a.dataId),u=r.shape[l];for(let P=0;P=0,()=>`GatherV2: the index value ${F} is not in [0, ${u-1}]`)}let d=N.segment_util.collectGatherOpShapeInfo(r,a,l,i),p=us({inputs:{x:r},attrs:{shape:[d.batchSize,d.outerSize,d.dimSize,d.sliceSize]},backend:t}),h=v.sizeFromShape(a.shape),f=us({inputs:{x:a},attrs:{shape:[d.batchSize,h/d.batchSize]},backend:t}),m=[d.batchSize,d.outerSize,h/d.batchSize,d.sliceSize],g=t.makeOutput(m,r.dtype);if(v.sizeFromShape(r.shape)===0)return g;let A=p.shape.length-1,x=t.dataIdMap.get(p.dataId).id,w=t.dataIdMap.get(f.dataId).id,k=t.dataIdMap.get(g.dataId).id,S=new Uint8Array(new Int32Array(v.computeStrides(p.shape)).buffer),E=new Uint8Array(new Int32Array(v.computeStrides(m)).buffer);return UC(x,en[r.dtype],S,A,w,d.batchSize,E,k),t.disposeData(p.dataId),t.disposeData(f.dataId),g.shape=d.outputShape,g}var Afe={kernelName:pi,backendName:"wasm",setupFunc:mfe,kernelFunc:gfe},yfe=!1,xfe=Xn(fi,yfe,"bool"),bfe=!1,vfe=Xn(La,bfe,"bool"),GC;function wfe(e){GC=e.wasm.cwrap(mi,null,["number","number","number","number"])}function kfe(e){let{inputs:{x:t},attrs:{alpha:n},backend:s}=e,r=s.dataIdMap.get(t.dataId).id,a=s.makeOutput(t.shape,"float32");if(v.sizeFromShape(t.shape)!==0){let o=s.dataIdMap.get(a.dataId).id;GC(r,en[t.dtype],n,o)}return a}var Ife={kernelName:mi,backendName:"wasm",setupFunc:wfe,kernelFunc:kfe},Sfe=!1,Cfe=Xn(gi,Sfe,"bool"),Tfe=!1,Nfe=Xn(Ai,Tfe,"bool"),Efe=En(Wa),Rfe=!1,$fe=Xn(yi,Rfe,"bool"),HC;function Dfe(e){HC=e.wasm.cwrap(Va,null,["number","number","number","number"])}function _fe(e){let{backend:t,inputs:n,attrs:s}=e,{reductionIndices:r,keepDims:a}=s,{x:o}=n,l=t.dataIdMap.get(o.dataId).id,c=o,{transposed:u,axes:d,originalAxes:p,inputWasTransposed:h}=zo(o,r,t);if(h){let x=t.dataIdMap.get(u.dataId).id;c=u,l=x}let f=c.shape.length;N.assertAxesAreInnerMostDims("max",d,f);let[m,g]=N.computeOutAndReduceShapes(c.shape,d),A=v.sizeFromShape(g),y=t.makeOutput(m,o.dtype);if(v.sizeFromShape(c.shape)!==0){let x=t.dataIdMap.get(y.dataId).id;HC(l,en[o.dtype],A,x)}if(h&&t.disposeData(u.dataId),a){let x=N.expandShapeToKeepDim(y.shape,p);y.shape=x}return y}var Pfe={kernelName:Va,backendName:"wasm",setupFunc:Dfe,kernelFunc:_fe},Ffe=!1,Ofe=Xn(Ua,Ffe),jC;function Mfe(e){jC=e.wasm.cwrap(Ga,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function zfe(e){let{inputs:t,attrs:n,backend:s}=e,r=t.x,a=s.dataIdMap.get(r.dataId).id;v.assert(r.dtype==="float32",()=>`Error in MaxPool: only float32 input is supported. Got ${r.dtype}.`);let{filterSize:o,strides:i,pad:l,dimRoundingMode:c}=n,u=N.computePool2DInfo(r.shape,o,i,1,l,c),d=u.filterHeight,p=u.filterWidth,h=u.padInfo.top,f=u.padInfo.right,m=u.padInfo.bottom,g=u.padInfo.left,A=u.dilationHeight,y=u.dilationWidth,x=u.strideHeight,b=u.strideWidth,w=u.inChannels,k=u.outChannels;if(u.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${u.dataFormat}'. Please use 'channelsLast'.`);let S=s.makeOutput(u.outShape,"float32"),E=s.dataIdMap.get(S.dataId).id;return jC(a,r.shape[0],r.shape[1],r.shape[2],d,p,h,f,m,g,A,y,x,b,w,k,E),S}var Lfe={kernelName:Ga,backendName:"wasm",setupFunc:Mfe,kernelFunc:zfe},qC;function Bfe(e){qC=e.wasm.cwrap(Ha,null,["number, number, number"])}function Wfe(e){let{backend:t,inputs:n,attrs:s}=e,{axis:r,keepDims:a}=s,{x:o}=n,i=t.dataIdMap.get(o.dataId).id,l=i,c=o,{transposed:u,axes:d,originalAxes:p,inputWasTransposed:h}=zo(o,r,t),f=d;if(h){let b=t.dataIdMap.get(u.dataId).id;b!==i&&(c=u,l=b,f=N.getInnerMostAxes(f.length,c.shape.length))}N.assertAxesAreInnerMostDims("mean",f,c.shape.length);let[m,g]=N.computeOutAndReduceShapes(c.shape,f),A=v.sizeFromShape(g),y=c;c.dtype!=="float32"&&(y=ap({backend:t,inputs:{x:c},attrs:{dtype:"float32"}}),l=t.dataIdMap.get(y.dataId).id);let x=t.makeOutput(m,"float32");if(v.sizeFromShape(c.shape)!==0){let b=t.dataIdMap.get(x.dataId).id;qC(l,A,b)}if(h&&t.disposeData(u.dataId),a){let b=N.expandShapeToKeepDim(x.shape,p);x.shape=b}return c.dtype!=="float32"&&t.disposeData(y.dataId),x}var Vfe={kernelName:Ha,backendName:"wasm",setupFunc:Bfe,kernelFunc:Wfe},XC;function Ufe(e){XC=e.wasm.cwrap(ja,null,["number","number","number","number"])}function Gfe(e){let{backend:t,inputs:n,attrs:s}=e,{axis:r,keepDims:a}=s,{x:o}=n,i=t.dataIdMap.get(o.dataId).id,l=i,c=o,{transposed:u,axes:d,originalAxes:p,inputWasTransposed:h}=zo(o,r,t);if(h){let x=t.dataIdMap.get(u.dataId).id;x!==i&&(c=u,l=x)}let f=c.shape.length;N.assertAxesAreInnerMostDims("min",d,f);let[m,g]=N.computeOutAndReduceShapes(c.shape,d),A=v.sizeFromShape(g),y=t.makeOutput(m,c.dtype);if(v.sizeFromShape(c.shape)!==0){let x=t.dataIdMap.get(y.dataId).id;XC(l,en[o.dtype],A,x)}if(h&&t.disposeData(u.dataId),a){let x=N.expandShapeToKeepDim(y.shape,p);y.shape=x}return y}var Hfe={kernelName:ja,backendName:"wasm",setupFunc:Ufe,kernelFunc:Gfe},jfe=!1,qfe=Xn(qa,jfe),mx;(function(e){e[e.reflect=0]="reflect",e[e.symmetric=1]="symmetric"})(mx||(mx={}));var KC;function Xfe(e){KC=e.wasm.cwrap(Xa,null,["number","array","number","number","array","array","number","number"])}function Kfe(e){let{inputs:{x:t},backend:n,attrs:{paddings:s,mode:r}}=e,a=s.map((f,m)=>f[0]+t.shape[m]+f[1]),o=n.dataIdMap.get(t.dataId).id,i=n.makeOutput(a,t.dtype),l=n.dataIdMap.get(i.dataId).id,c=new Uint8Array(new Int32Array(t.shape).buffer),u=s.map(f=>f[0]),d=s.map(f=>f[1]),p=new Uint8Array(new Int32Array(u).buffer),h=new Uint8Array(new Int32Array(d).buffer);return KC(o,c,t.shape.length,en[t.dtype],p,h,mx[r],l),i}var Zfe={kernelName:Xa,backendName:"wasm",kernelFunc:Kfe,setupFunc:Xfe},Yfe=!0,Jfe=Xn(Ka,Yfe),Qfe=En(xi);function gx(e,t){let n=new Int32Array(e.wasm.HEAPU8.buffer,t,4),s=n[0],r=n[1],a=n[2],o=n[3];return e.wasm._free(t),{pSelectedIndices:s,selectedSize:r,pSelectedScores:a,pValidOutputs:o}}var ZC;function eme(e){ZC=e.wasm.cwrap(vi,"number",["number","number","number","number","number"])}function tme(e){let{backend:t,inputs:n,attrs:s}=e,{iouThreshold:r,maxOutputSize:a,scoreThreshold:o}=s,{boxes:i,scores:l}=n,c=t.dataIdMap.get(i.dataId).id,u=t.dataIdMap.get(l.dataId).id,d=ZC(c,u,a,r,o),{pSelectedIndices:p,selectedSize:h,pSelectedScores:f,pValidOutputs:m}=gx(t,d);return t.wasm._free(f),t.wasm._free(m),t.makeOutput([h],"int32",p)}var nme={kernelName:vi,backendName:"wasm",setupFunc:eme,kernelFunc:tme},YC;function sme(e){YC=e.wasm.cwrap(ou,"number",["number","number","number","number","number","bool"])}function rme(e){let{backend:t,inputs:n,attrs:s}=e,{iouThreshold:r,maxOutputSize:a,scoreThreshold:o,padToMaxOutputSize:i}=s,{boxes:l,scores:c}=n,u=t.dataIdMap.get(l.dataId).id,d=t.dataIdMap.get(c.dataId).id,p=YC(u,d,a,r,o,i),{pSelectedIndices:h,selectedSize:f,pSelectedScores:m,pValidOutputs:g}=gx(t,p);t.wasm._free(m);let A=t.makeOutput([f],"int32",h),y=t.makeOutput([],"int32",g);return[A,y]}var ame={kernelName:ou,backendName:"wasm",setupFunc:sme,kernelFunc:rme},JC;function ome(e){JC=e.wasm.cwrap(wi,"number",["number","number","number","number","number","number"])}function ime(e){let{backend:t,inputs:n,attrs:s}=e,{iouThreshold:r,maxOutputSize:a,scoreThreshold:o,softNmsSigma:i}=s,{boxes:l,scores:c}=n,u=t.dataIdMap.get(l.dataId).id,d=t.dataIdMap.get(c.dataId).id,p=JC(u,d,a,r,o,i),{pSelectedIndices:h,selectedSize:f,pSelectedScores:m,pValidOutputs:g}=gx(t,p);t.wasm._free(g);let A=t.makeOutput([f],"int32",h),y=t.makeOutput([f],"float32",m);return[A,y]}var lme={kernelName:wi,backendName:"wasm",setupFunc:ome,kernelFunc:ime},ume=!1,cme=Xn(bi,ume,"bool"),QC;function dme(e){QC=e.wasm.cwrap(Ii,null,["number","number","number","number","number"])}function pme(e){let{inputs:t,backend:n,attrs:s}=e,{indices:r}=t,{depth:a,onValue:o,offValue:i}=s,l=n.makeOutput([...r.shape,a],"int32"),c=n.dataIdMap.get(l.dataId).id,d=n.dataIdMap.get(r.dataId).id;return QC(d,a,o,i,c),l}var hme={kernelName:Ii,backendName:"wasm",setupFunc:dme,kernelFunc:pme};function fme(e){let{inputs:{x:t},backend:n}=e,s=n.makeOutput(t.shape,t.dtype);return n.typedArrayFromHeap(s).fill(1),s}var mme={kernelName:ki,backendName:"wasm",kernelFunc:fme};function gme(e){let{inputs:t,backend:n,attrs:s}=e,{axis:r}=s;if(t.length===1)return fx({inputs:{input:t[0]},backend:n,attrs:{dim:r}});let a=t[0].shape,o=t[0].dtype;t.forEach(u=>{v.assertShapesMatch(a,u.shape,"All tensors passed to stack must have matching shapes"),v.assert(o===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],l=t.map(u=>{let d=fx({inputs:{input:u},backend:n,attrs:{dim:r}});return i.push(d),d}),c=RC({inputs:l,backend:n,attrs:{axis:r}});return i.forEach(u=>n.disposeData(u.dataId)),c}var Ame={kernelName:Si,backendName:"wasm",kernelFunc:gme},e6;function yme(e){e6=e.wasm.cwrap(Za,null,["number","array","number","number","array","array","number","number"])}function xme(e){let{inputs:{x:t},backend:n,attrs:{paddings:s,constantValue:r}}=e,a=s.map((m,g)=>m[0]+t.shape[g]+m[1]);if(v.sizeFromShape(t.shape)===0)return MC({backend:n,attrs:{shape:a,value:r,dtype:t.dtype}});let o=n.dataIdMap.get(t.dataId).id,i=n.makeOutput(a,t.dtype),c=n.dataIdMap.get(i.dataId).id,u=new Uint8Array(new Int32Array(t.shape).buffer),d=s.map(m=>m[0]),p=s.map(m=>m[1]),h=new Uint8Array(new Int32Array(d).buffer),f=new Uint8Array(new Int32Array(p).buffer);return e6(o,u,t.shape.length,en[t.dtype],h,f,r,c),i}var t6={kernelName:Za,backendName:"wasm",kernelFunc:xme,setupFunc:yme},bme=!1,vme=Xn(Ya,bme),n6;function wme(e){n6=e.wasm.cwrap(Ja,null,["number","number","number"])}function kme(e){let{inputs:t,backend:n}=e,{x:s,alpha:r}=t,a=n.dataIdMap.get(s.dataId).id,o=n.dataIdMap.get(r.dataId).id,i=a,l=s,c=l;l.dtype!=="float32"&&(c=ap({backend:n,inputs:{x:s},attrs:{dtype:"float32"}}),i=n.dataIdMap.get(c.dataId).id);let u=n.makeOutput(s.shape,"float32"),d=n.dataIdMap.get(u.dataId).id;return n6(i,o,d),l.dtype!=="float32"&&n.disposeData(c.dataId),u}var Ime={kernelName:Ja,backendName:"wasm",setupFunc:wme,kernelFunc:kme},s6;function Sme(e){s6=e.wasm.cwrap(Ci,null,["number","number","number","number"])}function Cme(e){let{backend:t,inputs:n,attrs:s}=e,{axis:r,keepDims:a}=s,{x:o}=n,i=t.dataIdMap.get(o.dataId).id,l=i,c=o,{transposed:u,axes:d,originalAxes:p,inputWasTransposed:h}=zo(o,r,t),f=d;if(h){let x=t.dataIdMap.get(u.dataId).id;x!==i&&(c=u,l=x,f=N.getInnerMostAxes(f.length,c.shape.length))}N.assertAxesAreInnerMostDims("prod",f,c.shape.length);let[m,g]=N.computeOutAndReduceShapes(c.shape,f),A=v.sizeFromShape(g),y=t.makeOutput(m,c.dtype);if(v.sizeFromShape(c.shape)!==0){let x=t.dataIdMap.get(y.dataId).id;s6(l,A,en[y.dtype],x)}if(h&&t.disposeData(u.dataId),a){let x=N.expandShapeToKeepDim(y.shape,p);y.shape=x}return y}var Tme={kernelName:Ci,backendName:"wasm",setupFunc:Sme,kernelFunc:Cme},Nme=e=>{let{backend:t,attrs:n}=e,{start:s,stop:r,step:a,dtype:o}=n,i=Sy(s,r,a,o),l=t.makeOutput([i.length],o);return t.typedArrayFromHeap(l).set(i),l},Eme={kernelName:iu,backendName:"wasm",kernelFunc:Nme},Rme=!0,$me=Xn(_a,Rme),Dme=En(Qa),_me=En(to),r6;function Pme(e){r6=e.wasm.cwrap(eo,null,["number","number","number","number","number","number","number","number","number","number"])}function Fme(e){let{backend:t,inputs:n,attrs:s}=e,{images:r}=n,{alignCorners:a,halfPixelCenters:o,size:i}=s,[l,c]=i,[u,d,p,h]=r.shape,f=[u,l,c,h],m=t.dataIdMap.get(r.dataId),g;m.dtype!=="float32"&&(g=ap({backend:t,inputs:{x:r},attrs:{dtype:"float32"}}),m=t.dataIdMap.get(g.dataId));let A=m.id,y=t.makeOutput(f,"float32");if(v.sizeFromShape(r.shape)===0)return y;let x=t.dataIdMap.get(y.dataId).id;return r6(A,u,d,p,h,l,c,a?1:0,o?1:0,x),g!=null&&t.disposeData(g.dataId),y}var Ome={kernelName:eo,backendName:"wasm",setupFunc:Pme,kernelFunc:Fme},a6;function Mme(e){a6=e.wasm.cwrap(Ni,null,["number","array","number","array","number","number"])}function zme(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{dims:a}=s,o=v.parseAxisParam(a,r.shape);if(r.shape.length===0)return Mm({inputs:{x:r},backend:n});let i=n.makeOutput(r.shape,r.dtype),l=n.dataIdMap.get(r.dataId).id,c=n.dataIdMap.get(i.dataId).id,u=new Uint8Array(new Int32Array(o).buffer),d=new Uint8Array(new Int32Array(r.shape).buffer);a6(l,u,o.length,d,r.shape.length,c);let p=us({inputs:{x:i},attrs:{shape:r.shape},backend:n});return n.disposeData(i.dataId),p}var Lme={kernelName:Ni,backendName:"wasm",kernelFunc:zme,setupFunc:Mme},o6;function Bme(e){o6=e.wasm.cwrap(Vi,null,["number","number","number","number","number","number","number","number","array","number","number"])}function Wme(e){let{inputs:t,backend:n,attrs:s}=e,{image:r}=t,{radians:a,fillValue:o,center:i}=s,l=n.makeOutput(r.shape,r.dtype),c=n.dataIdMap.get(r.dataId).id,u=n.dataIdMap.get(l.dataId).id,[d,p,h,f]=r.shape,[m,g]=N.getImageCenter(i,p,h),A=o===0,y=255,x=typeof o=="number"?[o,o,o,A?0:y]:[...o,y],b=new Uint8Array(new Int32Array(x).buffer);return o6(c,d,p,h,f,a,m,g,b,x.length,u),l}var Vme={kernelName:Vi,backendName:"wasm",kernelFunc:Wme,setupFunc:Bme},Ume=En(Ei),Gme=En(no),i6;function Hme(e){i6=e.wasm.cwrap(Ri,null,["number","number","number","number","number","number","array","number","number"])}function jme(e){let{backend:t,inputs:n,attrs:s}=e,{indices:r,updates:a}=n,{shape:o}=s,i=t.makeOutput(o,a.dtype);if(v.sizeFromShape(o)===0)return i;let{sliceRank:l,numUpdates:c,sliceSize:u,strides:d,outputSize:p}=y2.calculateShapes(a,r,o),f=t.dataIdMap.get(r.dataId).id,g=t.dataIdMap.get(a.dataId).id,A=new Uint8Array(new Int32Array(d).buffer),y=t.dataIdMap.get(i.dataId).id;return i6(f,g,en[a.dtype],l,c,u,A,p,y),i}var qme={kernelName:Ri,backendName:"wasm",setupFunc:Hme,kernelFunc:jme},l6;function Xme(e){l6=e.wasm.cwrap("SelectV2",null,["number","number","number","number","number"])}function Kme(e){let{inputs:t,backend:n}=e,{condition:s,t:r,e:a}=t,o=n.dataIdMap.get(s.dataId).id,i=n.dataIdMap.get(r.dataId).id,l=n.dataIdMap.get(a.dataId).id,c=n.makeOutput(r.shape,r.dtype),u=n.dataIdMap.get(c.dataId).id,d=s.shape.length,p=r.shape.length,h=d===0||d>1||p===1?1:v.sizeFromShape(r.shape.slice(1));return l6(o,i,l,h,u),c}var Zme={kernelName:$i,backendName:"wasm",kernelFunc:Kme,setupFunc:Xme},u6;function Yme(e){u6=e.wasm.cwrap(ro,null,["number","number"])}function Jme(e){let{backend:t,inputs:{x:n}}=e,s=t.dataIdMap.get(n.dataId).id,r=t.makeOutput(n.shape,n.dtype),a=t.dataIdMap.get(r.dataId).id;return v.sizeFromShape(r.shape)===0||u6(s,a),r}var Qme={kernelName:"Sigmoid",backendName:"wasm",setupFunc:Yme,kernelFunc:Jme},e0e=En(so),c6;function t0e(e){c6=e.wasm.cwrap(io,null,["number","number","number","number"])}function n0e(e){let{backend:t,inputs:{logits:n},attrs:{dim:s}}=e,r=t.dataIdMap.get(n.dataId).id,a=t.makeOutput(n.shape,n.dtype),o=t.dataIdMap.get(a.dataId).id,i=n.shape[s],l=v.sizeFromShape(n.shape)/i;return v.sizeFromShape(a.shape)===0||c6(r,o,i,l),a}var s0e={kernelName:io,backendName:"wasm",setupFunc:t0e,kernelFunc:n0e};function r0e(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,paddings:o}=s,i=v.sizeFromShape(a),l=[[0,0]];l.push(...o);for(let k=1+a.length;k{let p=[...u];p[i]=d;let h=rp({inputs:{x:r},attrs:{begin:c,size:p},backend:s});return c[i]+=d,h})}var i0e={kernelName:Fi,backendName:"wasm",kernelFunc:o0e},l0e=En(ao),u0e=En(hu),c0e=!0,d0e=Xn(lo,c0e),d6;function p0e(e){d6=e.wasm.cwrap(ho,null,["number","number","number","number"])}function h0e(e){let{backend:t,inputs:n,attrs:s}=e,{alpha:r}=s,{x:a}=n,o=t.dataIdMap.get(a.dataId).id,i=t.makeOutput(a.shape,a.dtype),l=t.dataIdMap.get(i.dataId).id;return d6(o,r,en[a.dtype],l),i}var f0e={kernelName:ho,backendName:"wasm",setupFunc:p0e,kernelFunc:h0e},p6;function m0e(e){p6=e.wasm.cwrap(Oi,null,["number","array","number","array","array","array","array","array","number","number"])}function g0e(e){let{backend:t,inputs:n,attrs:s}=e,{x:r}=n,{begin:a,end:o,strides:i}=s;i==null&&(i=new Array(a.length));let{beginMask:l,endMask:c,ellipsisMask:u,newAxisMask:d,shrinkAxisMask:p}=s,h=N.slice_util.maskToAxes(u);if(h.length>1)throw new Error("Multiple ellipses in slice is not allowed.");if(u!==0&&d!==0)throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");if(u!==0&&p!==0)throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");let f=r.shape.length-a.length,m=N.slice_util.maskToAxes(d),g=r.shape.slice();m.forEach(R=>{a[R]=0,o[R]=1,g.splice(R,0,1)});let A=us({inputs:{x:r},attrs:{shape:g},backend:t}),{begin:y,end:x,strides:b}=N.slice_util.getNormalizedAxes(A.shape,h,f,a,o,i,l,c,u);a=y,o=x,i=b;let w=N.slice_util.maskToAxes(p);w.forEach(R=>{o[R]=a[R]+1,i[R]=1});let k=N.slice_util.computeOutShape(a,o,i),S=k.filter((R,_)=>w.indexOf(_)===-1);if(i.every(R=>R===1)){let R=rp({inputs:{x:A},attrs:{begin:a,size:k},backend:t});t.disposeData(A.dataId);let _=us({inputs:{x:R},attrs:{shape:S},backend:t});return t.disposeData(R.dataId),_}let P=t.makeOutput(S,"float32");if(!S.some(R=>R===0)){let R=t.dataIdMap.get(A.dataId).id,_=new Uint8Array(new Int32Array(v.computeStrides(A.shape)).buffer),T=new Uint8Array(new Int32Array(a).buffer),M=new Uint8Array(new Int32Array(o).buffer),U=new Uint8Array(new Int32Array(i).buffer),H=new Uint8Array(new Int32Array(S).buffer),z=new Uint8Array(new Int32Array(v.computeStrides(S)).buffer),X=t.dataIdMap.get(P.dataId).id;p6(R,_,A.shape.length,T,M,U,H,z,S.length,X)}t.disposeData(A.dataId);let F=us({inputs:{x:P},attrs:{shape:S},backend:t});return t.disposeData(P.dataId),F}var A0e={kernelName:Oi,backendName:"wasm",setupFunc:m0e,kernelFunc:g0e},y0e=!0,x0e=Xn(uo,y0e),h6;function b0e(e){h6=e.wasm.cwrap(oo,null,["number","number","number","number"])}function v0e(e){let{backend:t,inputs:n,attrs:s}=e,{axis:r,keepDims:a}=s,{x:o}=n,i=t.dataIdMap.get(o.dataId).id,l=i,c=o,{transposed:u,axes:d,originalAxes:p,inputWasTransposed:h}=zo(o,r,t),f=d;if(h){let x=t.dataIdMap.get(u.dataId).id;x!==i&&(c=u,l=x,f=N.getInnerMostAxes(f.length,c.shape.length))}N.assertAxesAreInnerMostDims("sum",f,c.shape.length);let[m,g]=N.computeOutAndReduceShapes(c.shape,f),A=v.sizeFromShape(g),y=t.makeOutput(m,c.dtype);if(v.sizeFromShape(c.shape)!==0){let x=t.dataIdMap.get(y.dataId).id;h6(l,A,en[y.dtype],x)}if(h&&t.disposeData(u.dataId),a){let x=N.expandShapeToKeepDim(y.shape,p);y.shape=x}return y}var w0e={kernelName:oo,backendName:"wasm",setupFunc:b0e,kernelFunc:v0e},k0e=En(Mi),I0e=En(co),f6;function S0e(e){f6=e.wasm.cwrap(qr,null,["number","array","number","array","number","number"])}function C0e(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,a=n.dataIdMap.get(r.dataId).id,{reps:o}=s,i=new Array(r.shape.length);for(let p=0;p{let{x:s}=e,{k:r,sorted:a}=n,o=t.dataIdMap.get(s.dataId).id,i=new Uint8Array(new Int32Array(s.shape).buffer),l=s.shape.slice();l[l.length-1]=r;let c=t.makeOutput(l,s.dtype),u=t.dataIdMap.get(c.dataId).id,d=t.makeOutput(l,"int32"),p=t.dataIdMap.get(d.dataId).id;return m6(o,i,s.shape.length,en[s.dtype],r,a,u,p),[c,d]},R0e={kernelName:zi,backendName:"wasm",setupFunc:N0e,kernelFunc:E0e},g6;function $0e(e){g6=e.wasm.cwrap(Li,null,["number","number","bool","number","number","number","number","number","number","array","number","number","number","number","number"])}function D0e(e){let{backend:t,inputs:n,attrs:s}=e,{image:r,transforms:a}=n,{interpolation:o,fillMode:i,fillValue:l,outputShape:c}=s,[u,d,p,h]=r.shape,[f,m]=c!=null?c:[d,p],g=[u,f,m,h],A=new Uint8Array(new Int32Array(v.computeStrides(r.shape)).buffer),y=t.makeOutput(g,r.dtype),x=t.dataIdMap.get(y.dataId).id,w=t.dataIdMap.get(r.dataId).id,S=t.dataIdMap.get(a.dataId).id,E=o==="nearest"?1:2,P;switch(i){case"constant":P=1;break;case"reflect":P=2;break;case"wrap":P=3;break;case"nearest":P=4;break;default:P=1;break}return g6(w,S,a.shape[0]>1,u,f,m,h,p,d,A,r.shape.length-1,E,P,l,x),y}var _0e={kernelName:Li,backendName:"wasm",setupFunc:$0e,kernelFunc:D0e};function P0e(e){let{inputs:t,backend:n,attrs:s}=e,{value:r}=t,{axis:a}=s;a<0&&(a+=r.shape.length);let o=r.shape[a],i=r.shape.length,l=new Array(i-1),c=0;for(let h=0;h({dataId:h,dtype:f,shape:l}))}var F0e={kernelName:Bi,backendName:"wasm",kernelFunc:P0e};function O0e(e){let{inputs:{x:t},backend:n}=e,s=n.makeOutput(t.shape,t.dtype);return n.typedArrayFromHeap(s).fill(0),s}var M0e={kernelName:Wi,backendName:"wasm",kernelFunc:O0e},z0e=[Bpe,Vpe,Hpe,Qpe,nhe,ahe,lhe,phe,yhe,xhe,bhe,khe,Ihe,The,Rhe,$he,Dhe,Fhe,zhe,Whe,Ghe,Hhe,qhe,Xhe,Khe,Zhe,Qhe,efe,nfe,Lpe,afe,lfe,dfe,ffe,Afe,xfe,vfe,jpe,Ife,Cfe,Nfe,Efe,$fe,Pfe,Ofe,Lfe,Vfe,Hfe,qfe,Zfe,Jfe,Qfe,nme,ame,lme,cme,hme,mme,Ame,t6,vme,Ime,Tme,Eme,$me,Dme,_me,uhe,Ome,Lme,Vme,Gme,Ume,qme,Zme,Qme,e0e,ghe,s0e,a0e,i0e,l0e,u0e,d0e,f0e,A0e,x0e,w0e,k0e,I0e,T0e,R0e,_0e,Zpe,F0e,M0e];for(let e of z0e)Kr(e);var Ax=K();Ax.registerFlag("WASM_HAS_SIMD_SUPPORT",async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,9,1,7,0,65,0,253,15,26,11])));Ax.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT",async()=>{if(Ax.get("IS_NODE"))return!1;try{return new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch(e){return!1}});var L0e='var Module={};function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(" ");console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:text,threadId:Module["_pthread_self"]()})}var err=threadPrintErr;this.alert=threadAlert;Module["instantiateWasm"]=function(info,receiveInstance){var instance=new WebAssembly.Instance(Module["wasmModule"],info);Module["wasmModule"]=null;receiveInstance(instance);return instance.exports};function moduleLoaded(){}this.onmessage=function(e){try{if(e.data.cmd==="load"){Module["wasmModule"]=e.data.wasmModule;Module["wasmMemory"]=e.data.wasmMemory;Module["buffer"]=Module["wasmMemory"].buffer;Module["ENVIRONMENT_IS_PTHREAD"]=true;if(typeof e.data.urlOrBlob==="string"){importScripts(e.data.urlOrBlob)}else{var objectUrl=URL.createObjectURL(e.data.urlOrBlob);importScripts(objectUrl);URL.revokeObjectURL(objectUrl)}WasmBackendModuleThreadedSimd(Module).then(function(instance){Module=instance;moduleLoaded()})}else if(e.data.cmd==="objectTransfer"){Module["PThread"].receiveObjectTransfer(e.data)}else if(e.data.cmd==="run"){Module["__performance_now_clock_drift"]=performance.now()-e.data.time;Module["__emscripten_thread_init"](e.data.threadInfoStruct,0,0);var max=e.data.stackBase;var top=e.data.stackBase+e.data.stackSize;Module["establishStackSpace"](top,max);Module["_emscripten_tls_init"]();Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].setThreadStatus(Module["_pthread_self"](),1);try{var result=Module["invokeEntryPoint"](e.data.start_routine,e.data.arg);if(!Module["getNoExitRuntime"]())Module["PThread"].threadExit(result)}catch(ex){if(ex==="Canceled!"){Module["PThread"].threadCancel()}else if(ex!="unwind"){if(ex instanceof Module["ExitStatus"]){if(Module["getNoExitRuntime"]()){}else{Module["PThread"].threadExit(ex.status)}}else{Module["PThread"].threadExit(-2);throw ex}}}}else if(e.data.cmd==="cancel"){if(Module["_pthread_self"]()){Module["PThread"].threadCancel()}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processThreadQueue"){if(Module["_pthread_self"]()){Module["_emscripten_current_thread_process_queued_calls"]()}}else{err("worker.js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){err("worker.js onmessage() captured an uncaught exception: "+ex);if(ex&&ex.stack)err(ex.stack);throw ex}};if(typeof process==="object"&&typeof process.versions==="object"&&typeof process.versions.node==="string"){self={location:{href:__filename}};var onmessage=this.onmessage;var nodeWorkerThreads=require("worker_threads");global.Worker=nodeWorkerThreads.Worker;var parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",function(data){onmessage({data:data})});var nodeFS=require("fs");var nodeRead=function(filename){return nodeFS.readFileSync(filename,"utf8")};function globalEval(x){global.require=require;global.Module=Module;eval.call(null,x)}importScripts=function(f){globalEval(nodeRead(f))};postMessage=function(msg){parentPort.postMessage(msg)};if(typeof performance==="undefined"){performance={now:function(){return Date.now()}}}}',A6=Qo(BN()),B0e=Qo(WN()),y6=class extends Ll{constructor(e){super();this.wasm=e,this.dataIdNextNumber=1,this.wasm.tfjs.initWithThreadsCount(v6),xx=this.wasm.tfjs.getThreadsCount(),this.dataIdMap=new Dc(this,ss())}write(e,t,n){let s={id:this.dataIdNextNumber++};return this.move(s,e,t,n,1),s}numDataIds(){return this.dataIdMap.numDataIds()}async time(e){let t=v.now();return e(),{kernelMs:v.now()-t}}move(e,t,n,s,r){let a=this.dataIdNextNumber++;if(s==="string"){let c=t;this.dataIdMap.set(e,{id:a,stringBytes:c,shape:n,dtype:s,memoryOffset:null,refCount:r});return}let o=v.sizeFromShape(n),i=o*v.bytesPerElement(s),l=this.wasm._malloc(i);this.dataIdMap.set(e,{id:a,memoryOffset:l,shape:n,dtype:s,refCount:r}),this.wasm.tfjs.registerTensor(a,o,l),t!=null&&this.wasm.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,i),l)}async read(e){return this.readSync(e)}readSync(e){let{memoryOffset:t,dtype:n,shape:s,stringBytes:r}=this.dataIdMap.get(e);if(n==="string")return r;let a=this.wasm.HEAPU8.slice(t,t+v.sizeFromShape(s)*v.bytesPerElement(n));return U0e(a.buffer,n)}disposeData(e,t=!1){if(this.dataIdMap.has(e)){let n=this.dataIdMap.get(e);if(n.refCount--,!t&&n.refCount>0)return!1;this.wasm._free(n.memoryOffset),this.wasm.tfjs.disposeData(n.id),this.dataIdMap.delete(e)}return!0}refCount(e){return this.dataIdMap.has(e)?this.dataIdMap.get(e).refCount:0}incRef(e){let t=this.dataIdMap.get(e);t!=null&&t.refCount++}floatPrecision(){return 32}getMemoryOffset(e){return this.dataIdMap.get(e).memoryOffset}dispose(){this.wasm.tfjs.dispose(),"PThread"in this.wasm&&this.wasm.PThread.terminateAllThreads(),this.wasm=null}memory(){return{unreliable:!1}}makeOutput(e,t,n){let s;if(n==null)s=this.write(null,e,t);else{let r=this.dataIdNextNumber++;s={id:r},this.dataIdMap.set(s,{id:r,memoryOffset:n,shape:e,dtype:t,refCount:1});let a=v.sizeFromShape(e);this.wasm.tfjs.registerTensor(r,a,n)}return{dataId:s,shape:e,dtype:t}}typedArrayFromHeap({shape:e,dtype:t,dataId:n}){let s=this.wasm.HEAPU8.buffer,{memoryOffset:r}=this.dataIdMap.get(n),a=v.sizeFromShape(e);switch(t){case"float32":return new Float32Array(s,r,a);case"int32":return new Int32Array(s,r,a);case"bool":return new Uint8Array(s,r,a);default:throw new Error(`Unknown dtype ${t}`)}}};function W0e(e){return(t,n)=>(v.fetch(e,{credentials:"same-origin"}).then(s=>{s.ok||t.env.a(`failed to load wasm binary file at '${e}'`),s.arrayBuffer().then(r=>{WebAssembly.instantiate(r,t).then(a=>{n(a.instance,a.module)})})}),{})}function x6(e,t,n){if(zm!=null)return zm;let s="tfjs-backend-wasm.wasm";return e&&t?s="tfjs-backend-wasm-threaded-simd.wasm":e&&(s="tfjs-backend-wasm-simd.wasm"),ip!=null&&ip[s]!=null?ip[s]:n+s}async function V0e(){let[e,t]=await Promise.all([K().getAsync("WASM_HAS_SIMD_SUPPORT"),K().getAsync("WASM_HAS_MULTITHREAD_SUPPORT")]);return new Promise((n,s)=>{let r={};r.locateFile=(i,l)=>{if(i.endsWith(".worker.js")){let c=L0e,u=new Blob([c],{type:"application/javascript"});return URL.createObjectURL(u)}return i.endsWith(".wasm")?x6(e,t,op!=null?op:l):l+i},yx&&(r.instantiateWasm=W0e(x6(e,t,op!=null?op:"")));let a=!1;r.onAbort=()=>{if(a||lp)return;lp=!0,s({message:"Make sure the server can serve the `.wasm` file relative to the bundled js file. For more details see https://github.com/tensorflow/tfjs/blob/master/tfjs-backend-wasm/README.md#using-bundlers"})};let o;t&&e&&zm==null?(r.mainScriptUrlOrBlob=new Blob(["var WasmBackendModuleThreadedSimd = "+A6.default.toString()],{type:"text/javascript"}),o=(0,A6.default)(r)):o=(0,B0e.default)(r),o.then(i=>{a=!0,lp=!1;let l=null;i.tfjs={init:i.cwrap("init",null,[]),initWithThreadsCount:i.cwrap("init_with_threads_count",null,["number"]),getThreadsCount:i.cwrap("get_threads_count","number",[]),registerTensor:i.cwrap("register_tensor",null,["number","number","number"]),disposeData:i.cwrap("dispose_data",l,["number"]),dispose:i.cwrap("dispose",l,[])},n({wasm:i})})})}function U0e(e,t){switch(t){case"float32":return new Float32Array(e);case"int32":return new Int32Array(e);case"bool":return new Uint8Array(e);default:throw new Error(`Unknown dtype ${t}`)}}var G0e=["tfjs-backend-wasm.wasm","tfjs-backend-wasm-simd.wasm","tfjs-backend-wasm-threaded-simd.wasm"],zm=null,op=null,ip={},lp=!1,yx=!1;function H0e(e,t=!1){if(I2("setWasmPath has been deprecated in favor of setWasmPaths and will be removed in a future release."),lp)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPath()` before you call `tf.setBackend()` or `tf.ready()`");zm=e,yx=t}function b6(e,t=!1){if(lp)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPaths()` before you call `tf.setBackend()` or `tf.ready()`");if(typeof e=="string")op=e;else{ip=e;let n=G0e.filter(s=>ip[s]==null);if(n.length>0)throw new Error(`There were no entries found for the following binaries: ${n.join(",")}. Please either call setWasmPaths with a map providing a path for each binary, or with a string indicating the directory where all the binaries can be found.`)}yx=t}var v6=-1,xx=-1;function j0e(e){v6=e}function q0e(){if(xx===-1)throw new Error("WASM backend not initialized.");return xx}var X0e="0.0.0",K0e=2;Ki("wasm",async()=>{let{wasm:e}=await V0e();return new y6(e)},K0e);var Lo="3.10.0-20211022",w6={tfjs:Lo,"tfjs-core":Lo,"tfjs-data":Lo,"tfjs-layers":Lo,"tfjs-converter":Lo,"tfjs-backend-cpu":Lo,"tfjs-backend-webgl":Lo,"tfjs-backend-wasm":Lo},up=w6["tfjs-core"];var k6=` + `}getUserCode(){return this.makeFromPixelsSource()}setPipeline(e){this.pipeline=e}setUniform(e,t){if(!this.uniform){let n=e.createBuffer({size:t.length*4,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});this.uniform=n}!t||t.length===this.lastUniformData.length&&t.every((n,s)=>n===this.lastUniformData[s])||(e.queue.writeBuffer(this.uniform,0,new Uint32Array(t)),this.lastUniformData=t)}makeInputTexture(e,t,n){return(!this.inputTexture||this.lastPixelSize.width!==t||this.lastPixelSize.height!==n)&&(this.inputTexture&&this.inputTexture.destroy(),this.inputTexture=e.createTexture({size:[t,n],format:"rgba8unorm",usage:GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),this.lastPixelSize.width=t,this.lastPixelSize.height=n),this.inputTexture}dispose(){this.disposed||(this.uniform&&this.uniform.destroy(),this.inputTexture&&this.inputTexture.destroy(),this.disposed=!0)}getLayout(e){return this.layout===null&&(this.layout=this.createTextureLayout(e)),this.layout}createTextureLayout(e){let t=[];t.push({binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}}),t.push({binding:1,visibility:GPUShaderStage.COMPUTE,texture:{}}),t.push({binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{}});let n=e.createBindGroupLayout({entries:t}),s=e.createPipelineLayout({bindGroupLayouts:[n]});return{bindGroupLayout:n,pipelineLayout:s}}},Fpe=class extends yC{constructor(){super(...arguments);this.layout=null,this.useImport=!0}getUserCode(){return this.makeFromPixelsSource()}getLayout(e){return this.layout===null&&(this.layout=this.createTextureImportLayout(e)),this.layout}createTextureImportLayout(e){let t=[];t.push({binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}}),t.push({binding:1,visibility:GPUShaderStage.COMPUTE,externalTexture:{}}),t.push({binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{}});let n=e.createBindGroupLayout({entries:t}),s=e.createPipelineLayout({bindGroupLayouts:[n]});return{bindGroupLayout:n,pipelineLayout:s}}},Ope=K().getNumber("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD"),xC=class extends Ll{constructor(e,t=!1){super();if(this.commandQueueOwnedIds=new WeakSet,this.tensorDisposalQueue=[],this.uniformDisposalQueue=[],this.disposed=!1,this.uploadWaitMs=0,this.downloadWaitMs=0,this.dispatchNumberInEncoder=0,!rx())throw new Error("WebGPU is not supported on this device");this.layoutCache={},this.pipelineCache={},this.device=e,this.queue=e.queue,this.currentCommandEncoder=null,this.currentComputePass=null,this.supportTimeQuery=t,this.bufferManager=new Ppe(this.device),this.tensorMap=new Dc(this,ss()),this.supportTimeQuery&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:2})),K().getBool("WEBGPU_USE_PROFILE_TOOL")&&(this.dummyCanvas=document.createElement("canvas"),this.dummyCanvas.width=1,this.dummyCanvas.height=1,this.dummyContext=this.dummyCanvas.getContext("webgpu"),this.dummyContext.configure({device:e,format:"bgra8unorm"}),document.body.appendChild(this.dummyCanvas))}nextDataId(){return xC.nextDataId++}floatPrecision(){return 32}defaultGpuBufferUsage(){return GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST}flushDisposalQueue(){this.tensorDisposalQueue.forEach(e=>{this.maybeReleaseBuffer(e),this.tensorMap.delete(e)}),this.uniformDisposalQueue.forEach(e=>this.bufferManager.releaseBuffer(e.buffer,e.byteSize,e.usage)),this.tensorDisposalQueue=[],this.uniformDisposalQueue=[]}disposeData(e,t=!1){if(this.tensorMap.has(e)){let n=this.tensorMap.get(e);if(n.refCount--,!t&&n.refCount>0)return!1;if(this.commandQueueOwnedIds.has(e))return this.tensorDisposalQueue.push(e),!1;this.maybeReleaseBuffer(e);let{complexTensorInfos:s}=this.tensorMap.get(e);s!=null&&(this.disposeData(s.real.dataId,!0),this.disposeData(s.imag.dataId,!0)),this.tensorMap.delete(e)}return!0}memory(){return{numBytesInGPU:this.bufferManager.numBytesUsed,numBytesAllocatedInGPU:this.bufferManager.numBytesAllocated,unreliable:!1}}getBufferManager(){return this.bufferManager}acquireBuffer(e,t=this.defaultGpuBufferUsage()){return this.bufferManager.acquireBuffer(e,t)}maybeReleaseBuffer(e){let t=this.tensorMap.get(e);t!=null&&t.bufferInfo.buffer!=null&&(this.bufferManager.releaseBuffer(t.bufferInfo.buffer,t.bufferInfo.byteSize,t.bufferInfo.usage),t.bufferInfo.buffer=null)}refCount(e){return this.tensorMap.has(e)?this.tensorMap.get(e).refCount:0}incRef(e){let t=this.tensorMap.get(e);t.refCount++}decRef(e){if(this.tensorMap.has(e)){let t=this.tensorMap.get(e);t.refCount--}}write(e,t,n){if(n==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let s={id:this.nextDataId()},r=v.sizeFromShape(t)*sx(n);return n==="bool"&&e instanceof Uint8Array&&(e=Int32Array.from(e)),this.tensorMap.set(s,{dtype:n,values:e,bufferInfo:{byteSize:r,usage:this.defaultGpuBufferUsage()},refCount:1}),s}move(e,t,n,s,r){if(s==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let a=v.sizeFromShape(n)*sx(s);this.tensorMap.set(e,{dtype:s,values:t,bufferInfo:{byteSize:a,usage:this.defaultGpuBufferUsage()},refCount:r})}submitQueue(){this.ensureComputePassEnded(),this.queue.submit([this.currentCommandEncoder.finish()]),this.currentCommandEncoder=null,this.dispatchNumberInEncoder=0,this.commandQueueOwnedIds=new WeakSet,this.flushDisposalQueue()}getBuffer(e){return this.uploadToGPU(e),this.tensorMap.get(e).bufferInfo.buffer}getFromPixelsProgram(e){switch(e){case"copyExternal":return this.fromPixelProgram||(this.fromPixelProgram=new yC),this.fromPixelProgram;case"import":return this.fromPixelImportProgram||(this.fromPixelImportProgram=new Fpe),this.fromPixelImportProgram;default:v.assert(!1,()=>"Unsupported fromPixels shape");return}}ensureCommandEncoderReady(){this.currentCommandEncoder||(this.currentCommandEncoder=this.device.createCommandEncoder())}ensureComputePassEnded(){this.currentComputePass&&(this.currentComputePass.endPass(),this.currentComputePass=null)}getComputePass(){return this.currentComputePass||(this.currentComputePass=this.currentCommandEncoder.beginComputePass()),this.currentComputePass}async getBufferData(e){if(e.values!=null)return e.values;let t=this.acquireBuffer(e.bufferInfo.byteSize,GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ);this.ensureCommandEncoderReady(),this.ensureComputePassEnded(),this.currentCommandEncoder.copyBufferToBuffer(e.bufferInfo.buffer,0,t,0,e.bufferInfo.byteSize),this.submitQueue(),await t.mapAsync(GPUMapMode.READ);let n=t.getMappedRange().slice(0);return t.unmap(),t!=null&&this.bufferManager.releaseBuffer(t,e.bufferInfo.byteSize,GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ),K().getBool("WEBGPU_USE_PROFILE_TOOL")&&(v.assert(this.dummyContext!==void 0,()=>"Fail to get context for profiling tool"),this.dummyContext.getCurrentTexture()),n}convertAndCacheOnCPU(e,t){let n=this.tensorMap.get(e);return this.maybeReleaseBuffer(e),n.values=t,n.values}readSync(e){let t=this.tensorMap.get(e),{values:n}=t;if(n==null)throw new Error("WebGPU readSync is only available for CPU-resident tensors.");return n}async read(e){if(!this.tensorMap.has(e))throw new Error(`Tensor ${e} was not registered!`);let t=this.tensorMap.get(e),{values:n}=t;if(n!=null)return this.convertAndCacheOnCPU(e,n);let s;if(t.dtype==="complex64"){let r=await Promise.all([this.read(t.complexTensorInfos.real.dataId),this.read(t.complexTensorInfos.imag.dataId)]),a=r[0],o=r[1];s=N.mergeRealAndImagArrays(a,o)}else{let r=await this.getBufferData(t);s=B4(r,t.dtype)}return this.convertAndCacheOnCPU(e,s),s}bufferSync(e){let t=this.readSync(e.dataId),n=t;if(e.dtype==="string")try{n=t.map(s=>v.decodeString(s))}catch(s){throw new Error("Failed to decode encoded string bytes into utf-8")}return Le(e.shape,e.dtype,n)}async time(e){let t=this.activeTimers,n=[],s=!1;this.programTimersStack==null?(this.programTimersStack=n,s=!0):this.activeTimers.push(n),this.activeTimers=n,e();let r=v.flatten(this.activeTimers.map(l=>l.query)).filter(l=>l!=null),a=v.flatten(this.activeTimers.map(l=>l.name)).filter(l=>l!=null);this.activeTimers=t,s&&(this.programTimersStack=null);let o={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null},i=await Promise.all(r);return o.kernelMs=v.sum(i),o.getExtraProfileInfo=()=>i.map((l,c)=>({name:a[c],ms:l})).map(l=>`${l.name}: ${l.ms}`).join(", "),this.uploadWaitMs=0,this.downloadWaitMs=0,o}getAndSavePipeline(e,t){return e in this.pipelineCache||(this.pipelineCache[e]=t()),this.pipelineCache[e]}makeTensorInfo(e,t,n){let s;if(t==="string"&&n!=null&&n.length>0&&v.isString(n[0])){let r=n.map(a=>v.encodeString(a));s=this.write(r,e,t)}else s=this.write(n,e,t);return{dataId:s,shape:e,dtype:t}}tensorToBinding(e){if(!e)return null;let t=this.tensorMap.get(e.dataId);return{offset:0,size:t.bufferInfo.byteSize,buffer:t.bufferInfo.buffer}}async getQueryTime(e){return this.supportTimeQuery?this.getTimeFromQuerySet(e):0}uploadToGPU(e){let t=this.tensorMap.get(e);t.bufferInfo.buffer==null&&(t.bufferInfo.buffer=this.acquireBuffer(t.bufferInfo.byteSize),t.values&&this.queue.writeBuffer(t.bufferInfo.buffer,0,t.values))}makeUniformsDataView(e){let t=this.acquireBuffer(e.byteLength,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);return this.queue.writeBuffer(t,0,e),{offset:0,size:e.byteLength,buffer:t}}arrayToDataView(e,t){let n=4,s=new DataView(new ArrayBuffer(t*n)),r=0;return e.forEach(a=>{let o=a.data;if(a.type!=="int32"&&a.type!=="float32"&&a.type!=="uint32")throw new Error(`${a.type} not supported!`);a.type==="int32"?o.forEach(i=>{s.setInt32(r*n,i,!0),r++}):a.type==="uint32"?o.forEach(i=>{s.setUint32(r*n,i,!0),r++}):o.forEach(i=>{s.setFloat32(r*n,i,!0),r++})}),s}computePadding(e){let t=0,n=0,s=0,r=[];return e.forEach((a,o)=>{a.data.length===0&&(a.data=[1]);let i;switch(a.data.length){case 0:i=1;break;case 1:i=1;break;case 2:i=2;break;case 3:i=4;break;case 4:i=4;break;default:v.assert(!1,()=>`Unsupported ${a.data.length}D shape`)}n=Math.ceil(t/i)*i-t;for(let l=0;lE.shape),i="int32";o.map(E=>{a.push({type:i,data:E})});let l=v.computeStrides(r.shape);a.push({type:i,data:l}),e.size!=null&&a.push({type:i,data:[e.size]}),a.push({type:"uint32",data:e.dispatch}),s&&(a=[...a,...s]);let c=null,u=this.computePadding(a),d=u.byteLength;c=this.makeUniformsDataView(u);let p=t.map((E,$)=>{if(E.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");return this.uploadToGPU(E.dataId),{dtype:this.tensorMap.get(E.dataId).dtype,shape:E.shape,name:e.variableNames[$]}}),h=p.map(E=>E.dtype).concat(r.dtype),f=p.map(E=>N.getBroadcastDims(E.shape,r.shape)),m=p.map(E=>v.arraysEqual(E.shape,r.shape)).join("_"),g=f.map(E=>E.join("_")).join(";"),A=lC(e,o,h,g,m),{bindGroupLayout:y,pipelineLayout:x}=this.getCachedOrCreateLayout(e.variableNames.length),b=this.getAndSavePipeline(A,()=>iC(this.device,e,x,p,r)),w=this.activeTimers!=null,k=Ace(this.device,y,t.map(E=>this.tensorToBinding(E)),this.tensorToBinding(r),c);this.ensureCommandEncoderReady();let S=this.getComputePass();if(w&&this.supportTimeQuery&&S.writeTimestamp(this.querySet,0),S.setPipeline(b),S.setBindGroup(0,k),S.dispatch(e.dispatch[0],e.dispatch[1],e.dispatch[2]),w&&this.supportTimeQuery&&S.writeTimestamp(this.querySet,1),this.dispatchNumberInEncoder++,t.forEach(E=>{this.commandQueueOwnedIds.add(E.dataId)}),this.commandQueueOwnedIds.add(r.dataId),c){let E={byteSize:d,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM,buffer:c.buffer};this.uniformDisposalQueue.push(E)}return K().get("WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE")<=this.dispatchNumberInEncoder&&this.submitQueue(),w&&this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(this.querySet)}),r}runFromPixelsProgram(e,t,n,s,r){let a=this.device.createBindGroup({layout:n.bindGroupLayout,entries:[{binding:0,resource:{buffer:t}},{binding:1,resource:s},{binding:2,resource:{buffer:e.uniform}}]});this.ensureCommandEncoderReady();let o=this.getComputePass(),i=this.activeTimers!=null;i&&this.supportTimeQuery&&o.writeTimestamp(this.querySet,0),o.setPipeline(e.pipeline),o.setBindGroup(0,a),o.dispatch(e.dispatch[0],e.dispatch[1],e.dispatch[2]),i&&this.supportTimeQuery&&o.writeTimestamp(this.querySet,1),this.commandQueueOwnedIds.add(r),this.submitQueue(),i&&this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(this.querySet)})}async getTimeFromQuerySet(e){let t=this.acquireBuffer(16,GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE),n=this.acquireBuffer(16,GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST);this.ensureCommandEncoderReady(),this.ensureComputePassEnded(),this.currentCommandEncoder.resolveQuerySet(e,0,2,t,0),this.currentCommandEncoder.copyBufferToBuffer(t,0,n,0,16),this.submitQueue(),await n.mapAsync(GPUMapMode.READ);let s=new BigUint64Array(n.getMappedRange()),r=Number(s[1]-s[0]);return n.unmap(),this.bufferManager.releaseBuffer(n,16,GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST),this.bufferManager.releaseBuffer(t,16,GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE),r/1e6}shouldExecuteOnCPU(e,t=Ope){return K().getBool("WEBGPU_CPU_FORWARD")&&e.every(n=>this.tensorMap.get(n.dataId).bufferInfo.buffer==null&&v.sizeFromShape(n.shape)px,webgpu_util:()=>L4});gu.isBrowser()&&rx()&&Ki("webgpu",async()=>{K().set("CHECK_COMPUTATION_FOR_ERRORS",!1);let e={powerPreference:K().get("WEBGPU_USE_LOW_POWER_GPU")?"low-power":"high-performance"},t=await navigator.gpu.requestAdapter(e),n={},s=t.features.has("timestamp-query");s?n={requiredFeatures:["timestamp-query"]}:console.warn("This device doesn't support timestamp-query extension. Start Chrome browser with flag --disable-dawn-features=disallow_unsafe_apis then try again. Or zero will shown for the kernel time when profiling mode isenabled. Using performance.now is not workable for webgpu sinceit doesn't support synchronously to read data from GPU.");let r=await t.requestDevice(n);return new px(r,s)},3);var en;(function(e){e[e.float32=0]="float32",e[e.int32=1]="int32",e[e.bool=2]="bool",e[e.string=3]="string",e[e.complex64=4]="complex64"})(en||(en={}));var sp;(function(e){e[e.linear=0]="linear",e[e.relu=1]="relu",e[e.relu6=2]="relu6",e[e.prelu=3]="prelu",e[e.leakyrelu=4]="leakyrelu",e[e.sigmoid=5]="sigmoid",e[e.elu=6]="elu"})(sp||(sp={}));var vC;function Mpe(e){vC=e.wasm.cwrap(fo,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function zpe(e){let{inputs:t,backend:n,attrs:s}=e,{a:r,b:a,bias:o,preluActivationWeights:i}=t;if(r.dtype!=="float32"||a.dtype!=="float32")throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");let{transposeA:l,transposeB:c,activation:u,leakyreluAlpha:d}=s,p=n.dataIdMap.get(r.dataId).id,h=n.dataIdMap.get(a.dataId).id,f=0;if(o!=null){let E=n.dataIdMap.get(o.dataId);if(E.shape.length!==1)throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${E.shape.length}.`);f=E.id}let m=i==null?0:n.dataIdMap.get(i.dataId).id,g=sp[u];if(g==null)throw new Error(`${u} activation not yet supported for FusedConv2D in the wasm backend.`);let A=l?r.shape[2]:r.shape[1],y=c?a.shape[1]:a.shape[2],x=r.shape[0],b=n.makeOutput([x,A,y],r.dtype),w=n.dataIdMap.get(b.dataId).id,k=new Uint8Array(new Int32Array(r.shape).buffer),S=new Uint8Array(new Int32Array(a.shape).buffer);return vC(p,k,r.shape.length,h,S,a.shape.length,l,c,g,f,m,d||0,w),b}var Lpe={kernelName:fo,backendName:"wasm",setupFunc:Mpe,kernelFunc:zpe};function En(e,t){let n;function s(a){n=a.wasm.cwrap(e,null,["number","number","number"])}function r(a){let{backend:o,inputs:{x:i}}=a,l=o.dataIdMap.get(i.dataId).id,c=o.makeOutput(i.shape,t||i.dtype),u=o.dataIdMap.get(c.dataId).id;return v.sizeFromShape(c.shape)===0||n(l,en[i.dtype],u),c}return{kernelName:e,backendName:"wasm",setupFunc:s,kernelFunc:r}}var Bpe=En(ni);function Xn(e,t,n){let s;function r(o){s=o.wasm.cwrap(e,null,["number","array","number","number","array","number","number","number"])}function a(o){let{backend:i,inputs:l}=o,{a:c,b:u}=l,d=i.dataIdMap.get(c.dataId).id,p=i.dataIdMap.get(u.dataId).id,h=n!=null?n:c.dtype,f=N.assertAndGetBroadcastShape(c.shape,u.shape),m=i.makeOutput(f,h);if(v.sizeFromShape(f)===0)return m;let g=new Uint8Array(new Int32Array(c.shape).buffer),A=new Uint8Array(new Int32Array(u.shape).buffer),y=i.dataIdMap.get(m.dataId).id,x=()=>s(d,g,c.shape.length,p,A,u.shape.length,en[c.dtype],y);if(t&&c.dtype==="float32")return x(),m;let b=N.getBroadcastDims(c.shape,f),w=N.getBroadcastDims(u.shape,f),k=b.every((E,$)=>E===$),S=w.every((E,$)=>E===$);if(k&&S)return x(),m;throw new Error(`Broadcasting along outer dims is not yet supported for ${c.dtype} ${e}.`)}return{kernelName:e,backendName:"wasm",setupFunc:r,kernelFunc:a}}var Wpe=!0,Vpe=Xn(Hr,Wpe),wC;function Upe(e){wC=e.wasm.cwrap(wa,null,["array","number","number","number"])}function Gpe(e){let{inputs:t,backend:n}=e,s=n.makeOutput(t[0].shape,t[0].dtype);if(v.sizeFromShape(s.shape)===0)return s;let r=t.map(i=>n.dataIdMap.get(i.dataId).id),a=new Uint8Array(new Int32Array(r).buffer),o=n.dataIdMap.get(s.dataId).id;return wC(a,r.length,en[s.dtype],o),s}var Hpe={kernelName:wa,backendName:"wasm",setupFunc:Upe,kernelFunc:Gpe};function Mm(e){let{inputs:{x:t},backend:n}=e,s=n.makeOutput(t.shape,t.dtype),r=n.typedArrayFromHeap(t);return n.typedArrayFromHeap(s).set(r),s}var jpe={kernelName:Ba,backendName:"wasm",kernelFunc:Mm},kC;function qpe(e){kC=e.wasm.cwrap(po,null,["number","array","number","number","number","array","number"])}function lc(e){let{inputs:t,backend:n,attrs:s}=e,[r,a]=Kpe(t.x.shape,s.perm),o=!0;for(let f=0;f=r&&(a===-1||s[a]>s[o])&&(a=o);s[a]=r}return[n,s]}var Zpe={kernelName:po,backendName:"wasm",kernelFunc:lc,setupFunc:qpe};function zo(e,t,n){let s=e.shape,r=e.shape.length,a=v.parseAxisParam(t,s),o=a,i=N.getAxesPermutation(o,r),l=null,c=!1;if(i!=null){let u=new Array(r);for(let h=0;h`new shape: ${o}, old shape: ${s.shape}. New shape and old shape must have the same number of elements.`),e.backend.incRef(s.dataId),{dataId:s.dataId,shape:o,dtype:s.dtype}}var uhe={kernelName:Ti,backendName:"wasm",kernelFunc:us},NC;function che(e){NC=e.wasm.cwrap(Sa,null,["number","array","number","number","array","number","number","number","number"])}function dhe(e){let{inputs:t,backend:n,attrs:s}=e,{a:r,b:a}=t,{transposeA:o,transposeB:i}=s;if(r.dtype!=="float32"||a.dtype!=="float32")throw new Error("BatchMatMul for non non-float32 tensors not yet supported.");let l=r.shape.length,c=a.shape.length,u=o?r.shape[l-2]:r.shape[l-1],d=i?a.shape[c-1]:a.shape[c-2],p=o?r.shape[l-1]:r.shape[l-2],h=i?a.shape[c-2]:a.shape[c-1],f=r.shape.slice(0,-2),m=a.shape.slice(0,-2),g=v.sizeFromShape(f),A=v.sizeFromShape(m),y=g===A||g===1||A===1;v.assert(l>=2&&c>=2&&y,()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${f}) and (${m}).`);let b=(g>A?r.shape.slice(0,-2):a.shape.slice(0,-2)).concat([p,h]);v.assert(u===d,()=>`Error in matMul: inner shapes (${u}) and (${d}) of Tensors with shapes ${r.shape} and ${a.shape} and transposeA=${o} and transposeB=${i} must match.`);let w=o?[g,u,p]:[g,p,u],k=i?[A,h,d]:[A,d,h],S=us({inputs:{x:r},backend:n,attrs:{shape:w}}),E=us({inputs:{x:a},backend:n,attrs:{shape:k}}),$=n.dataIdMap.get(S.dataId).id,F=n.dataIdMap.get(E.dataId).id,R=o?S.shape[2]:S.shape[1],P=i?E.shape[1]:E.shape[2],T=Math.max(g,A),M=n.makeOutput([T,R,P],S.dtype),U=n.dataIdMap.get(M.dataId).id,H=new Uint8Array(new Int32Array(S.shape).buffer),z=new Uint8Array(new Int32Array(E.shape).buffer);return NC($,H,S.shape.length,F,z,E.shape.length,o,i,U),n.disposeData(S.dataId),n.disposeData(E.dataId),M.shape=b,M}var phe={kernelName:Sa,backendName:"wasm",setupFunc:che,kernelFunc:dhe};function rp(e){let{inputs:{x:t},attrs:{begin:n,size:s},backend:r}=e,[a,o]=An.parseSliceParams(t,n,s),i=An.isSliceContinous(t.shape,a,o),l=r.readSync(t.dataId),c=r.makeOutput(o,t.dtype),u=v.computeStrides(t.shape),d=r.dataIdMap.get(c.dataId);if(i){let f=An.computeFlatOffset(a,u);return t.dtype==="string"?d.stringBytes=l.slice(f,f+v.sizeFromShape(o)):r.typedArrayFromHeap(c).set(l.subarray(f,f+v.sizeFromShape(o))),c}if(t.dtype==="string"){let f=um(l,a,o,t.shape,t.dtype);return d.stringBytes=f,c}let p=r.typedArrayFromHeap(c),h=t.shape.length;if(h===2)hhe(l,u[0],p,a,o);else if(h===3)fhe(l,u[0],u[1],p,a,o);else if(h===4)mhe(l,u[0],u[1],u[2],p,a,o);else{let f=um(l,a,o,t.shape,t.dtype);p.set(f)}return c}function hhe(e,t,n,s,r){let a=0,o=s[0],i=s[1],l=o+r[0];for(let c=o;cA*y),l=N.getReshaped(r.shape,a,i),c=N.getPermuted(l.length,a.length),u=N.getReshapedPermuted(r.shape,a,i),d=N.getSliceBeginCoords(o,a.length),p=N.getSliceSize(u,o,a.length),h=us({inputs:{x:r},backend:n,attrs:{shape:l}}),f=lc({inputs:{x:h},backend:n,attrs:{perm:c}}),m=us({inputs:{x:f},backend:n,attrs:{shape:u}}),g=rp({inputs:{x:m},backend:n,attrs:{begin:d,size:p}});return n.disposeData(h.dataId),n.disposeData(f.dataId),n.disposeData(h.dataId),g}var yhe={kernelName:si,backendName:"wasm",kernelFunc:Ahe};function ap(e){let{inputs:{x:t},attrs:{dtype:n},backend:s}=e,r=s.makeOutput(t.shape,n),a=s.typedArrayFromHeap(t);return s.typedArrayFromHeap(r).set(a),r}var xhe={kernelName:Ca,backendName:"wasm",kernelFunc:ap},bhe=En(Ta),EC;function vhe(e){EC=e.wasm.cwrap(jr,null,["number","number","number","number"])}function whe(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{clipValueMin:a,clipValueMax:o}=s,i=n.dataIdMap.get(r.dataId).id,l=n.makeOutput(r.shape,r.dtype),c=n.dataIdMap.get(l.dataId).id;return EC(i,a,o,c),l}var khe={kernelName:jr,backendName:"wasm",setupFunc:vhe,kernelFunc:whe};function RC(e){let{inputs:t,backend:n}=e,s=v.parseAxisParam(e.attrs.axis,t[0].shape)[0],r=N.computeOutShape(t.map(h=>h.shape),s),a=t.filter(h=>v.sizeFromShape(h.shape)>0);if(a.length===1)return Mm({inputs:{x:a[0]},backend:n});let o=n.makeOutput(r,t[0].dtype);if(v.sizeFromShape(r)===0)return o;let i=a.map(h=>h.shape);if(N.assertParamsConsistent(i,s),a[0].dtype==="string"){let h=a.map(x=>{let b=v.sizeFromShape(x.shape.slice(s));return us({inputs:{x},backend:n,attrs:{shape:[-1,b]}})}),f=h.map(x=>({vals:n.readSync(x.dataId),shape:x.shape}));r=N.computeOutShape(h.map(x=>x.shape),1);let m=h[0].shape[0]===1,g=wy(f,r,t[0].dtype,m),A=N.computeOutShape(a.map(x=>x.shape),s);o.shape=A;let y=n.dataIdMap.get(o.dataId);return y.stringBytes=N.fromStringArrayToUint8(g),h.forEach(x=>n.disposeData(x.dataId)),o}let l=v.sizeFromShape(a[0].shape.slice(0,s)),c=0,u=a.map(h=>{let f=v.sizeFromShape(h.shape.slice(s));return c+=f,f}),d=a.map(h=>n.typedArrayFromHeap(h)),p=n.typedArrayFromHeap(o);for(let h=0;h`cumsum does not support ${r.dtype} tensors in the WASM backend`);let c=N.getAxesPermutation([a],l),u=r;c!==null&&(u=lc({inputs:{x:r},attrs:{perm:c},backend:n}));let d=N.getInnerMostAxes(1,l)[0];N.assertAxesAreInnerMostDims("cumsum",[d],l);let p=n.makeOutput(u.shape,u.dtype),h=u.shape[d],f=n.dataIdMap.get(u.dataId).id,m=n.dataIdMap.get(p.dataId).id;PC(f,o?1:0,i?1:0,h,m,en[r.dtype]);let g=p;if(c!==null){let A=N.getUndoAxesPermutation(c);g=lc({inputs:{x:p},attrs:{perm:A},backend:n}),n.disposeData(u.dataId),n.disposeData(p.dataId)}return g}var zhe={kernelName:ai,backendName:"wasm",setupFunc:Ohe,kernelFunc:Mhe},FC;function Lhe(e){FC=e.wasm.cwrap(ii,null,["number","number","number","array","number","array","array","number","number"])}function Bhe(e){let{backend:t,inputs:n,attrs:s}=e,{x:r}=n,{blockSize:a,dataFormat:o}=s,i=r.shape[0],l=o==="NHWC"?r.shape[1]:r.shape[2],c=o==="NHWC"?r.shape[2]:r.shape[3],u=o==="NHWC"?r.shape[3]:r.shape[1],d=l*a,p=c*a,h=u/(a*a),f=o==="NHWC"?[i,d,p,h]:[i,h,d,p],m=t.makeOutput(f,"float32"),A=t.dataIdMap.get(r.dataId).id,y=new Uint8Array(new Int32Array(v.computeStrides(r.shape)).buffer),x=new Uint8Array(new Int32Array(f).buffer),b=new Uint8Array(new Int32Array(v.computeStrides(f)).buffer),w=t.dataIdMap.get(m.dataId).id;return FC(A,a,o==="NHWC"?1:0,y,r.shape.length-1,x,b,f.length,w),m}var Whe={kernelName:ii,backendName:"wasm",setupFunc:Lhe,kernelFunc:Bhe},OC;function Vhe(e){OC=e.wasm.cwrap(Da,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Uhe(e){let{inputs:t,attrs:n,backend:s}=e,{x:r,filter:a}=t,o=s.dataIdMap.get(r.dataId).id,i=s.dataIdMap.get(a.dataId).id,{strides:l,dilations:c,pad:u,dimRoundingMode:d}=n,p=c==null?[1,1]:c,h=N.computeConv2DInfo(r.shape,a.shape,l,p,u,d,!0),f=h.filterHeight,m=h.filterWidth,g=h.padInfo.top,A=h.padInfo.right,y=h.padInfo.bottom,x=h.padInfo.left,b=h.dilationHeight,w=h.dilationWidth,k=h.strideHeight,S=h.strideWidth,E=h.inChannels,$=h.outChannels,F=h.padInfo.type==="SAME"?1:0;if(h.dataFormat!=="channelsLast")throw new Error(`wasm backend DepthwiseConv2dNative does not support dataFormat:'${h.dataFormat}'. Please use 'channelsLast'.`);let R=s.makeOutput(h.outShape,"float32"),P=s.dataIdMap.get(R.dataId).id;return OC(o,r.shape[0],r.shape[1],r.shape[2],i,f,m,g,A,y,x,F,b,w,k,S,E,$,P),R}var Ghe={kernelName:Da,backendName:"wasm",setupFunc:Vhe,kernelFunc:Uhe},Hhe=En(Pa),jhe=!1,qhe=Xn(li,jhe,"bool"),Xhe=En(Fa,"float32");function fx(e){let{inputs:t,attrs:n,backend:s}=e,{input:r}=t,{dim:a}=n,o=r.shape.length,i=r.shape.slice(),l=a;return a<0&&(v.assert(-(o+1)<=a,()=>`Axis must be in the interval [${-(o+1)}, ${o}]`),l=o+a+1),i.splice(l,0,1),us({inputs:{x:r},backend:s,attrs:{shape:i}})}var Khe={kernelName:ui,backendName:"wasm",kernelFunc:fx};function MC(e){let{attrs:{shape:t,value:n,dtype:s},backend:r}=e,a=r.makeOutput(t,s);return r.typedArrayFromHeap(a).fill(n),a}var Zhe={kernelName:Ql,backendName:"wasm",kernelFunc:MC},zC;function Yhe(e){zC=e.wasm.cwrap(di,null,["number","number","number","number","number","number"])}function Jhe(e){let{inputs:t,backend:n}=e,{image:s}=t,r=n.makeOutput(s.shape,s.dtype),a=n.dataIdMap.get(s.dataId).id,o=n.dataIdMap.get(r.dataId).id,[i,l,c,u]=s.shape;return zC(a,i,l,c,u,o),r}var Qhe={kernelName:di,backendName:"wasm",kernelFunc:Jhe,setupFunc:Yhe},efe=En(Oa),tfe=!1,nfe=Xn(Ma,tfe),LC;function sfe(e){LC=e.wasm.cwrap(za,null,["number","number","number","number","number","number","number"])}function rfe(e){let{backend:t,inputs:n,attrs:s}=e,{varianceEpsilon:r}=s,{x:a,mean:o,variance:i,offset:l,scale:c}=n,u=t.dataIdMap.get(a.dataId).id,d=t.dataIdMap.get(o.dataId).id,p=t.dataIdMap.get(i.dataId).id,h=l!=null?t.dataIdMap.get(l.dataId).id:0,f=c!=null?t.dataIdMap.get(c.dataId).id:0,m=t.makeOutput(a.shape,a.dtype);if(v.sizeFromShape(a.shape)===0)return m;let g=t.dataIdMap.get(m.dataId).id;return LC(u,d,p,h,f,r,g),m}var afe={kernelName:za,backendName:"wasm",setupFunc:sfe,kernelFunc:rfe},BC;function ofe(e){BC=e.wasm.cwrap(mo,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function ife(e){let{inputs:t,attrs:n,backend:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:c,dilations:u,dataFormat:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=n,m=N.computeConv2DInfo(r.shape,a.shape,l,u,c,p),g=sp[h];if(g==null)throw new Error(`${h} activation not yet supported for FusedConv2D in the wasm backend.`);let A=s.dataIdMap.get(r.dataId).id,y=s.dataIdMap.get(a.dataId).id,x=m.outChannels,b=0;if(o!=null){let J=s.dataIdMap.get(o.dataId);if(J.shape.length!==1)throw new Error(`FusedConv2D only supports rank-1 bias but got rank ${J.shape.length}.`);if(J.shape[0]!==x)throw new Error(`FusedConv2D bias shape (${J.shape}) does not match the number of output channels (${x})`);b=J.id}let w=m.filterHeight,k=m.filterWidth,S=m.padInfo.top,E=m.padInfo.right,$=m.padInfo.bottom,F=m.padInfo.left,R=m.dilationHeight,P=m.dilationWidth,T=m.strideHeight,M=m.strideWidth,U=m.inChannels,H=m.padInfo.type==="SAME"?1:0,z=m.batchSize,X=m.inHeight,ee=m.inWidth;if(d!=="NHWC")throw new Error(`wasm backend FusedConv2D does not support dataFormat:'${d}'. Please use 'NHWC'.`);let Y=s.makeOutput(m.outShape,"float32"),ne=s.dataIdMap.get(Y.dataId).id,se=i==null?0:s.dataIdMap.get(i.dataId).id;return BC(A,z,X,ee,y,w,k,b,S,E,$,F,H,R,P,T,M,U,x,g,se,f||0,ne),Y}var lfe={kernelName:mo,backendName:"wasm",setupFunc:ofe,kernelFunc:ife},WC;function ufe(e){WC=e.wasm.cwrap(go,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function cfe(e){let{inputs:t,attrs:n,backend:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:c,dilations:u,dataFormat:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=n,m=N.computeConv2DInfo(r.shape,a.shape,l,u,c,p,!0),g=sp[h];if(g==null)throw new Error(`${h} activation not yet supported for FusedDepthwiseConv2D in the wasm backend.`);let A=s.dataIdMap.get(r.dataId).id,y=s.dataIdMap.get(a.dataId).id,x=m.outChannels,b=0;if(o!=null){let J=s.dataIdMap.get(o.dataId);if(J.shape.length!==1)throw new Error(`FusedDepthwiseConv2D only supports rank-1 bias but got rank ${J.shape.length}.`);if(J.shape[0]!==x)throw new Error(`FusedDepthwiseConv2D bias shape (${J.shape}) does not match the number of output channels (${x})`);b=J.id}let w=m.filterHeight,k=m.filterWidth,S=m.padInfo.top,E=m.padInfo.right,$=m.padInfo.bottom,F=m.padInfo.left,R=m.dilationHeight,P=m.dilationWidth,T=m.strideHeight,M=m.strideWidth,U=m.inChannels,H=m.padInfo.type==="SAME"?1:0,z=m.batchSize,X=m.inHeight,ee=m.inWidth;if(d!=="NHWC")throw new Error(`wasm backend FusedDepthwiseConv2D does not support dataFormat:'${d}'. Please use 'NHWC'.`);let Y=s.makeOutput(m.outShape,"float32"),ne=s.dataIdMap.get(Y.dataId).id,se=i==null?0:s.dataIdMap.get(i.dataId).id;return WC(A,z,X,ee,y,w,k,b,S,E,$,F,H,R,P,T,M,U,x,g,se,f||0,ne),Y}var dfe={kernelName:go,backendName:"wasm",setupFunc:ufe,kernelFunc:cfe},VC;function pfe(e){VC=e.wasm.cwrap(hi,null,["number","number","number","number","number","number","array","number"])}function hfe(e){let{backend:t,inputs:n}=e,{params:s,indices:r}=n,[a,o,i,l]=A2.prepareAndValidate(s,r),c=t.makeOutput(a,s.dtype);if(o===0)return c;let u=r.shape,d=u[u.length-1],h=t.dataIdMap.get(s.dataId).id,m=t.dataIdMap.get(r.dataId).id,g=new Uint8Array(new Int32Array(l).buffer),A=t.dataIdMap.get(c.dataId).id;return VC(h,en[s.dtype],m,o,d,i,g,A),c}var ffe={kernelName:hi,backendName:"wasm",setupFunc:pfe,kernelFunc:hfe},UC;function mfe(e){UC=e.wasm.cwrap("Gather",null,["number","number","array","number","number","number","array","number"])}function gfe(e){let{backend:t,inputs:n,attrs:s}=e,{x:r,indices:a}=n,{axis:o,batchDims:i}=s,l=v.parseAxisParam(o,r.shape)[0],c=t.readSync(a.dataId),u=r.shape[l];for(let $=0;$=0,()=>`GatherV2: the index value ${F} is not in [0, ${u-1}]`)}let d=N.segment_util.collectGatherOpShapeInfo(r,a,l,i),p=us({inputs:{x:r},attrs:{shape:[d.batchSize,d.outerSize,d.dimSize,d.sliceSize]},backend:t}),h=v.sizeFromShape(a.shape),f=us({inputs:{x:a},attrs:{shape:[d.batchSize,h/d.batchSize]},backend:t}),m=[d.batchSize,d.outerSize,h/d.batchSize,d.sliceSize],g=t.makeOutput(m,r.dtype);if(v.sizeFromShape(r.shape)===0)return g;let A=p.shape.length-1,x=t.dataIdMap.get(p.dataId).id,w=t.dataIdMap.get(f.dataId).id,k=t.dataIdMap.get(g.dataId).id,S=new Uint8Array(new Int32Array(v.computeStrides(p.shape)).buffer),E=new Uint8Array(new Int32Array(v.computeStrides(m)).buffer);return UC(x,en[r.dtype],S,A,w,d.batchSize,E,k),t.disposeData(p.dataId),t.disposeData(f.dataId),g.shape=d.outputShape,g}var Afe={kernelName:pi,backendName:"wasm",setupFunc:mfe,kernelFunc:gfe},yfe=!1,xfe=Xn(fi,yfe,"bool"),bfe=!1,vfe=Xn(La,bfe,"bool"),GC;function wfe(e){GC=e.wasm.cwrap(mi,null,["number","number","number","number"])}function kfe(e){let{inputs:{x:t},attrs:{alpha:n},backend:s}=e,r=s.dataIdMap.get(t.dataId).id,a=s.makeOutput(t.shape,"float32");if(v.sizeFromShape(t.shape)!==0){let o=s.dataIdMap.get(a.dataId).id;GC(r,en[t.dtype],n,o)}return a}var Ife={kernelName:mi,backendName:"wasm",setupFunc:wfe,kernelFunc:kfe},Sfe=!1,Cfe=Xn(gi,Sfe,"bool"),Tfe=!1,Nfe=Xn(Ai,Tfe,"bool"),Efe=En(Wa),Rfe=!1,$fe=Xn(yi,Rfe,"bool"),HC;function Dfe(e){HC=e.wasm.cwrap(Va,null,["number","number","number","number"])}function _fe(e){let{backend:t,inputs:n,attrs:s}=e,{reductionIndices:r,keepDims:a}=s,{x:o}=n,l=t.dataIdMap.get(o.dataId).id,c=o,{transposed:u,axes:d,originalAxes:p,inputWasTransposed:h}=zo(o,r,t);if(h){let x=t.dataIdMap.get(u.dataId).id;c=u,l=x}let f=c.shape.length;N.assertAxesAreInnerMostDims("max",d,f);let[m,g]=N.computeOutAndReduceShapes(c.shape,d),A=v.sizeFromShape(g),y=t.makeOutput(m,o.dtype);if(v.sizeFromShape(c.shape)!==0){let x=t.dataIdMap.get(y.dataId).id;HC(l,en[o.dtype],A,x)}if(h&&t.disposeData(u.dataId),a){let x=N.expandShapeToKeepDim(y.shape,p);y.shape=x}return y}var Pfe={kernelName:Va,backendName:"wasm",setupFunc:Dfe,kernelFunc:_fe},Ffe=!1,Ofe=Xn(Ua,Ffe),jC;function Mfe(e){jC=e.wasm.cwrap(Ga,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function zfe(e){let{inputs:t,attrs:n,backend:s}=e,r=t.x,a=s.dataIdMap.get(r.dataId).id;v.assert(r.dtype==="float32",()=>`Error in MaxPool: only float32 input is supported. Got ${r.dtype}.`);let{filterSize:o,strides:i,pad:l,dimRoundingMode:c}=n,u=N.computePool2DInfo(r.shape,o,i,1,l,c),d=u.filterHeight,p=u.filterWidth,h=u.padInfo.top,f=u.padInfo.right,m=u.padInfo.bottom,g=u.padInfo.left,A=u.dilationHeight,y=u.dilationWidth,x=u.strideHeight,b=u.strideWidth,w=u.inChannels,k=u.outChannels;if(u.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${u.dataFormat}'. Please use 'channelsLast'.`);let S=s.makeOutput(u.outShape,"float32"),E=s.dataIdMap.get(S.dataId).id;return jC(a,r.shape[0],r.shape[1],r.shape[2],d,p,h,f,m,g,A,y,x,b,w,k,E),S}var Lfe={kernelName:Ga,backendName:"wasm",setupFunc:Mfe,kernelFunc:zfe},qC;function Bfe(e){qC=e.wasm.cwrap(Ha,null,["number, number, number"])}function Wfe(e){let{backend:t,inputs:n,attrs:s}=e,{axis:r,keepDims:a}=s,{x:o}=n,i=t.dataIdMap.get(o.dataId).id,l=i,c=o,{transposed:u,axes:d,originalAxes:p,inputWasTransposed:h}=zo(o,r,t),f=d;if(h){let b=t.dataIdMap.get(u.dataId).id;b!==i&&(c=u,l=b,f=N.getInnerMostAxes(f.length,c.shape.length))}N.assertAxesAreInnerMostDims("mean",f,c.shape.length);let[m,g]=N.computeOutAndReduceShapes(c.shape,f),A=v.sizeFromShape(g),y=c;c.dtype!=="float32"&&(y=ap({backend:t,inputs:{x:c},attrs:{dtype:"float32"}}),l=t.dataIdMap.get(y.dataId).id);let x=t.makeOutput(m,"float32");if(v.sizeFromShape(c.shape)!==0){let b=t.dataIdMap.get(x.dataId).id;qC(l,A,b)}if(h&&t.disposeData(u.dataId),a){let b=N.expandShapeToKeepDim(x.shape,p);x.shape=b}return c.dtype!=="float32"&&t.disposeData(y.dataId),x}var Vfe={kernelName:Ha,backendName:"wasm",setupFunc:Bfe,kernelFunc:Wfe},XC;function Ufe(e){XC=e.wasm.cwrap(ja,null,["number","number","number","number"])}function Gfe(e){let{backend:t,inputs:n,attrs:s}=e,{axis:r,keepDims:a}=s,{x:o}=n,i=t.dataIdMap.get(o.dataId).id,l=i,c=o,{transposed:u,axes:d,originalAxes:p,inputWasTransposed:h}=zo(o,r,t);if(h){let x=t.dataIdMap.get(u.dataId).id;x!==i&&(c=u,l=x)}let f=c.shape.length;N.assertAxesAreInnerMostDims("min",d,f);let[m,g]=N.computeOutAndReduceShapes(c.shape,d),A=v.sizeFromShape(g),y=t.makeOutput(m,c.dtype);if(v.sizeFromShape(c.shape)!==0){let x=t.dataIdMap.get(y.dataId).id;XC(l,en[o.dtype],A,x)}if(h&&t.disposeData(u.dataId),a){let x=N.expandShapeToKeepDim(y.shape,p);y.shape=x}return y}var Hfe={kernelName:ja,backendName:"wasm",setupFunc:Ufe,kernelFunc:Gfe},jfe=!1,qfe=Xn(qa,jfe),mx;(function(e){e[e.reflect=0]="reflect",e[e.symmetric=1]="symmetric"})(mx||(mx={}));var KC;function Xfe(e){KC=e.wasm.cwrap(Xa,null,["number","array","number","number","array","array","number","number"])}function Kfe(e){let{inputs:{x:t},backend:n,attrs:{paddings:s,mode:r}}=e,a=s.map((f,m)=>f[0]+t.shape[m]+f[1]),o=n.dataIdMap.get(t.dataId).id,i=n.makeOutput(a,t.dtype),l=n.dataIdMap.get(i.dataId).id,c=new Uint8Array(new Int32Array(t.shape).buffer),u=s.map(f=>f[0]),d=s.map(f=>f[1]),p=new Uint8Array(new Int32Array(u).buffer),h=new Uint8Array(new Int32Array(d).buffer);return KC(o,c,t.shape.length,en[t.dtype],p,h,mx[r],l),i}var Zfe={kernelName:Xa,backendName:"wasm",kernelFunc:Kfe,setupFunc:Xfe},Yfe=!0,Jfe=Xn(Ka,Yfe),Qfe=En(xi);function gx(e,t){let n=new Int32Array(e.wasm.HEAPU8.buffer,t,4),s=n[0],r=n[1],a=n[2],o=n[3];return e.wasm._free(t),{pSelectedIndices:s,selectedSize:r,pSelectedScores:a,pValidOutputs:o}}var ZC;function eme(e){ZC=e.wasm.cwrap(vi,"number",["number","number","number","number","number"])}function tme(e){let{backend:t,inputs:n,attrs:s}=e,{iouThreshold:r,maxOutputSize:a,scoreThreshold:o}=s,{boxes:i,scores:l}=n,c=t.dataIdMap.get(i.dataId).id,u=t.dataIdMap.get(l.dataId).id,d=ZC(c,u,a,r,o),{pSelectedIndices:p,selectedSize:h,pSelectedScores:f,pValidOutputs:m}=gx(t,d);return t.wasm._free(f),t.wasm._free(m),t.makeOutput([h],"int32",p)}var nme={kernelName:vi,backendName:"wasm",setupFunc:eme,kernelFunc:tme},YC;function sme(e){YC=e.wasm.cwrap(ou,"number",["number","number","number","number","number","bool"])}function rme(e){let{backend:t,inputs:n,attrs:s}=e,{iouThreshold:r,maxOutputSize:a,scoreThreshold:o,padToMaxOutputSize:i}=s,{boxes:l,scores:c}=n,u=t.dataIdMap.get(l.dataId).id,d=t.dataIdMap.get(c.dataId).id,p=YC(u,d,a,r,o,i),{pSelectedIndices:h,selectedSize:f,pSelectedScores:m,pValidOutputs:g}=gx(t,p);t.wasm._free(m);let A=t.makeOutput([f],"int32",h),y=t.makeOutput([],"int32",g);return[A,y]}var ame={kernelName:ou,backendName:"wasm",setupFunc:sme,kernelFunc:rme},JC;function ome(e){JC=e.wasm.cwrap(wi,"number",["number","number","number","number","number","number"])}function ime(e){let{backend:t,inputs:n,attrs:s}=e,{iouThreshold:r,maxOutputSize:a,scoreThreshold:o,softNmsSigma:i}=s,{boxes:l,scores:c}=n,u=t.dataIdMap.get(l.dataId).id,d=t.dataIdMap.get(c.dataId).id,p=JC(u,d,a,r,o,i),{pSelectedIndices:h,selectedSize:f,pSelectedScores:m,pValidOutputs:g}=gx(t,p);t.wasm._free(g);let A=t.makeOutput([f],"int32",h),y=t.makeOutput([f],"float32",m);return[A,y]}var lme={kernelName:wi,backendName:"wasm",setupFunc:ome,kernelFunc:ime},ume=!1,cme=Xn(bi,ume,"bool"),QC;function dme(e){QC=e.wasm.cwrap(Ii,null,["number","number","number","number","number"])}function pme(e){let{inputs:t,backend:n,attrs:s}=e,{indices:r}=t,{depth:a,onValue:o,offValue:i}=s,l=n.makeOutput([...r.shape,a],"int32"),c=n.dataIdMap.get(l.dataId).id,d=n.dataIdMap.get(r.dataId).id;return QC(d,a,o,i,c),l}var hme={kernelName:Ii,backendName:"wasm",setupFunc:dme,kernelFunc:pme};function fme(e){let{inputs:{x:t},backend:n}=e,s=n.makeOutput(t.shape,t.dtype);return n.typedArrayFromHeap(s).fill(1),s}var mme={kernelName:ki,backendName:"wasm",kernelFunc:fme};function gme(e){let{inputs:t,backend:n,attrs:s}=e,{axis:r}=s;if(t.length===1)return fx({inputs:{input:t[0]},backend:n,attrs:{dim:r}});let a=t[0].shape,o=t[0].dtype;t.forEach(u=>{v.assertShapesMatch(a,u.shape,"All tensors passed to stack must have matching shapes"),v.assert(o===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],l=t.map(u=>{let d=fx({inputs:{input:u},backend:n,attrs:{dim:r}});return i.push(d),d}),c=RC({inputs:l,backend:n,attrs:{axis:r}});return i.forEach(u=>n.disposeData(u.dataId)),c}var Ame={kernelName:Si,backendName:"wasm",kernelFunc:gme},e6;function yme(e){e6=e.wasm.cwrap(Za,null,["number","array","number","number","array","array","number","number"])}function xme(e){let{inputs:{x:t},backend:n,attrs:{paddings:s,constantValue:r}}=e,a=s.map((m,g)=>m[0]+t.shape[g]+m[1]);if(v.sizeFromShape(t.shape)===0)return MC({backend:n,attrs:{shape:a,value:r,dtype:t.dtype}});let o=n.dataIdMap.get(t.dataId).id,i=n.makeOutput(a,t.dtype),c=n.dataIdMap.get(i.dataId).id,u=new Uint8Array(new Int32Array(t.shape).buffer),d=s.map(m=>m[0]),p=s.map(m=>m[1]),h=new Uint8Array(new Int32Array(d).buffer),f=new Uint8Array(new Int32Array(p).buffer);return e6(o,u,t.shape.length,en[t.dtype],h,f,r,c),i}var t6={kernelName:Za,backendName:"wasm",kernelFunc:xme,setupFunc:yme},bme=!1,vme=Xn(Ya,bme),n6;function wme(e){n6=e.wasm.cwrap(Ja,null,["number","number","number"])}function kme(e){let{inputs:t,backend:n}=e,{x:s,alpha:r}=t,a=n.dataIdMap.get(s.dataId).id,o=n.dataIdMap.get(r.dataId).id,i=a,l=s,c=l;l.dtype!=="float32"&&(c=ap({backend:n,inputs:{x:s},attrs:{dtype:"float32"}}),i=n.dataIdMap.get(c.dataId).id);let u=n.makeOutput(s.shape,"float32"),d=n.dataIdMap.get(u.dataId).id;return n6(i,o,d),l.dtype!=="float32"&&n.disposeData(c.dataId),u}var Ime={kernelName:Ja,backendName:"wasm",setupFunc:wme,kernelFunc:kme},s6;function Sme(e){s6=e.wasm.cwrap(Ci,null,["number","number","number","number"])}function Cme(e){let{backend:t,inputs:n,attrs:s}=e,{axis:r,keepDims:a}=s,{x:o}=n,i=t.dataIdMap.get(o.dataId).id,l=i,c=o,{transposed:u,axes:d,originalAxes:p,inputWasTransposed:h}=zo(o,r,t),f=d;if(h){let x=t.dataIdMap.get(u.dataId).id;x!==i&&(c=u,l=x,f=N.getInnerMostAxes(f.length,c.shape.length))}N.assertAxesAreInnerMostDims("prod",f,c.shape.length);let[m,g]=N.computeOutAndReduceShapes(c.shape,f),A=v.sizeFromShape(g),y=t.makeOutput(m,c.dtype);if(v.sizeFromShape(c.shape)!==0){let x=t.dataIdMap.get(y.dataId).id;s6(l,A,en[y.dtype],x)}if(h&&t.disposeData(u.dataId),a){let x=N.expandShapeToKeepDim(y.shape,p);y.shape=x}return y}var Tme={kernelName:Ci,backendName:"wasm",setupFunc:Sme,kernelFunc:Cme},Nme=e=>{let{backend:t,attrs:n}=e,{start:s,stop:r,step:a,dtype:o}=n,i=Sy(s,r,a,o),l=t.makeOutput([i.length],o);return t.typedArrayFromHeap(l).set(i),l},Eme={kernelName:iu,backendName:"wasm",kernelFunc:Nme},Rme=!0,$me=Xn(_a,Rme),Dme=En(Qa),_me=En(to),r6;function Pme(e){r6=e.wasm.cwrap(eo,null,["number","number","number","number","number","number","number","number","number","number"])}function Fme(e){let{backend:t,inputs:n,attrs:s}=e,{images:r}=n,{alignCorners:a,halfPixelCenters:o,size:i}=s,[l,c]=i,[u,d,p,h]=r.shape,f=[u,l,c,h],m=t.dataIdMap.get(r.dataId),g;m.dtype!=="float32"&&(g=ap({backend:t,inputs:{x:r},attrs:{dtype:"float32"}}),m=t.dataIdMap.get(g.dataId));let A=m.id,y=t.makeOutput(f,"float32");if(v.sizeFromShape(r.shape)===0)return y;let x=t.dataIdMap.get(y.dataId).id;return r6(A,u,d,p,h,l,c,a?1:0,o?1:0,x),g!=null&&t.disposeData(g.dataId),y}var Ome={kernelName:eo,backendName:"wasm",setupFunc:Pme,kernelFunc:Fme},a6;function Mme(e){a6=e.wasm.cwrap(Ni,null,["number","array","number","array","number","number"])}function zme(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{dims:a}=s,o=v.parseAxisParam(a,r.shape);if(r.shape.length===0)return Mm({inputs:{x:r},backend:n});let i=n.makeOutput(r.shape,r.dtype),l=n.dataIdMap.get(r.dataId).id,c=n.dataIdMap.get(i.dataId).id,u=new Uint8Array(new Int32Array(o).buffer),d=new Uint8Array(new Int32Array(r.shape).buffer);a6(l,u,o.length,d,r.shape.length,c);let p=us({inputs:{x:i},attrs:{shape:r.shape},backend:n});return n.disposeData(i.dataId),p}var Lme={kernelName:Ni,backendName:"wasm",kernelFunc:zme,setupFunc:Mme},o6;function Bme(e){o6=e.wasm.cwrap(Vi,null,["number","number","number","number","number","number","number","number","array","number","number"])}function Wme(e){let{inputs:t,backend:n,attrs:s}=e,{image:r}=t,{radians:a,fillValue:o,center:i}=s,l=n.makeOutput(r.shape,r.dtype),c=n.dataIdMap.get(r.dataId).id,u=n.dataIdMap.get(l.dataId).id,[d,p,h,f]=r.shape,[m,g]=N.getImageCenter(i,p,h),A=o===0,y=255,x=typeof o=="number"?[o,o,o,A?0:y]:[...o,y],b=new Uint8Array(new Int32Array(x).buffer);return o6(c,d,p,h,f,a,m,g,b,x.length,u),l}var Vme={kernelName:Vi,backendName:"wasm",kernelFunc:Wme,setupFunc:Bme},Ume=En(Ei),Gme=En(no),i6;function Hme(e){i6=e.wasm.cwrap(Ri,null,["number","number","number","number","number","number","array","number","number"])}function jme(e){let{backend:t,inputs:n,attrs:s}=e,{indices:r,updates:a}=n,{shape:o}=s,i=t.makeOutput(o,a.dtype);if(v.sizeFromShape(o)===0)return i;let{sliceRank:l,numUpdates:c,sliceSize:u,strides:d,outputSize:p}=y2.calculateShapes(a,r,o),f=t.dataIdMap.get(r.dataId).id,g=t.dataIdMap.get(a.dataId).id,A=new Uint8Array(new Int32Array(d).buffer),y=t.dataIdMap.get(i.dataId).id;return i6(f,g,en[a.dtype],l,c,u,A,p,y),i}var qme={kernelName:Ri,backendName:"wasm",setupFunc:Hme,kernelFunc:jme},l6;function Xme(e){l6=e.wasm.cwrap("SelectV2",null,["number","number","number","number","number"])}function Kme(e){let{inputs:t,backend:n}=e,{condition:s,t:r,e:a}=t,o=n.dataIdMap.get(s.dataId).id,i=n.dataIdMap.get(r.dataId).id,l=n.dataIdMap.get(a.dataId).id,c=n.makeOutput(r.shape,r.dtype),u=n.dataIdMap.get(c.dataId).id,d=s.shape.length,p=r.shape.length,h=d===0||d>1||p===1?1:v.sizeFromShape(r.shape.slice(1));return l6(o,i,l,h,u),c}var Zme={kernelName:$i,backendName:"wasm",kernelFunc:Kme,setupFunc:Xme},u6;function Yme(e){u6=e.wasm.cwrap(ro,null,["number","number"])}function Jme(e){let{backend:t,inputs:{x:n}}=e,s=t.dataIdMap.get(n.dataId).id,r=t.makeOutput(n.shape,n.dtype),a=t.dataIdMap.get(r.dataId).id;return v.sizeFromShape(r.shape)===0||u6(s,a),r}var Qme={kernelName:"Sigmoid",backendName:"wasm",setupFunc:Yme,kernelFunc:Jme},e0e=En(so),c6;function t0e(e){c6=e.wasm.cwrap(io,null,["number","number","number","number"])}function n0e(e){let{backend:t,inputs:{logits:n},attrs:{dim:s}}=e,r=t.dataIdMap.get(n.dataId).id,a=t.makeOutput(n.shape,n.dtype),o=t.dataIdMap.get(a.dataId).id,i=n.shape[s],l=v.sizeFromShape(n.shape)/i;return v.sizeFromShape(a.shape)===0||c6(r,o,i,l),a}var s0e={kernelName:io,backendName:"wasm",setupFunc:t0e,kernelFunc:n0e};function r0e(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,paddings:o}=s,i=v.sizeFromShape(a),l=[[0,0]];l.push(...o);for(let k=1+a.length;k{let p=[...u];p[i]=d;let h=rp({inputs:{x:r},attrs:{begin:c,size:p},backend:s});return c[i]+=d,h})}var i0e={kernelName:Fi,backendName:"wasm",kernelFunc:o0e},l0e=En(ao),u0e=En(hu),c0e=!0,d0e=Xn(lo,c0e),d6;function p0e(e){d6=e.wasm.cwrap(ho,null,["number","number","number","number"])}function h0e(e){let{backend:t,inputs:n,attrs:s}=e,{alpha:r}=s,{x:a}=n,o=t.dataIdMap.get(a.dataId).id,i=t.makeOutput(a.shape,a.dtype),l=t.dataIdMap.get(i.dataId).id;return d6(o,r,en[a.dtype],l),i}var f0e={kernelName:ho,backendName:"wasm",setupFunc:p0e,kernelFunc:h0e},p6;function m0e(e){p6=e.wasm.cwrap(Oi,null,["number","array","number","array","array","array","array","array","number","number"])}function g0e(e){let{backend:t,inputs:n,attrs:s}=e,{x:r}=n,{begin:a,end:o,strides:i}=s;i==null&&(i=new Array(a.length));let{beginMask:l,endMask:c,ellipsisMask:u,newAxisMask:d,shrinkAxisMask:p}=s,h=N.slice_util.maskToAxes(u);if(h.length>1)throw new Error("Multiple ellipses in slice is not allowed.");if(u!==0&&d!==0)throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");if(u!==0&&p!==0)throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");let f=r.shape.length-a.length,m=N.slice_util.maskToAxes(d),g=r.shape.slice();m.forEach(R=>{a[R]=0,o[R]=1,g.splice(R,0,1)});let A=us({inputs:{x:r},attrs:{shape:g},backend:t}),{begin:y,end:x,strides:b}=N.slice_util.getNormalizedAxes(A.shape,h,f,a,o,i,l,c,u);a=y,o=x,i=b;let w=N.slice_util.maskToAxes(p);w.forEach(R=>{o[R]=a[R]+1,i[R]=1});let k=N.slice_util.computeOutShape(a,o,i),S=k.filter((R,P)=>w.indexOf(P)===-1);if(i.every(R=>R===1)){let R=rp({inputs:{x:A},attrs:{begin:a,size:k},backend:t});t.disposeData(A.dataId);let P=us({inputs:{x:R},attrs:{shape:S},backend:t});return t.disposeData(R.dataId),P}let $=t.makeOutput(S,"float32");if(!S.some(R=>R===0)){let R=t.dataIdMap.get(A.dataId).id,P=new Uint8Array(new Int32Array(v.computeStrides(A.shape)).buffer),T=new Uint8Array(new Int32Array(a).buffer),M=new Uint8Array(new Int32Array(o).buffer),U=new Uint8Array(new Int32Array(i).buffer),H=new Uint8Array(new Int32Array(S).buffer),z=new Uint8Array(new Int32Array(v.computeStrides(S)).buffer),X=t.dataIdMap.get($.dataId).id;p6(R,P,A.shape.length,T,M,U,H,z,S.length,X)}t.disposeData(A.dataId);let F=us({inputs:{x:$},attrs:{shape:S},backend:t});return t.disposeData($.dataId),F}var A0e={kernelName:Oi,backendName:"wasm",setupFunc:m0e,kernelFunc:g0e},y0e=!0,x0e=Xn(uo,y0e),h6;function b0e(e){h6=e.wasm.cwrap(oo,null,["number","number","number","number"])}function v0e(e){let{backend:t,inputs:n,attrs:s}=e,{axis:r,keepDims:a}=s,{x:o}=n,i=t.dataIdMap.get(o.dataId).id,l=i,c=o,{transposed:u,axes:d,originalAxes:p,inputWasTransposed:h}=zo(o,r,t),f=d;if(h){let x=t.dataIdMap.get(u.dataId).id;x!==i&&(c=u,l=x,f=N.getInnerMostAxes(f.length,c.shape.length))}N.assertAxesAreInnerMostDims("sum",f,c.shape.length);let[m,g]=N.computeOutAndReduceShapes(c.shape,f),A=v.sizeFromShape(g),y=t.makeOutput(m,c.dtype);if(v.sizeFromShape(c.shape)!==0){let x=t.dataIdMap.get(y.dataId).id;h6(l,A,en[y.dtype],x)}if(h&&t.disposeData(u.dataId),a){let x=N.expandShapeToKeepDim(y.shape,p);y.shape=x}return y}var w0e={kernelName:oo,backendName:"wasm",setupFunc:b0e,kernelFunc:v0e},k0e=En(Mi),I0e=En(co),f6;function S0e(e){f6=e.wasm.cwrap(qr,null,["number","array","number","array","number","number"])}function C0e(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,a=n.dataIdMap.get(r.dataId).id,{reps:o}=s,i=new Array(r.shape.length);for(let p=0;p{let{x:s}=e,{k:r,sorted:a}=n,o=t.dataIdMap.get(s.dataId).id,i=new Uint8Array(new Int32Array(s.shape).buffer),l=s.shape.slice();l[l.length-1]=r;let c=t.makeOutput(l,s.dtype),u=t.dataIdMap.get(c.dataId).id,d=t.makeOutput(l,"int32"),p=t.dataIdMap.get(d.dataId).id;return m6(o,i,s.shape.length,en[s.dtype],r,a,u,p),[c,d]},R0e={kernelName:zi,backendName:"wasm",setupFunc:N0e,kernelFunc:E0e},g6;function $0e(e){g6=e.wasm.cwrap(Li,null,["number","number","bool","number","number","number","number","number","number","array","number","number","number","number","number"])}function D0e(e){let{backend:t,inputs:n,attrs:s}=e,{image:r,transforms:a}=n,{interpolation:o,fillMode:i,fillValue:l,outputShape:c}=s,[u,d,p,h]=r.shape,[f,m]=c!=null?c:[d,p],g=[u,f,m,h],A=new Uint8Array(new Int32Array(v.computeStrides(r.shape)).buffer),y=t.makeOutput(g,r.dtype),x=t.dataIdMap.get(y.dataId).id,w=t.dataIdMap.get(r.dataId).id,S=t.dataIdMap.get(a.dataId).id,E=o==="nearest"?1:2,$;switch(i){case"constant":$=1;break;case"reflect":$=2;break;case"wrap":$=3;break;case"nearest":$=4;break;default:$=1;break}return g6(w,S,a.shape[0]>1,u,f,m,h,p,d,A,r.shape.length-1,E,$,l,x),y}var _0e={kernelName:Li,backendName:"wasm",setupFunc:$0e,kernelFunc:D0e};function P0e(e){let{inputs:t,backend:n,attrs:s}=e,{value:r}=t,{axis:a}=s;a<0&&(a+=r.shape.length);let o=r.shape[a],i=r.shape.length,l=new Array(i-1),c=0;for(let h=0;h({dataId:h,dtype:f,shape:l}))}var F0e={kernelName:Bi,backendName:"wasm",kernelFunc:P0e};function O0e(e){let{inputs:{x:t},backend:n}=e,s=n.makeOutput(t.shape,t.dtype);return n.typedArrayFromHeap(s).fill(0),s}var M0e={kernelName:Wi,backendName:"wasm",kernelFunc:O0e},z0e=[Bpe,Vpe,Hpe,Qpe,nhe,ahe,lhe,phe,yhe,xhe,bhe,khe,Ihe,The,Rhe,$he,Dhe,Fhe,zhe,Whe,Ghe,Hhe,qhe,Xhe,Khe,Zhe,Qhe,efe,nfe,Lpe,afe,lfe,dfe,ffe,Afe,xfe,vfe,jpe,Ife,Cfe,Nfe,Efe,$fe,Pfe,Ofe,Lfe,Vfe,Hfe,qfe,Zfe,Jfe,Qfe,nme,ame,lme,cme,hme,mme,Ame,t6,vme,Ime,Tme,Eme,$me,Dme,_me,uhe,Ome,Lme,Vme,Gme,Ume,qme,Zme,Qme,e0e,ghe,s0e,a0e,i0e,l0e,u0e,d0e,f0e,A0e,x0e,w0e,k0e,I0e,T0e,R0e,_0e,Zpe,F0e,M0e];for(let e of z0e)Kr(e);var Ax=K();Ax.registerFlag("WASM_HAS_SIMD_SUPPORT",async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,9,1,7,0,65,0,253,15,26,11])));Ax.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT",async()=>{if(Ax.get("IS_NODE"))return!1;try{return new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch(e){return!1}});var L0e='var Module={};function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(" ");console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:text,threadId:Module["_pthread_self"]()})}var err=threadPrintErr;this.alert=threadAlert;Module["instantiateWasm"]=function(info,receiveInstance){var instance=new WebAssembly.Instance(Module["wasmModule"],info);Module["wasmModule"]=null;receiveInstance(instance);return instance.exports};function moduleLoaded(){}this.onmessage=function(e){try{if(e.data.cmd==="load"){Module["wasmModule"]=e.data.wasmModule;Module["wasmMemory"]=e.data.wasmMemory;Module["buffer"]=Module["wasmMemory"].buffer;Module["ENVIRONMENT_IS_PTHREAD"]=true;if(typeof e.data.urlOrBlob==="string"){importScripts(e.data.urlOrBlob)}else{var objectUrl=URL.createObjectURL(e.data.urlOrBlob);importScripts(objectUrl);URL.revokeObjectURL(objectUrl)}WasmBackendModuleThreadedSimd(Module).then(function(instance){Module=instance;moduleLoaded()})}else if(e.data.cmd==="objectTransfer"){Module["PThread"].receiveObjectTransfer(e.data)}else if(e.data.cmd==="run"){Module["__performance_now_clock_drift"]=performance.now()-e.data.time;Module["__emscripten_thread_init"](e.data.threadInfoStruct,0,0);var max=e.data.stackBase;var top=e.data.stackBase+e.data.stackSize;Module["establishStackSpace"](top,max);Module["_emscripten_tls_init"]();Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].setThreadStatus(Module["_pthread_self"](),1);try{var result=Module["invokeEntryPoint"](e.data.start_routine,e.data.arg);if(!Module["getNoExitRuntime"]())Module["PThread"].threadExit(result)}catch(ex){if(ex==="Canceled!"){Module["PThread"].threadCancel()}else if(ex!="unwind"){if(ex instanceof Module["ExitStatus"]){if(Module["getNoExitRuntime"]()){}else{Module["PThread"].threadExit(ex.status)}}else{Module["PThread"].threadExit(-2);throw ex}}}}else if(e.data.cmd==="cancel"){if(Module["_pthread_self"]()){Module["PThread"].threadCancel()}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processThreadQueue"){if(Module["_pthread_self"]()){Module["_emscripten_current_thread_process_queued_calls"]()}}else{err("worker.js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){err("worker.js onmessage() captured an uncaught exception: "+ex);if(ex&&ex.stack)err(ex.stack);throw ex}};if(typeof process==="object"&&typeof process.versions==="object"&&typeof process.versions.node==="string"){self={location:{href:__filename}};var onmessage=this.onmessage;var nodeWorkerThreads=require("worker_threads");global.Worker=nodeWorkerThreads.Worker;var parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",function(data){onmessage({data:data})});var nodeFS=require("fs");var nodeRead=function(filename){return nodeFS.readFileSync(filename,"utf8")};function globalEval(x){global.require=require;global.Module=Module;eval.call(null,x)}importScripts=function(f){globalEval(nodeRead(f))};postMessage=function(msg){parentPort.postMessage(msg)};if(typeof performance==="undefined"){performance={now:function(){return Date.now()}}}}',A6=Qo(BN()),B0e=Qo(WN()),y6=class extends Ll{constructor(e){super();this.wasm=e,this.dataIdNextNumber=1,this.wasm.tfjs.initWithThreadsCount(v6),xx=this.wasm.tfjs.getThreadsCount(),this.dataIdMap=new Dc(this,ss())}write(e,t,n){let s={id:this.dataIdNextNumber++};return this.move(s,e,t,n,1),s}numDataIds(){return this.dataIdMap.numDataIds()}async time(e){let t=v.now();return e(),{kernelMs:v.now()-t}}move(e,t,n,s,r){let a=this.dataIdNextNumber++;if(s==="string"){let c=t;this.dataIdMap.set(e,{id:a,stringBytes:c,shape:n,dtype:s,memoryOffset:null,refCount:r});return}let o=v.sizeFromShape(n),i=o*v.bytesPerElement(s),l=this.wasm._malloc(i);this.dataIdMap.set(e,{id:a,memoryOffset:l,shape:n,dtype:s,refCount:r}),this.wasm.tfjs.registerTensor(a,o,l),t!=null&&this.wasm.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,i),l)}async read(e){return this.readSync(e)}readSync(e){let{memoryOffset:t,dtype:n,shape:s,stringBytes:r}=this.dataIdMap.get(e);if(n==="string")return r;let a=this.wasm.HEAPU8.slice(t,t+v.sizeFromShape(s)*v.bytesPerElement(n));return U0e(a.buffer,n)}disposeData(e,t=!1){if(this.dataIdMap.has(e)){let n=this.dataIdMap.get(e);if(n.refCount--,!t&&n.refCount>0)return!1;this.wasm._free(n.memoryOffset),this.wasm.tfjs.disposeData(n.id),this.dataIdMap.delete(e)}return!0}refCount(e){return this.dataIdMap.has(e)?this.dataIdMap.get(e).refCount:0}incRef(e){let t=this.dataIdMap.get(e);t!=null&&t.refCount++}floatPrecision(){return 32}getMemoryOffset(e){return this.dataIdMap.get(e).memoryOffset}dispose(){this.wasm.tfjs.dispose(),"PThread"in this.wasm&&this.wasm.PThread.terminateAllThreads(),this.wasm=null}memory(){return{unreliable:!1}}makeOutput(e,t,n){let s;if(n==null)s=this.write(null,e,t);else{let r=this.dataIdNextNumber++;s={id:r},this.dataIdMap.set(s,{id:r,memoryOffset:n,shape:e,dtype:t,refCount:1});let a=v.sizeFromShape(e);this.wasm.tfjs.registerTensor(r,a,n)}return{dataId:s,shape:e,dtype:t}}typedArrayFromHeap({shape:e,dtype:t,dataId:n}){let s=this.wasm.HEAPU8.buffer,{memoryOffset:r}=this.dataIdMap.get(n),a=v.sizeFromShape(e);switch(t){case"float32":return new Float32Array(s,r,a);case"int32":return new Int32Array(s,r,a);case"bool":return new Uint8Array(s,r,a);default:throw new Error(`Unknown dtype ${t}`)}}};function W0e(e){return(t,n)=>(v.fetch(e,{credentials:"same-origin"}).then(s=>{s.ok||t.env.a(`failed to load wasm binary file at '${e}'`),s.arrayBuffer().then(r=>{WebAssembly.instantiate(r,t).then(a=>{n(a.instance,a.module)})})}),{})}function x6(e,t,n){if(zm!=null)return zm;let s="tfjs-backend-wasm.wasm";return e&&t?s="tfjs-backend-wasm-threaded-simd.wasm":e&&(s="tfjs-backend-wasm-simd.wasm"),ip!=null&&ip[s]!=null?ip[s]:n+s}async function V0e(){let[e,t]=await Promise.all([K().getAsync("WASM_HAS_SIMD_SUPPORT"),K().getAsync("WASM_HAS_MULTITHREAD_SUPPORT")]);return new Promise((n,s)=>{let r={};r.locateFile=(i,l)=>{if(i.endsWith(".worker.js")){let c=L0e,u=new Blob([c],{type:"application/javascript"});return URL.createObjectURL(u)}return i.endsWith(".wasm")?x6(e,t,op!=null?op:l):l+i},yx&&(r.instantiateWasm=W0e(x6(e,t,op!=null?op:"")));let a=!1;r.onAbort=()=>{if(a||lp)return;lp=!0,s({message:"Make sure the server can serve the `.wasm` file relative to the bundled js file. For more details see https://github.com/tensorflow/tfjs/blob/master/tfjs-backend-wasm/README.md#using-bundlers"})};let o;t&&e&&zm==null?(r.mainScriptUrlOrBlob=new Blob(["var WasmBackendModuleThreadedSimd = "+A6.default.toString()],{type:"text/javascript"}),o=(0,A6.default)(r)):o=(0,B0e.default)(r),o.then(i=>{a=!0,lp=!1;let l=null;i.tfjs={init:i.cwrap("init",null,[]),initWithThreadsCount:i.cwrap("init_with_threads_count",null,["number"]),getThreadsCount:i.cwrap("get_threads_count","number",[]),registerTensor:i.cwrap("register_tensor",null,["number","number","number"]),disposeData:i.cwrap("dispose_data",l,["number"]),dispose:i.cwrap("dispose",l,[])},n({wasm:i})})})}function U0e(e,t){switch(t){case"float32":return new Float32Array(e);case"int32":return new Int32Array(e);case"bool":return new Uint8Array(e);default:throw new Error(`Unknown dtype ${t}`)}}var G0e=["tfjs-backend-wasm.wasm","tfjs-backend-wasm-simd.wasm","tfjs-backend-wasm-threaded-simd.wasm"],zm=null,op=null,ip={},lp=!1,yx=!1;function H0e(e,t=!1){if(I2("setWasmPath has been deprecated in favor of setWasmPaths and will be removed in a future release."),lp)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPath()` before you call `tf.setBackend()` or `tf.ready()`");zm=e,yx=t}function b6(e,t=!1){if(lp)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPaths()` before you call `tf.setBackend()` or `tf.ready()`");if(typeof e=="string")op=e;else{ip=e;let n=G0e.filter(s=>ip[s]==null);if(n.length>0)throw new Error(`There were no entries found for the following binaries: ${n.join(",")}. Please either call setWasmPaths with a map providing a path for each binary, or with a string indicating the directory where all the binaries can be found.`)}yx=t}var v6=-1,xx=-1;function j0e(e){v6=e}function q0e(){if(xx===-1)throw new Error("WASM backend not initialized.");return xx}var X0e="0.0.0",K0e=2;Ki("wasm",async()=>{let{wasm:e}=await V0e();return new y6(e)},K0e);var Lo="3.10.0-20211023",w6={tfjs:Lo,"tfjs-core":Lo,"tfjs-data":Lo,"tfjs-layers":Lo,"tfjs-converter":Lo,"tfjs-backend-cpu":Lo,"tfjs-backend-webgl":Lo,"tfjs-backend-wasm":Lo},up=w6["tfjs-core"];var k6=` precision highp float; attribute vec2 pos; attribute vec2 uv; @@ -7077,8 +7077,8 @@ return a / b;`,lre=` c31 * m[6] + c32 * m[7] + c33 * m[8]; gl_FragColor.a = c22.a; } -`;var bx=(e,t,n)=>{let s=new RegExp("\\b"+t+" \\w+ (\\w+)","ig");e.replace(s,(r,a)=>(n[a]=0,r))},E6=class{constructor(t,n,s){pe(this,"uniform",{});pe(this,"attribute",{});pe(this,"gl");pe(this,"id");pe(this,"compile",(t,n)=>{let s=this.gl.createShader(n);if(this.gl.shaderSource(s,t),this.gl.compileShader(s),!this.gl.getShaderParameter(s,this.gl.COMPILE_STATUS))throw new Error(`filter: gl compile failed: ${this.gl.getShaderInfoLog(s)}`);return s});this.gl=t;let r=this.compile(n,this.gl.VERTEX_SHADER),a=this.compile(s,this.gl.FRAGMENT_SHADER);if(this.id=this.gl.createProgram(),this.gl.attachShader(this.id,r),this.gl.attachShader(this.id,a),this.gl.linkProgram(this.id),!this.gl.getProgramParameter(this.id,this.gl.LINK_STATUS))throw new Error(`filter: gl link failed: ${this.gl.getProgramInfoLog(this.id)}`);this.gl.useProgram(this.id),bx(n,"attribute",this.attribute);for(let o in this.attribute)this.attribute[o]=this.gl.getAttribLocation(this.id,o);bx(n,"uniform",this.uniform),bx(s,"uniform",this.uniform);for(let o in this.uniform)this.uniform[o]=this.gl.getUniformLocation(this.id,o)}};function R6(){let e=0,t=null,n=!1,s=-1,r=[null,null],a=[],o=null,i=null,l=Kn(100,100),c={},u={INTERMEDIATE:1},d=l.getContext("webgl");if(!d)throw new Error("filter: cannot get webgl context");function p(y,x){if(!(y===l.width&&x===l.height)){if(l.width=y,l.height=x,!o){let b=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,-1,1,0,0,1,-1,1,1,1,1,1,0]);o=d.createBuffer(),d.bindBuffer(d.ARRAY_BUFFER,o),d.bufferData(d.ARRAY_BUFFER,b,d.STATIC_DRAW),d.pixelStorei(d.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!0)}d.viewport(0,0,l.width,l.height),r=[null,null]}}function h(y,x){let b=d.createFramebuffer();d.bindFramebuffer(d.FRAMEBUFFER,b);let w=d.createRenderbuffer();d.bindRenderbuffer(d.RENDERBUFFER,w);let k=d.createTexture();return d.bindTexture(d.TEXTURE_2D,k),d.texImage2D(d.TEXTURE_2D,0,d.RGBA,y,x,0,d.RGBA,d.UNSIGNED_BYTE,null),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_MAG_FILTER,d.LINEAR),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_MIN_FILTER,d.LINEAR),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_WRAP_S,d.CLAMP_TO_EDGE),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_WRAP_T,d.CLAMP_TO_EDGE),d.framebufferTexture2D(d.FRAMEBUFFER,d.COLOR_ATTACHMENT0,d.TEXTURE_2D,k,0),d.bindTexture(d.TEXTURE_2D,null),d.bindFramebuffer(d.FRAMEBUFFER,null),{fbo:b,texture:k}}function f(y){return r[y]=r[y]||h(l.width,l.height),r[y]}function m(y=0){var k,S;if(!i)return;let x=null,b=null,w=!1;e===0?x=t:x=((k=f(s))==null?void 0:k.texture)||null,e++,n&&!(y&u.INTERMEDIATE)?(b=null,w=e%2==0):(s=(s+1)%2,b=((S=f(s))==null?void 0:S.fbo)||null),d.bindTexture(d.TEXTURE_2D,x),d.bindFramebuffer(d.FRAMEBUFFER,b),d.uniform1f(i.uniform.flipY,w?-1:1),d.drawArrays(d.TRIANGLES,0,6)}function g(y){if(c[y])return i=c[y],d.useProgram((i==null?void 0:i.id)||null),i;i=new E6(d,k6,y);let x=Float32Array.BYTES_PER_ELEMENT,b=4*x;return d.enableVertexAttribArray(i.attribute.pos),d.vertexAttribPointer(i.attribute.pos,2,d.FLOAT,!1,b,0*x),d.enableVertexAttribArray(i.attribute.uv),d.vertexAttribPointer(i.attribute.uv,2,d.FLOAT,!1,b,2*x),c[y]=i,i}let A={colorMatrix:y=>{let x=new Float32Array(y);x[4]/=255,x[9]/=255,x[14]/=255,x[19]/=255;let b=x[18]===1&&x[3]===0&&x[8]===0&&x[13]===0&&x[15]===0&&x[16]===0&&x[17]===0&&x[19]===0?S6:I6,w=g(b);d.uniform1fv(w==null?void 0:w.uniform.m,x),m()},brightness:y=>{let x=(y||0)+1;A.colorMatrix([x,0,0,0,0,0,x,0,0,0,0,0,x,0,0,0,0,0,1,0])},saturation:y=>{let x=(y||0)*2/3+1,b=(x-1)*-.5;A.colorMatrix([x,b,b,0,0,b,x,b,0,0,b,b,x,0,0,0,0,0,1,0])},desaturate:()=>{A.saturation(-1)},contrast:y=>{let x=(y||0)+1,b=-128*(x-1);A.colorMatrix([x,0,0,0,b,0,x,0,0,b,0,0,x,0,b,0,0,0,1,0])},negative:()=>{A.contrast(-2)},hue:y=>{y=(y||0)/180*Math.PI;let x=Math.cos(y),b=Math.sin(y),w=.213,k=.715,S=.072;A.colorMatrix([w+x*(1-w)+b*-w,k+x*-k+b*-k,S+x*-S+b*(1-S),0,0,w+x*-w+b*.143,k+x*(1-k)+b*.14,S+x*-S+b*-.283,0,0,w+x*-w+b*-(1-w),k+x*-k+b*k,S+x*(1-S)+b*S,0,0,0,0,0,1,0])},desaturateLuminance:()=>{A.colorMatrix([.2764723,.929708,.0938197,0,-37.1,.2764723,.929708,.0938197,0,-37.1,.2764723,.929708,.0938197,0,-37.1,0,0,0,1,0])},sepia:()=>{A.colorMatrix([.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0])},brownie:()=>{A.colorMatrix([.5997023498159715,.34553243048391263,-.2708298674538042,0,47.43192855600873,-.037703249837783157,.8609577587992641,.15059552388459913,0,-36.96841498319127,.24113635128153335,-.07441037908422492,.44972182064877153,0,-7.562075277591283,0,0,0,1,0])},vintagePinhole:()=>{A.colorMatrix([.6279345635605994,.3202183420819367,-.03965408211312453,0,9.651285835294123,.02578397704808868,.6441188644374771,.03259127616149294,0,7.462829176470591,.0466055556782719,-.0851232987247891,.5241648018700465,0,5.159190588235296,0,0,0,1,0])},kodachrome:()=>{A.colorMatrix([1.1285582396593525,-.3967382283601348,-.03992559172921793,0,63.72958762196502,-.16404339962244616,1.0835251566291304,-.05498805115633132,0,24.732407896706203,-.16786010706155763,-.5603416277695248,1.6014850761964943,0,35.62982807460946,0,0,0,1,0])},technicolor:()=>{A.colorMatrix([1.9125277891456083,-.8545344976951645,-.09155508482755585,0,11.793603434377337,-.3087833385928097,1.7658908555458428,-.10601743074722245,0,-70.35205161461398,-.231103377548616,-.7501899197440212,1.847597816108189,0,30.950940869491138,0,0,0,1,0])},polaroid:()=>{A.colorMatrix([1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0])},shiftToBGR:()=>{A.colorMatrix([0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0])},convolution:y=>{let x=new Float32Array(y),b=1/l.width,w=1/l.height,k=g(N6);d.uniform1fv(k==null?void 0:k.uniform.m,x),d.uniform2f(k==null?void 0:k.uniform.px,b,w),m()},detectEdges:()=>{A.convolution.call(this,[0,1,0,1,-4,1,0,1,0])},sobelX:()=>{A.convolution.call(this,[-1,0,1,-2,0,2,-1,0,1])},sobelY:()=>{A.convolution.call(this,[-1,-2,-1,0,0,0,1,2,1])},sharpen:y=>{let x=y||1;A.convolution.call(this,[0,-1*x,0,-1*x,1+4*x,-1*x,0,-1*x,0])},emboss:y=>{let x=y||1;A.convolution.call(this,[-2*x,-1*x,0,-1*x,1,1*x,0,1*x,2*x])},blur:y=>{let x=y/7/l.width,b=y/7/l.height,w=g(T6);d.uniform2f(w==null?void 0:w.uniform.px,0,b),m(u.INTERMEDIATE),d.uniform2f(w==null?void 0:w.uniform.px,x,0),m()},pixelate:y=>{let x=y/l.width,b=y/l.height,w=g(C6);d.uniform2f(w==null?void 0:w.uniform.size,x,b),m()}};this.add=function(y){let x=Array.prototype.slice.call(arguments,1),b=A[y];a.push({func:b,args:x})},this.reset=function(){a=[]},this.get=function(){return a},this.apply=function(y){p(y.width,y.height),e=0,t||(t=d.createTexture()),d.bindTexture(d.TEXTURE_2D,t),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_WRAP_S,d.CLAMP_TO_EDGE),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_WRAP_T,d.CLAMP_TO_EDGE),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_MIN_FILTER,d.NEAREST),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_MAG_FILTER,d.NEAREST),d.texImage2D(d.TEXTURE_2D,0,d.RGBA,d.RGBA,d.UNSIGNED_BYTE,y);for(let x=0;x0,r=e.naturalHeight||e.videoHeight||e.height||e.shape&&e.shape[2]>0;if(!s||!r)return t.debug&&ae("cannot determine input dimensions"),{tensor:null,canvas:lt};let a=s,o=r;if(a>Lm&&(a=Lm,o=Math.trunc(a*r/s)),o>Lm&&(o=Lm,a=Math.trunc(o*s/r)),(t.filter.width||0)>0?a=t.filter.width:(t.filter.height||0)>0&&(a=s*((t.filter.height||0)/r)),(t.filter.height||0)>0?o=t.filter.height:(t.filter.width||0)>0&&(o=r*((t.filter.width||0)/s)),!a||!o)throw new Error("input cannot determine dimension");(!lt||(lt==null?void 0:lt.width)!==a||(lt==null?void 0:lt.height)!==o)&&(lt=Kn(a,o));let i=lt.getContext("2d");if(typeof ImageData!="undefined"&&e instanceof ImageData?i.putImageData(e,0,0):t.filter.flip&&typeof i.translate!="undefined"?(i.translate(s,0),i.scale(-1,1),i.drawImage(e,0,0,s,r,0,0,lt==null?void 0:lt.width,lt==null?void 0:lt.height),i.setTransform(1,0,0,1,0,0)):i.drawImage(e,0,0,s,r,0,0,lt==null?void 0:lt.width,lt==null?void 0:lt.height),(!qt||lt.width!==qt.width||(lt==null?void 0:lt.height)!==(qt==null?void 0:qt.height))&&(qt=Kn(lt.width,lt.height)),t.filter.enabled&&be.webgl.supported){if(_t||(_t=be.browser?new R6:null),be.filter=!!_t,!_t)return{tensor:null,canvas:lt};_t.reset(),t.filter.brightness!==0&&_t.add("brightness",t.filter.brightness),t.filter.contrast!==0&&_t.add("contrast",t.filter.contrast),t.filter.sharpness!==0&&_t.add("sharpen",t.filter.sharpness),t.filter.blur!==0&&_t.add("blur",t.filter.blur),t.filter.saturation!==0&&_t.add("saturation",t.filter.saturation),t.filter.hue!==0&&_t.add("hue",t.filter.hue),t.filter.negative&&_t.add("negative"),t.filter.sepia&&_t.add("sepia"),t.filter.vintage&&_t.add("brownie"),t.filter.sepia&&_t.add("sepia"),t.filter.kodachrome&&_t.add("kodachrome"),t.filter.technicolor&&_t.add("technicolor"),t.filter.polaroid&&_t.add("polaroid"),t.filter.pixelate!==0&&_t.add("pixelate",t.filter.pixelate),_t.get()>0?qt=_t.apply(lt):qt=_t.draw(lt)}else vx(lt,qt),_t&&(_t=null),be.filter=!!_t;if(!n)return{tensor:null,canvas:qt};if(!qt)throw new Error("cannot create output canvas");let l,c=3;if(typeof ImageData!="undefined"&&e instanceof ImageData||e.data&&e.width&&e.height)if(be.browser&&Gs)l=Gs?Gs.fromPixels(e):null;else{c=e.data.length/e.height/e.width;let p=new Uint8Array(e.data.buffer);l=Gt(p,[e.height,e.width,c],"int32")}else if((!Bo||qt.width!==Bo.width||(qt==null?void 0:qt.height)!==(Bo==null?void 0:Bo.height))&&(Bo=Kn(qt.width,qt.height)),Gs&&be.browser)t.backend==="webgl"||t.backend==="humangl"||t.backend==="webgpu"?l=Gs.fromPixels(qt):(Bo=vx(qt),l=Gs.fromPixels(Bo));else{let f=vx(qt).getContext("2d").getImageData(0,0,a,o);c=f.data.length/a/o;let m=new Uint8Array(f.data.buffer);l=Gt(m,[a,o,c])}if(c===4){let p=Ru(l,[0,0,0],[-1,-1,3]);Q(l),l=p}if(!l)throw new Error("cannot create tensor from input");let u=de(l,"float32"),d=Kt(u,0);return Q([l,u]),{tensor:d,canvas:t.filter.return?qt:null}}}var wx=0,kx=1,Ix=0,Z0e=async e=>{let t=48,n=$e.resizeBilinear(e,[Math.trunc((e.shape[1]||1)/t),Math.trunc((e.shape[2]||1)/t)]),s=async()=>{let o=Ie(n),i=await o.data();return Q(o),i[0]},r=async()=>{let o=await n.data(),i=0;for(let l=0;l10*e.cacheSensitivity?0:s,r=r&&kx>0,r}var Sx=class{constructor(){pe(this,"browser");pe(this,"node");pe(this,"worker");pe(this,"platform","");pe(this,"agent","");pe(this,"backends",[]);pe(this,"initial");pe(this,"filter");pe(this,"tfjs");pe(this,"offscreen");pe(this,"wasm",{supported:void 0,backend:void 0,simd:void 0,multithread:void 0});pe(this,"webgl",{supported:void 0,backend:void 0,version:void 0,renderer:void 0});pe(this,"webgpu",{supported:void 0,backend:void 0,adapter:void 0});pe(this,"cpu",{model:void 0,flags:[]});pe(this,"kernels",[]);pe(this,"Canvas");pe(this,"Image");pe(this,"ImageData");if(this.browser=typeof navigator!="undefined",this.node=typeof process!="undefined",this.tfjs={version:up},this.offscreen=typeof OffscreenCanvas!="undefined",this.initial=!0,this.worker=this.browser&&this.offscreen?typeof WorkerGlobalScope!="undefined":void 0,typeof navigator!="undefined"){let t=navigator.userAgent.match(/\(([^()]+)\)/g);if(t&&t[0]){let n=t[0].match(/\(([^()]+)\)/g);this.platform=n&&n[0]?n[0].replace(/\(|\)/g,""):"",this.agent=navigator.userAgent.replace(t[0],""),this.platform[1]&&(this.agent=this.agent.replace(t[1],"")),this.agent=this.agent.replace(/ /g," ")}}else typeof process!="undefined"&&(this.platform=`${process.platform} ${process.arch}`,this.agent=`NodeJS ${process.version}`)}async updateBackend(){var s;this.backends=Object.keys(ss().registryFactory),this.wasm.supported=typeof WebAssembly!="undefined",this.wasm.backend=this.backends.includes("wasm"),this.wasm.supported&&this.wasm.backend&&ir()==="wasm"&&(this.wasm.simd=await K().getAsync("WASM_HAS_SIMD_SUPPORT"),this.wasm.multithread=await K().getAsync("WASM_HAS_MULTITHREAD_SUPPORT"));let t=Kn(100,100),n=t?t.getContext("webgl2"):void 0;if(this.webgl.supported=typeof n!="undefined",this.webgl.backend=this.backends.includes("webgl"),this.webgl.supported&&this.webgl.backend&&(ir()==="webgl"||ir()==="humangl")){let r=Tr().gpgpu!=="undefined"?await Tr().getGPGPUContext().gl:null;r&&(this.webgl.version=r.getParameter(r.VERSION),this.webgl.renderer=r.getParameter(r.RENDERER))}this.webgpu.supported=this.browser&&typeof navigator.gpu!="undefined",this.webgpu.backend=this.backends.includes("webgpu"),this.webgpu.supported&&(this.webgpu.adapter=(s=await navigator.gpu.requestAdapter())==null?void 0:s.name),this.kernels=Xr(ir()).map(r=>r.kernelName.toLowerCase())}async updateCPU(){var n;let t={model:"",flags:[]};if(this.node&&((n=this.platform)==null?void 0:n.startsWith("linux"))){let s=xa("fs");try{let r=s.readFileSync("/proc/cpuinfo").toString();for(let a of r.split(` -`))a.startsWith("model name")&&(t.model=a.match(/:(.*)/g)[0].replace(":","").trim()),a.startsWith("flags")&&(t.flags=a.match(/:(.*)/g)[0].replace(":","").trim().split(" ").sort())}catch(r){}}this.cpu?this.cpu=t:Object.defineProperty(this,"cpu",{value:t})}},be=new Sx;var Cx="2.4.0";var Wo;var m2e=Number.MAX_SAFE_INTEGER;async function D6(e){return be.initial&&(Wo=null),Wo?e.debug&&ae("cached model:",Wo.modelUrl):(Wo=await st(at(e.modelBasePath,e.face.agegenderrace.modelPath)),!Wo||!Wo.modelUrl?ae("load model failed:",e.face.agegenderrace.modelPath):e.debug&&ae("load model:",Wo.modelUrl)),Wo}var cn,Bm=[],Tx=Number.MAX_SAFE_INTEGER,_6=0,P6=0;async function F6(e){var t,n;return be.initial&&(cn=null),cn?e.debug&&ae("cached model:",cn.modelUrl):(cn=await st(at(e.modelBasePath,((t=e.face.antispoof)==null?void 0:t.modelPath)||"")),!cn||!cn.modelUrl?ae("load model failed:",(n=e.face.antispoof)==null?void 0:n.modelPath):e.debug&&ae("load model:",cn.modelUrl)),cn}async function Nx(e,t,n,s){var r,a;return cn?Tx<(((r=t.face.antispoof)==null?void 0:r.skipFrames)||0)&&(((a=t.face.antispoof)==null?void 0:a.skipTime)||0)<=Ae()-P6&&t.skipFrame&&_6===s&&Bm[n]?(Tx++,Bm[n]):(Tx=0,new Promise(async o=>{let i=$e.resizeBilinear(e,[(cn==null?void 0:cn.inputs[0].shape)?cn.inputs[0].shape[2]:0,(cn==null?void 0:cn.inputs[0].shape)?cn.inputs[0].shape[1]:0],!1),l=cn==null?void 0:cn.predict(i),c=(await l.data())[0];Bm[n]=Math.round(100*c)/100,_6=s,P6=Ae(),Q([i,l]),o(Bm[n])})):null}var Lr={silhouette:[10,338,297,332,284,251,389,356,454,323,361,288,397,365,379,378,400,377,152,148,176,149,150,136,172,58,132,93,234,127,162,21,54,103,67,109],lipsUpperOuter:[61,185,40,39,37,0,267,269,270,409,291],lipsLowerOuter:[146,91,181,84,17,314,405,321,375,291],lipsUpperInner:[78,191,80,81,82,13,312,311,310,415,308],lipsLowerInner:[78,95,88,178,87,14,317,402,318,324,308],rightEyeUpper0:[246,161,160,159,158,157,173],rightEyeLower0:[33,7,163,144,145,153,154,155,133],rightEyeUpper1:[247,30,29,27,28,56,190],rightEyeLower1:[130,25,110,24,23,22,26,112,243],rightEyeUpper2:[113,225,224,223,222,221,189],rightEyeLower2:[226,31,228,229,230,231,232,233,244],rightEyeLower3:[143,111,117,118,119,120,121,128,245],rightEyebrowUpper:[156,70,63,105,66,107,55,193],rightEyebrowLower:[35,124,46,53,52,65],rightEyeIris:[473,474,475,476,477],leftEyeUpper0:[466,388,387,386,385,384,398],leftEyeLower0:[263,249,390,373,374,380,381,382,362],leftEyeUpper1:[467,260,259,257,258,286,414],leftEyeLower1:[359,255,339,254,253,252,256,341,463],leftEyeUpper2:[342,445,444,443,442,441,413],leftEyeLower2:[446,261,448,449,450,451,452,453,464],leftEyeLower3:[372,340,346,347,348,349,350,357,465],leftEyebrowUpper:[383,300,293,334,296,336,285,417],leftEyebrowLower:[265,353,276,283,282,295],leftEyeIris:[468,469,470,471,472],midwayBetweenEyes:[168],noseTip:[1],noseBottom:[2],noseRightCorner:[98],noseLeftCorner:[327],rightCheek:[205],leftCheek:[425]},Ex={count:468,mouth:13,symmetryLine:[13,Lr.midwayBetweenEyes[0]]},cp={leftEye:0,rightEye:1,nose:2,mouth:3,leftEar:4,rightEar:5,symmetryLine:[3,2]},Rx=[{key:"EyeUpper0",indices:[9,10,11,12,13,14,15]},{key:"EyeUpper1",indices:[25,26,27,28,29,30,31]},{key:"EyeUpper2",indices:[41,42,43,44,45,46,47]},{key:"EyeLower0",indices:[0,1,2,3,4,5,6,7,8]},{key:"EyeLower1",indices:[16,17,18,19,20,21,22,23,24]},{key:"EyeLower2",indices:[32,33,34,35,36,37,38,39,40]},{key:"EyeLower3",indices:[54,55,56,57,58,59,60,61,62]}],dp=[[.499976992607117,.652534008026123],[.500025987625122,.547487020492554],[.499974012374878,.602371990680695],[.482113003730774,.471979022026062],[.500150978565216,.527155995368958],[.499909996986389,.498252987861633],[.499523013830185,.40106201171875],[.289712011814117,.380764007568359],[.499954998493195,.312398016452789],[.499987006187439,.269918978214264],[.500023007392883,.107050001621246],[.500023007392883,.666234016418457],[.5000159740448,.679224014282227],[.500023007392883,.692348003387451],[.499976992607117,.695277988910675],[.499976992607117,.70593398809433],[.499976992607117,.719385027885437],[.499976992607117,.737019002437592],[.499967992305756,.781370997428894],[.499816000461578,.562981009483337],[.473773002624512,.573909997940063],[.104906998574734,.254140973091125],[.365929991006851,.409575998783112],[.338757991790771,.41302502155304],[.311120003461838,.409460008144379],[.274657994508743,.389131009578705],[.393361985683441,.403706014156342],[.345234006643295,.344011008739471],[.370094001293182,.346076011657715],[.319321990013123,.347265005111694],[.297903001308441,.353591024875641],[.24779200553894,.410809993743896],[.396889001131058,.842755019664764],[.280097991228104,.375599980354309],[.106310002505779,.399955987930298],[.2099249958992,.391353011131287],[.355807989835739,.534406006336212],[.471751004457474,.65040397644043],[.474155008792877,.680191993713379],[.439785003662109,.657229006290436],[.414617002010345,.66654098033905],[.450374007225037,.680860996246338],[.428770989179611,.682690978050232],[.374971002340317,.727805018424988],[.486716985702515,.547628998756409],[.485300987958908,.527395009994507],[.257764995098114,.314490020275116],[.401223003864288,.455172002315521],[.429818987846375,.548614978790283],[.421351999044418,.533740997314453],[.276895999908447,.532056987285614],[.483370006084442,.499586999416351],[.33721199631691,.282882988452911],[.296391993761063,.293242990970612],[.169294998049736,.193813979625702],[.447580009698868,.302609980106354],[.392390012741089,.353887975215912],[.354490011930466,.696784019470215],[.067304998636246,.730105042457581],[.442739009857178,.572826027870178],[.457098007202148,.584792017936707],[.381974011659622,.694710969924927],[.392388999462128,.694203019142151],[.277076005935669,.271932005882263],[.422551989555359,.563233017921448],[.385919004678726,.281364023685455],[.383103013038635,.255840003490448],[.331431001424789,.119714021682739],[.229923993349075,.232002973556519],[.364500999450684,.189113974571228],[.229622006416321,.299540996551514],[.173287004232407,.278747975826263],[.472878992557526,.666198015213013],[.446828007698059,.668527007102966],[.422762006521225,.673889994621277],[.445307999849319,.580065965652466],[.388103008270264,.693961024284363],[.403039008378983,.706539988517761],[.403629004955292,.693953037261963],[.460041999816895,.557139039039612],[.431158006191254,.692366003990173],[.452181994915009,.692366003990173],[.475387006998062,.692366003990173],[.465828001499176,.779190003871918],[.472328990697861,.736225962638855],[.473087012767792,.717857003211975],[.473122000694275,.704625964164734],[.473033010959625,.695277988910675],[.427942007780075,.695277988910675],[.426479011774063,.703539967536926],[.423162013292313,.711845993995667],[.4183090031147,.720062971115112],[.390094995498657,.639572978019714],[.013953999616206,.560034036636353],[.499913990497589,.58014702796936],[.413199990987778,.69539999961853],[.409626007080078,.701822996139526],[.468080013990402,.601534962654114],[.422728985548019,.585985004901886],[.463079988956451,.593783974647522],[.37211999297142,.47341400384903],[.334562003612518,.496073007583618],[.411671012639999,.546965003013611],[.242175996303558,.14767599105835],[.290776997804642,.201445996761322],[.327338010072708,.256527006626129],[.399509996175766,.748921036720276],[.441727995872498,.261676013469696],[.429764986038208,.187834024429321],[.412198007106781,.108901023864746],[.288955003023148,.398952007293701],[.218936994671822,.435410976409912],[.41278201341629,.398970007896423],[.257135003805161,.355440020561218],[.427684992551804,.437960982322693],[.448339998722076,.536936044692993],[.178560003638268,.45755398273468],[.247308000922203,.457193970680237],[.286267012357712,.467674970626831],[.332827985286713,.460712015628815],[.368755996227264,.447206974029541],[.398963987827301,.432654976844788],[.476410001516342,.405806005001068],[.189241006970406,.523923993110657],[.228962004184723,.348950982093811],[.490725994110107,.562400996685028],[.404670000076294,.485132992267609],[.019469000399113,.401564002037048],[.426243007183075,.420431017875671],[.396993011236191,.548797011375427],[.266469985246658,.376977026462555],[.439121007919312,.51895797252655],[.032313998788595,.644356966018677],[.419054001569748,.387154996395111],[.462783008813858,.505746960639954],[.238978996872902,.779744982719421],[.198220998048782,.831938028335571],[.107550002634525,.540755033493042],[.183610007166862,.740257024765015],[.134409993886948,.333683013916016],[.385764002799988,.883153975009918],[.490967005491257,.579378008842468],[.382384985685349,.508572995662689],[.174399003386497,.397670984268188],[.318785011768341,.39623498916626],[.343364000320435,.400596976280212],[.396100014448166,.710216999053955],[.187885001301765,.588537991046906],[.430987000465393,.944064974784851],[.318993002176285,.898285031318665],[.266247987747192,.869701027870178],[.500023007392883,.190576016902924],[.499976992607117,.954452991485596],[.366169989109039,.398822009563446],[.393207013607025,.39553701877594],[.410373002290726,.391080021858215],[.194993004202843,.342101991176605],[.388664990663528,.362284004688263],[.365961998701096,.355970978736877],[.343364000320435,.355356991291046],[.318785011768341,.35834002494812],[.301414996385574,.363156020641327],[.058132998645306,.319076001644135],[.301414996385574,.387449026107788],[.499987989664078,.618434011936188],[.415838003158569,.624195992946625],[.445681989192963,.566076993942261],[.465844005346298,.620640993118286],[.49992299079895,.351523995399475],[.288718998432159,.819945991039276],[.335278987884521,.852819979190826],[.440512001514435,.902418971061707],[.128294005990028,.791940987110138],[.408771991729736,.373893976211548],[.455606997013092,.451801002025604],[.499877005815506,.908990025520325],[.375436991453171,.924192011356354],[.11421000212431,.615022003650665],[.448662012815475,.695277988910675],[.4480200111866,.704632043838501],[.447111994028091,.715808033943176],[.444831997156143,.730794012546539],[.430011987686157,.766808986663818],[.406787008047104,.685672998428345],[.400738000869751,.681069016456604],[.392399996519089,.677703022956848],[.367855995893478,.663918972015381],[.247923001646996,.601333022117615],[.452769994735718,.420849978923798],[.43639200925827,.359887003898621],[.416164010763168,.368713974952698],[.413385987281799,.692366003990173],[.228018000721931,.683571994304657],[.468268007040024,.352671027183533],[.411361992359161,.804327011108398],[.499989002943039,.469825029373169],[.479153990745544,.442654013633728],[.499974012374878,.439637005329132],[.432112008333206,.493588984012604],[.499886006116867,.866917014122009],[.49991300702095,.821729004383087],[.456548988819122,.819200992584229],[.344549000263214,.745438992977142],[.37890899181366,.574010014533997],[.374292999505997,.780184984207153],[.319687992334366,.570737957954407],[.357154995203018,.604269981384277],[.295284003019333,.621580958366394],[.447750002145767,.862477004528046],[.410986006259918,.508723020553589],[.31395098567009,.775308012962341],[.354128003120422,.812552988529205],[.324548006057739,.703992962837219],[.189096003770828,.646299958229065],[.279776990413666,.71465802192688],[.1338230073452,.682700991630554],[.336768001317978,.644733011722565],[.429883986711502,.466521978378296],[.455527991056442,.548622965812683],[.437114000320435,.558896005153656],[.467287987470627,.529924988746643],[.414712011814117,.335219979286194],[.37704598903656,.322777986526489],[.344107985496521,.320150971412659],[.312875986099243,.32233202457428],[.283526003360748,.333190023899078],[.241245999932289,.382785975933075],[.102986000478268,.468762993812561],[.267612010240555,.424560010433197],[.297879010438919,.433175981044769],[.333433985710144,.433878004550934],[.366427004337311,.426115989685059],[.396012008190155,.416696012020111],[.420121014118195,.41022801399231],[.007561000064015,.480777025222778],[.432949006557465,.569517970085144],[.458638995885849,.479089021682739],[.473466008901596,.545744001865387],[.476087987422943,.563830018043518],[.468472003936768,.555056989192963],[.433990985155106,.582361996173859],[.483518004417419,.562983989715576],[.482482999563217,.57784903049469],[.42645001411438,.389798998832703],[.438998997211456,.39649498462677],[.450067013502121,.400434017181396],[.289712011814117,.368252992630005],[.276670008897781,.363372981548309],[.517862021923065,.471948027610779],[.710287988185883,.380764007568359],[.526226997375488,.573909997940063],[.895093023777008,.254140973091125],[.634069979190826,.409575998783112],[.661242008209229,.41302502155304],[.688880026340485,.409460008144379],[.725341975688934,.389131009578705],[.606630027294159,.40370500087738],[.654766023159027,.344011008739471],[.629905998706818,.346076011657715],[.680678009986877,.347265005111694],[.702096998691559,.353591024875641],[.75221198797226,.410804986953735],[.602918028831482,.842862963676453],[.719901978969574,.375599980354309],[.893692970275879,.399959981441498],[.790081977844238,.391354024410248],[.643998026847839,.534487962722778],[.528249025344849,.65040397644043],[.525849997997284,.680191040039062],[.560214996337891,.657229006290436],[.585384011268616,.66654098033905],[.549625992774963,.680860996246338],[.57122802734375,.682691991329193],[.624852001667023,.72809898853302],[.513050019741058,.547281980514526],[.51509702205658,.527251958847046],[.742246985435486,.314507007598877],[.598631024360657,.454979002475739],[.570338010787964,.548575043678284],[.578631997108459,.533622980117798],[.723087012767792,.532054007053375],[.516445994377136,.499638974666595],[.662801027297974,.282917976379395],[.70362401008606,.293271005153656],[.830704987049103,.193813979625702],[.552385985851288,.302568018436432],[.607609987258911,.353887975215912],[.645429015159607,.696707010269165],[.932694971561432,.730105042457581],[.557260990142822,.572826027870178],[.542901992797852,.584792017936707],[.6180260181427,.694710969924927],[.607590973377228,.694203019142151],[.722943007946014,.271963000297546],[.577413976192474,.563166975975037],[.614082992076874,.281386971473694],[.616907000541687,.255886018276215],[.668509006500244,.119913995265961],[.770092010498047,.232020974159241],[.635536015033722,.189248979091644],[.77039098739624,.299556016921997],[.826722025871277,.278755009174347],[.527121007442474,.666198015213013],[.553171992301941,.668527007102966],[.577238023281097,.673889994621277],[.554691970348358,.580065965652466],[.611896991729736,.693961024284363],[.59696102142334,.706539988517761],[.596370995044708,.693953037261963],[.539958000183105,.557139039039612],[.568841993808746,.692366003990173],[.547818005084991,.692366003990173],[.52461302280426,.692366003990173],[.534089982509613,.779141008853912],[.527670979499817,.736225962638855],[.526912987232208,.717857003211975],[.526877999305725,.704625964164734],[.526966989040375,.695277988910675],[.572058022022247,.695277988910675],[.573521018028259,.703539967536926],[.57683801651001,.711845993995667],[.581691026687622,.720062971115112],[.609944999217987,.639909982681274],[.986046016216278,.560034036636353],[.5867999792099,.69539999961853],[.590372025966644,.701822996139526],[.531915009021759,.601536989212036],[.577268004417419,.585934996604919],[.536915004253387,.593786001205444],[.627542972564697,.473352015018463],[.665585994720459,.495950996875763],[.588353991508484,.546862006187439],[.757824003696442,.14767599105835],[.709249973297119,.201507985591888],[.672684013843536,.256581008434296],[.600408971309662,.74900496006012],[.55826598405838,.261672019958496],[.570303976535797,.187870979309082],[.588165998458862,.109044015407562],[.711045026779175,.398952007293701],[.781069993972778,.435405015945435],[.587247014045715,.398931980133057],[.742869973182678,.355445981025696],[.572156012058258,.437651991844177],[.55186802148819,.536570012569427],[.821442008018494,.457556009292603],[.752701997756958,.457181990146637],[.71375697851181,.467626988887787],[.66711300611496,.460672974586487],[.631101012229919,.447153985500336],[.6008620262146,.432473003864288],[.523481011390686,.405627012252808],[.810747981071472,.523926019668579],[.771045982837677,.348959028720856],[.509127020835876,.562718033790588],[.595292985439301,.485023975372314],[.980530977249146,.401564002037048],[.573499977588654,.420000016689301],[.602994978427887,.548687994480133],[.733529984951019,.376977026462555],[.560611009597778,.519016981124878],[.967685997486115,.644356966018677],[.580985009670258,.387160003185272],[.537728011608124,.505385041236877],[.760966002941132,.779752969741821],[.801778972148895,.831938028335571],[.892440974712372,.54076099395752],[.816350996494293,.740260004997253],[.865594983100891,.333687007427216],[.614073991775513,.883246004581451],[.508952975273132,.579437971115112],[.617941975593567,.508316040039062],[.825608015060425,.397674977779388],[.681214988231659,.39623498916626],[.656635999679565,.400596976280212],[.603900015354156,.710216999053955],[.81208598613739,.588539004325867],[.56801301240921,.944564998149872],[.681007981300354,.898285031318665],[.733752012252808,.869701027870178],[.633830010890961,.398822009563446],[.606792986392975,.39553701877594],[.589659988880157,.391062021255493],[.805015981197357,.342108011245728],[.611334979534149,.362284004688263],[.634037971496582,.355970978736877],[.656635999679565,.355356991291046],[.681214988231659,.35834002494812],[.698584973812103,.363156020641327],[.941866993904114,.319076001644135],[.698584973812103,.387449026107788],[.584177017211914,.624107003211975],[.554318010807037,.566076993942261],[.534153997898102,.62064003944397],[.711217999458313,.819975018501282],[.664629995822906,.852871000766754],[.559099972248077,.902631998062134],[.871706008911133,.791940987110138],[.591234028339386,.373893976211548],[.544341027736664,.451583981513977],[.624562978744507,.924192011356354],[.88577002286911,.615028977394104],[.551338016986847,.695277988910675],[.551980018615723,.704632043838501],[.552887976169586,.715808033943176],[.555167973041534,.730794012546539],[.569944024085999,.767035007476807],[.593203008174896,.685675978660583],[.599261999130249,.681069016456604],[.607599973678589,.677703022956848],[.631937980651855,.663500010967255],[.752032995223999,.601315021514893],[.547226011753082,.420395016670227],[.563543975353241,.359827995300293],[.583841025829315,.368713974952698],[.586614012718201,.692366003990173],[.771915018558502,.683578014373779],[.531597018241882,.352482974529266],[.588370978832245,.804440975189209],[.52079701423645,.442565023899078],[.567984998226166,.493479013442993],[.543282985687256,.819254994392395],[.655317008495331,.745514988899231],[.621008992195129,.574018001556396],[.625559985637665,.78031200170517],[.680198013782501,.570719003677368],[.64276397228241,.604337990283966],[.704662978649139,.621529996395111],[.552012026309967,.862591981887817],[.589071989059448,.508637011051178],[.685944974422455,.775357007980347],[.645735025405884,.812640011310577],[.675342977046967,.703978002071381],[.810858011245728,.646304965019226],[.72012197971344,.714666962623596],[.866151988506317,.682704985141754],[.663187026977539,.644596993923187],[.570082008838654,.466325998306274],[.544561982154846,.548375964164734],[.562758982181549,.558784961700439],[.531987011432648,.530140042304993],[.585271000862122,.335177004337311],[.622952997684479,.32277899980545],[.655896008014679,.320163011550903],[.687132000923157,.322345972061157],[.716481983661652,.333200991153717],[.758756995201111,.382786989212036],[.897013008594513,.468769013881683],[.732392013072968,.424547016620636],[.70211398601532,.433162987232208],[.66652500629425,.433866024017334],[.633504986763,.426087975502014],[.603875994682312,.416586995124817],[.579657971858978,.409945011138916],[.992439985275269,.480777025222778],[.567192018032074,.569419980049133],[.54136598110199,.478899002075195],[.526564002037048,.546118021011353],[.523913025856018,.563830018043518],[.531529009342194,.555056989192963],[.566035985946655,.582329034805298],[.51631098985672,.563053965568542],[.5174720287323,.577877044677734],[.573594987392426,.389806985855103],[.560697972774506,.395331978797913],[.549755990505219,.399751007556915],[.710287988185883,.368252992630005],[.723330020904541,.363372981548309]],kl=[127,34,139,11,0,37,232,231,120,72,37,39,128,121,47,232,121,128,104,69,67,175,171,148,157,154,155,118,50,101,73,39,40,9,151,108,48,115,131,194,204,211,74,40,185,80,42,183,40,92,186,230,229,118,202,212,214,83,18,17,76,61,146,160,29,30,56,157,173,106,204,194,135,214,192,203,165,98,21,71,68,51,45,4,144,24,23,77,146,91,205,50,187,201,200,18,91,106,182,90,91,181,85,84,17,206,203,36,148,171,140,92,40,39,193,189,244,159,158,28,247,246,161,236,3,196,54,68,104,193,168,8,117,228,31,189,193,55,98,97,99,126,47,100,166,79,218,155,154,26,209,49,131,135,136,150,47,126,217,223,52,53,45,51,134,211,170,140,67,69,108,43,106,91,230,119,120,226,130,247,63,53,52,238,20,242,46,70,156,78,62,96,46,53,63,143,34,227,173,155,133,123,117,111,44,125,19,236,134,51,216,206,205,154,153,22,39,37,167,200,201,208,36,142,100,57,212,202,20,60,99,28,158,157,35,226,113,160,159,27,204,202,210,113,225,46,43,202,204,62,76,77,137,123,116,41,38,72,203,129,142,64,98,240,49,102,64,41,73,74,212,216,207,42,74,184,169,170,211,170,149,176,105,66,69,122,6,168,123,147,187,96,77,90,65,55,107,89,90,180,101,100,120,63,105,104,93,137,227,15,86,85,129,102,49,14,87,86,55,8,9,100,47,121,145,23,22,88,89,179,6,122,196,88,95,96,138,172,136,215,58,172,115,48,219,42,80,81,195,3,51,43,146,61,171,175,199,81,82,38,53,46,225,144,163,110,246,33,7,52,65,66,229,228,117,34,127,234,107,108,69,109,108,151,48,64,235,62,78,191,129,209,126,111,35,143,163,161,246,117,123,50,222,65,52,19,125,141,221,55,65,3,195,197,25,7,33,220,237,44,70,71,139,122,193,245,247,130,33,71,21,162,153,158,159,170,169,150,188,174,196,216,186,92,144,160,161,2,97,167,141,125,241,164,167,37,72,38,12,145,159,160,38,82,13,63,68,71,226,35,111,158,153,154,101,50,205,206,92,165,209,198,217,165,167,97,220,115,218,133,112,243,239,238,241,214,135,169,190,173,133,171,208,32,125,44,237,86,87,178,85,86,179,84,85,180,83,84,181,201,83,182,137,93,132,76,62,183,61,76,184,57,61,185,212,57,186,214,207,187,34,143,156,79,239,237,123,137,177,44,1,4,201,194,32,64,102,129,213,215,138,59,166,219,242,99,97,2,94,141,75,59,235,24,110,228,25,130,226,23,24,229,22,23,230,26,22,231,112,26,232,189,190,243,221,56,190,28,56,221,27,28,222,29,27,223,30,29,224,247,30,225,238,79,20,166,59,75,60,75,240,147,177,215,20,79,166,187,147,213,112,233,244,233,128,245,128,114,188,114,217,174,131,115,220,217,198,236,198,131,134,177,132,58,143,35,124,110,163,7,228,110,25,356,389,368,11,302,267,452,350,349,302,303,269,357,343,277,452,453,357,333,332,297,175,152,377,384,398,382,347,348,330,303,304,270,9,336,337,278,279,360,418,262,431,304,408,409,310,415,407,270,409,410,450,348,347,422,430,434,313,314,17,306,307,375,387,388,260,286,414,398,335,406,418,364,367,416,423,358,327,251,284,298,281,5,4,373,374,253,307,320,321,425,427,411,421,313,18,321,405,406,320,404,405,315,16,17,426,425,266,377,400,369,322,391,269,417,465,464,386,257,258,466,260,388,456,399,419,284,332,333,417,285,8,346,340,261,413,441,285,327,460,328,355,371,329,392,439,438,382,341,256,429,420,360,364,394,379,277,343,437,443,444,283,275,440,363,431,262,369,297,338,337,273,375,321,450,451,349,446,342,467,293,334,282,458,461,462,276,353,383,308,324,325,276,300,293,372,345,447,382,398,362,352,345,340,274,1,19,456,248,281,436,427,425,381,256,252,269,391,393,200,199,428,266,330,329,287,273,422,250,462,328,258,286,384,265,353,342,387,259,257,424,431,430,342,353,276,273,335,424,292,325,307,366,447,345,271,303,302,423,266,371,294,455,460,279,278,294,271,272,304,432,434,427,272,407,408,394,430,431,395,369,400,334,333,299,351,417,168,352,280,411,325,319,320,295,296,336,319,403,404,330,348,349,293,298,333,323,454,447,15,16,315,358,429,279,14,15,316,285,336,9,329,349,350,374,380,252,318,402,403,6,197,419,318,319,325,367,364,365,435,367,397,344,438,439,272,271,311,195,5,281,273,287,291,396,428,199,311,271,268,283,444,445,373,254,339,263,466,249,282,334,296,449,347,346,264,447,454,336,296,299,338,10,151,278,439,455,292,407,415,358,371,355,340,345,372,390,249,466,346,347,280,442,443,282,19,94,370,441,442,295,248,419,197,263,255,359,440,275,274,300,383,368,351,412,465,263,467,466,301,368,389,380,374,386,395,378,379,412,351,419,436,426,322,373,390,388,2,164,393,370,462,461,164,0,267,302,11,12,374,373,387,268,12,13,293,300,301,446,261,340,385,384,381,330,266,425,426,423,391,429,355,437,391,327,326,440,457,438,341,382,362,459,457,461,434,430,394,414,463,362,396,369,262,354,461,457,316,403,402,315,404,403,314,405,404,313,406,405,421,418,406,366,401,361,306,408,407,291,409,408,287,410,409,432,436,410,434,416,411,264,368,383,309,438,457,352,376,401,274,275,4,421,428,262,294,327,358,433,416,367,289,455,439,462,370,326,2,326,370,305,460,455,254,449,448,255,261,446,253,450,449,252,451,450,256,452,451,341,453,452,413,464,463,441,413,414,258,442,441,257,443,442,259,444,443,260,445,444,467,342,445,459,458,250,289,392,290,290,328,460,376,433,435,250,290,392,411,416,433,341,463,464,453,464,465,357,465,412,343,412,399,360,363,440,437,399,456,420,456,363,401,435,288,372,383,353,339,255,249,448,261,255,133,243,190,133,155,112,33,246,247,33,130,25,398,384,286,362,398,414,362,463,341,263,359,467,263,249,255,466,467,260,75,60,166,238,239,79,162,127,139,72,11,37,121,232,120,73,72,39,114,128,47,233,232,128,103,104,67,152,175,148,173,157,155,119,118,101,74,73,40,107,9,108,49,48,131,32,194,211,184,74,185,191,80,183,185,40,186,119,230,118,210,202,214,84,83,17,77,76,146,161,160,30,190,56,173,182,106,194,138,135,192,129,203,98,54,21,68,5,51,4,145,144,23,90,77,91,207,205,187,83,201,18,181,91,182,180,90,181,16,85,17,205,206,36,176,148,140,165,92,39,245,193,244,27,159,28,30,247,161,174,236,196,103,54,104,55,193,8,111,117,31,221,189,55,240,98,99,142,126,100,219,166,218,112,155,26,198,209,131,169,135,150,114,47,217,224,223,53,220,45,134,32,211,140,109,67,108,146,43,91,231,230,120,113,226,247,105,63,52,241,238,242,124,46,156,95,78,96,70,46,63,116,143,227,116,123,111,1,44,19,3,236,51,207,216,205,26,154,22,165,39,167,199,200,208,101,36,100,43,57,202,242,20,99,56,28,157,124,35,113,29,160,27,211,204,210,124,113,46,106,43,204,96,62,77,227,137,116,73,41,72,36,203,142,235,64,240,48,49,64,42,41,74,214,212,207,183,42,184,210,169,211,140,170,176,104,105,69,193,122,168,50,123,187,89,96,90,66,65,107,179,89,180,119,101,120,68,63,104,234,93,227,16,15,85,209,129,49,15,14,86,107,55,9,120,100,121,153,145,22,178,88,179,197,6,196,89,88,96,135,138,136,138,215,172,218,115,219,41,42,81,5,195,51,57,43,61,208,171,199,41,81,38,224,53,225,24,144,110,105,52,66,118,229,117,227,34,234,66,107,69,10,109,151,219,48,235,183,62,191,142,129,126,116,111,143,7,163,246,118,117,50,223,222,52,94,19,141,222,221,65,196,3,197,45,220,44,156,70,139,188,122,245,139,71,162,145,153,159,149,170,150,122,188,196,206,216,92,163,144,161,164,2,167,242,141,241,0,164,37,11,72,12,144,145,160,12,38,13,70,63,71,31,226,111,157,158,154,36,101,205,203,206,165,126,209,217,98,165,97,237,220,218,237,239,241,210,214,169,140,171,32,241,125,237,179,86,178,180,85,179,181,84,180,182,83,181,194,201,182,177,137,132,184,76,183,185,61,184,186,57,185,216,212,186,192,214,187,139,34,156,218,79,237,147,123,177,45,44,4,208,201,32,98,64,129,192,213,138,235,59,219,141,242,97,97,2,141,240,75,235,229,24,228,31,25,226,230,23,229,231,22,230,232,26,231,233,112,232,244,189,243,189,221,190,222,28,221,223,27,222,224,29,223,225,30,224,113,247,225,99,60,240,213,147,215,60,20,166,192,187,213,243,112,244,244,233,245,245,128,188,188,114,174,134,131,220,174,217,236,236,198,134,215,177,58,156,143,124,25,110,7,31,228,25,264,356,368,0,11,267,451,452,349,267,302,269,350,357,277,350,452,357,299,333,297,396,175,377,381,384,382,280,347,330,269,303,270,151,9,337,344,278,360,424,418,431,270,304,409,272,310,407,322,270,410,449,450,347,432,422,434,18,313,17,291,306,375,259,387,260,424,335,418,434,364,416,391,423,327,301,251,298,275,281,4,254,373,253,375,307,321,280,425,411,200,421,18,335,321,406,321,320,405,314,315,17,423,426,266,396,377,369,270,322,269,413,417,464,385,386,258,248,456,419,298,284,333,168,417,8,448,346,261,417,413,285,326,327,328,277,355,329,309,392,438,381,382,256,279,429,360,365,364,379,355,277,437,282,443,283,281,275,363,395,431,369,299,297,337,335,273,321,348,450,349,359,446,467,283,293,282,250,458,462,300,276,383,292,308,325,283,276,293,264,372,447,346,352,340,354,274,19,363,456,281,426,436,425,380,381,252,267,269,393,421,200,428,371,266,329,432,287,422,290,250,328,385,258,384,446,265,342,386,387,257,422,424,430,445,342,276,422,273,424,306,292,307,352,366,345,268,271,302,358,423,371,327,294,460,331,279,294,303,271,304,436,432,427,304,272,408,395,394,431,378,395,400,296,334,299,6,351,168,376,352,411,307,325,320,285,295,336,320,319,404,329,330,349,334,293,333,366,323,447,316,15,315,331,358,279,317,14,316,8,285,9,277,329,350,253,374,252,319,318,403,351,6,419,324,318,325,397,367,365,288,435,397,278,344,439,310,272,311,248,195,281,375,273,291,175,396,199,312,311,268,276,283,445,390,373,339,295,282,296,448,449,346,356,264,454,337,336,299,337,338,151,294,278,455,308,292,415,429,358,355,265,340,372,388,390,466,352,346,280,295,442,282,354,19,370,285,441,295,195,248,197,457,440,274,301,300,368,417,351,465,251,301,389,385,380,386,394,395,379,399,412,419,410,436,322,387,373,388,326,2,393,354,370,461,393,164,267,268,302,12,386,374,387,312,268,13,298,293,301,265,446,340,380,385,381,280,330,425,322,426,391,420,429,437,393,391,326,344,440,438,458,459,461,364,434,394,428,396,262,274,354,457,317,316,402,316,315,403,315,314,404,314,313,405,313,421,406,323,366,361,292,306,407,306,291,408,291,287,409,287,432,410,427,434,411,372,264,383,459,309,457,366,352,401,1,274,4,418,421,262,331,294,358,435,433,367,392,289,439,328,462,326,94,2,370,289,305,455,339,254,448,359,255,446,254,253,449,253,252,450,252,256,451,256,341,452,414,413,463,286,441,414,286,258,441,258,257,442,257,259,443,259,260,444,260,467,445,309,459,250,305,289,290,305,290,460,401,376,435,309,250,392,376,411,433,453,341,464,357,453,465,343,357,412,437,343,399,344,360,440,420,437,456,360,420,363,361,401,288,265,372,353,390,339,249,339,448,255];var J0e=[127,234,132,58,172,150,149,148,152,377,378,379,397,288,361,454,356,70,63,105,66,107,336,296,334,293,300,168,6,195,4,98,97,2,326,327,33,160,158,133,153,144,362,385,387,263,373,380,57,40,37,0,267,270,287,321,314,17,84,91,78,81,13,311,308,402,14,178],Q0e=[33,133,362,263,1,62,308,159,145,386,374,6,102,331,2,13,14,70,105,107,336,334,300,54,10,284,50,280,234,454,58,288,152],ege=[33,133,362,263,1,78,308],v2e=J0e.map(e=>dp[e]),w2e=Q0e.map(e=>dp[e]),k2e=ege.map(e=>dp[e]);var O6=e=>({startPoint:_e(e,[0,0],[-1,2]),endPoint:_e(e,[0,2],[-1,2])});var pp=e=>[Math.abs(e.endPoint[0]-e.startPoint[0]),Math.abs(e.endPoint[1]-e.startPoint[1])],Wm=e=>[e.startPoint[0]+(e.endPoint[0]-e.startPoint[0])/2,e.startPoint[1]+(e.endPoint[1]-e.startPoint[1])/2],$x=(e,t)=>e?[Math.trunc(Math.max(0,e.startPoint[0])),Math.trunc(Math.max(0,e.startPoint[1])),Math.trunc(Math.min(t.shape[2]||0,e.endPoint[0])-Math.max(0,e.startPoint[0])),Math.trunc(Math.min(t.shape[1]||0,e.endPoint[1])-Math.max(0,e.startPoint[1]))]:[0,0,0,0],Dx=(e,t)=>e?[e.startPoint[0]/(t.shape[2]||0),e.startPoint[1]/(t.shape[1]||0),(e.endPoint[0]-e.startPoint[0])/(t.shape[2]||0),(e.endPoint[1]-e.startPoint[1])/(t.shape[1]||0)]:[0,0,0,0],M6=(e,t)=>{let n=[e.startPoint[0]*t[0],e.startPoint[1]*t[1]],s=[e.endPoint[0]*t[0],e.endPoint[1]*t[1]];return{startPoint:n,endPoint:s}},_x=(e,t,n)=>{let s=t.shape[1],r=t.shape[2];return $e.cropAndResize(t,[[e.startPoint[1]/s,e.startPoint[0]/r,e.endPoint[1]/s,e.endPoint[0]/r]],[0],n)},hp=(e,t=1.5)=>{let n=Wm(e),s=pp(e),r=[t*s[0]/2,t*s[1]/2];return{startPoint:[n[0]-r[0],n[1]-r[1]],endPoint:[n[0]+r[0],n[1]+r[1]],landmarks:e.landmarks}},fp=e=>{let t=Wm(e),n=pp(e),s=Math.max(...n)/2;return{startPoint:[Math.round(t[0]-s),Math.round(t[1]-s)],endPoint:[Math.round(t[0]+s),Math.round(t[1]+s)],landmarks:e.landmarks}},Vm=e=>{let t=e.map(s=>s[0]),n=e.map(s=>s[1]);return{startPoint:[Math.min(...t),Math.min(...n)],endPoint:[Math.max(...t),Math.max(...n)],landmarks:e}},Um=[[1,0,0],[0,1,0],[0,0,1]],tge=e=>e-2*Math.PI*Math.floor((e+Math.PI)/(2*Math.PI)),nge=(e,t)=>tge(Math.PI/2-Math.atan2(-(t[1]-e[1]),t[0]-e[0]));var z6=(e,t)=>[[1,0,e],[0,1,t],[0,0,1]],Il=(e,t)=>{let n=0;for(let s=0;s{let n=[];for(let s=0;s{let n=[],s=e.length;for(let r=0;r{let n=Math.cos(e),s=Math.sin(e),r=[[n,-s,0],[s,n,0],[0,0,1]],a=z6(t[0],t[1]),o=L6(a,r),i=z6(-t[0],-t[1]);return L6(o,i)},rge=e=>{let t=[[e[0][0],e[1][0]],[e[0][1],e[1][1]]],n=[e[0][2],e[1][2]],s=[-Il(t[0],n),-Il(t[1],n)];return[t[0].concat(s[0]),t[1].concat(s[1]),[0,0,1]]},age=(e,t)=>[Il(e,t[0]),Il(e,t[1])];function W6(e){let t={strides:[e/16,e/8],anchors:[2,6]},n=[];for(let s=0;s[a[0]/r*(d[0]-r/2),a[1]/r*(d[1]-r/2),d[2]||0]),i=n!==0?B6(n,[0,0]):Um,l=n!==0?o.map(d=>[...age(d,i),d[2]]):o,c=n!==0?rge(s):Um,u=[...Wm({startPoint:t.startPoint,endPoint:t.endPoint}),1];return l.map(d=>[Math.round(d[0]+Il(u,c[0])),Math.round(d[1]+Il(u,c[1])),Math.round(d[2]||0)])}function Px(e,t,n){let s=e.landmarks.length>=Ex.count?Ex.symmetryLine:cp.symmetryLine,r=nge(e.landmarks[s[0]],e.landmarks[s[1]]),a=Wm({startPoint:e.startPoint,endPoint:e.endPoint}),o=[a[0]/t.shape[2],a[1]/t.shape[1]],i=$e.rotateWithOffset(t,r,0,o),l=B6(-r,a),c=_x({startPoint:e.startPoint,endPoint:e.endPoint},i,[n,n]),u=he(c,255);return Q(c),Q(i),[r,l,u]}var U6=6,Os,Fx=[],G6=null,Ms=0,mp=()=>Ms;async function H6(e){var t,n;return be.initial&&(Os=null),Os?e.debug&&ae("cached model:",Os.modelUrl):(Os=await st(at(e.modelBasePath,((t=e.face.detector)==null?void 0:t.modelPath)||"")),!Os||!Os.modelUrl?ae("load model failed:",(n=e.face.detector)==null?void 0:n.modelPath):e.debug&&ae("load model:",Os.modelUrl)),Ms=Os.inputs[0].shape?Os.inputs[0].shape[2]:0,Ms===-1&&(Ms=64),Fx=W6(Ms),G6=ur(Fx),Os}function oge(e){let t=_e(e,[0,1],[-1,2]),n=ie(t,G6),s=_e(e,[0,3],[-1,2]),r=he(s,Ms),a=he(n,Ms),o=he(r,2),i=ye(a,o),l=ie(a,o),c=W(i,Ms),u=W(l,Ms);return ku([c,u],1)}async function j6(e,t){var c,u,d,p;if(!e||e.isDisposedInternal||e.shape.length!==4||e.shape[1]<1||e.shape[2]<1)return{boxes:[]};let[n,s,r]=j(()=>{let h=$e.resizeBilinear(e,[Ms,Ms]),f=ye(he(h,127.5),.5),m=Os==null?void 0:Os.execute(f),g;if(Array.isArray(m)){let b=m.sort((E,P)=>E.size-P.size),w=It([b[0],b[2]],2),k=It([b[1],b[3]],2),S=It([k,w],1);g=pt(S,0)}else g=pt(m);let A=oge(g),y=_e(g,[0,0],[-1,1]),x=pt(hs(y));return[g,A,x]}),a=await $e.nonMaxSuppressionAsync(s,r,((c=t.face.detector)==null?void 0:c.maxDetected)||0,((u=t.face.detector)==null?void 0:u.iouThreshold)||0,((d=t.face.detector)==null?void 0:d.minConfidence)||0),o=await a.array();Q(a);let i=[],l=await r.data();for(let h=0;h(((p=t.face.detector)==null?void 0:p.minConfidence)||0)){let m=_e(s,[o[h],0],[1,-1]),g=j(()=>G(pt(_e(n,[o[h],U6-1],[1,-1])),[U6,-1]));i.push({box:O6(m),landmarks:g,anchor:Fx[o[h]],confidence:f}),Q(m)}}return Q(n),Q(s),Q(r),{boxes:i,scaleFactor:[e.shape[2]/Ms,e.shape[1]/Ms]}}var zx={};qp(zx,{connected:()=>Mx,kpt:()=>Ox});var Ox=["nose","leftEyeInside","leftEye","leftEyeOutside","rightEyeInside","rightEye","rightEyeOutside","leftEar","rightEar","leftMouth","rightMouth","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftPalm","rightPalm","leftIndex","rightIndex","leftPinky","rightPinky","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle","leftHeel","rightHeel","leftFoot","rightFoot","bodyCenter","bodyTop","leftThumb","leftHand","rightThumb","rightHand"],Mx={leftLeg:["leftHip","leftKnee","leftAnkle","leftHeel","leftFoot"],rightLeg:["rightHip","rightKnee","rightAnkle","rightHeel","rightFoot"],torso:["leftShoulder","rightShoulder","rightHip","leftHip","leftShoulder"],leftArm:["leftShoulder","leftElbow","leftWrist","leftPalm"],rightArm:["rightShoulder","rightElbow","rightWrist","rightPalm"],leftHand:[],rightHand:[],head:[]};var q6={initial:!0},dn=[null,null],Vo=[[0,0],[0,0]],Lx=Number.MAX_SAFE_INTEGER,Bx,Gm=null,Uo=[[0,0],[0,0],[0,0],[0,0]],X6=0;async function K6(e){var t,n,s;if(q6.initial&&(dn[0]=null),!dn[0]&&((t=e.body.detector)==null?void 0:t.modelPath)){dn[0]=await st(at(e.modelBasePath,((n=e.body.detector)==null?void 0:n.modelPath)||""));let r=Object.values(dn[0].modelSignature.inputs);Vo[0][0]=Array.isArray(r)?parseInt(r[0].tensorShape.dim[1].size):0,Vo[0][1]=Array.isArray(r)?parseInt(r[0].tensorShape.dim[2].size):0,!dn[0]||!dn[0].modelUrl?ae("load model failed:",(s=e.body.detector)==null?void 0:s.modelPath):e.debug&&ae("load model:",dn[0].modelUrl)}else e.debug&&dn[0]&&ae("cached model:",dn[0].modelUrl);return dn[0]}async function Z6(e){var t;if(q6.initial&&(dn[1]=null),dn[1])e.debug&&ae("cached model:",dn[1].modelUrl);else{dn[1]=await st(at(e.modelBasePath,e.body.modelPath||""));let n=Object.values(dn[1].modelSignature.inputs);Vo[1][0]=Array.isArray(n)?parseInt(n[0].tensorShape.dim[1].size):0,Vo[1][1]=Array.isArray(n)?parseInt(n[0].tensorShape.dim[2].size):0,((t=e.body.modelPath)==null?void 0:t.includes("lite"))?Bx=["ld_3d","output_segmentation","output_heatmap","world_3d","output_poseflag"]:Bx=["Identity","Identity_2","Identity_3","Identity_4","Identity_1"],!dn[1]||!dn[1].modelUrl?ae("load model failed:",e.body.modelPath):e.debug&&ae("load model:",dn[1].modelUrl)}return dn[1]}function ige(e,t){let n=e.map(o=>o.position[0]),s=e.map(o=>o.position[1]),r=[Math.min(...n),Math.min(...s),Math.max(...n)-Math.min(...n),Math.max(...s)-Math.min(...s)],a=[r[0]/t[0],r[1]/t[1],r[2]/t[0],r[3]/t[1]];return{keypointsBox:r,keypointsBoxRaw:a}}async function lge(e){let t={};if(!e.shape||!e.shape[1]||!e.shape[2])return e;Uo=[[0,0],[e.shape[2]>e.shape[1]?Math.trunc((e.shape[2]-e.shape[1])/2):0,e.shape[2]>e.shape[1]?Math.trunc((e.shape[2]-e.shape[1])/2):0],[e.shape[1]>e.shape[2]?Math.trunc((e.shape[1]-e.shape[2])/2):0,e.shape[1]>e.shape[2]?Math.trunc((e.shape[1]-e.shape[2])/2):0],[0,0]],t.pad=qs(e,Uo),t.resize=$e.resizeBilinear(t.pad,[Vo[1][0],Vo[1][1]]);let n=he(t.resize,255);return Object.keys(t).forEach(s=>Q(t[s])),n}function uge(e,t){for(let n of e)n.position=[n.position[0]*(t[0]+Uo[2][0]+Uo[2][1])/t[0]-Uo[2][0],n.position[1]*(t[1]+Uo[1][0]+Uo[1][1])/t[1]-Uo[1][0],n.position[2]],n.positionRaw=[n.position[0]/t[0],n.position[1]/t[1],n.position[2]];return e}var Y6=e=>1-1/(1+Math.exp(e));async function cge(e,t,n){var h;let s={};s.input=await lge(e),[s.ld,s.segmentation,s.heatmap,s.world,s.poseflag]=await((h=dn[1])==null?void 0:h.execute(s.input,Bx));let r=(await s.poseflag.data())[0],a=Math.max(0,(r-.8)/(1-.8)),o=await s.ld.data(),i=[],l=5;for(let f=0;fQ(s[f]));let d={};for(let[f,m]of Object.entries(Mx)){let g=[];for(let A=0;Ab.part===m[A]),x=c.find(b=>b.part===m[A+1]);y&&x&&y.score>(t.body.minConfidence||0)&&x.score>(t.body.minConfidence||0)&&g.push([y.position,x.position])}d[f]=g}return{id:0,score:Math.trunc(100*a)/100,box:u.keypointsBox,boxRaw:u.keypointsBoxRaw,keypoints:c,annotations:d}}async function Wx(e,t){let n=[e.shape[2]||0,e.shape[1]||0];return Lx<(t.body.skipFrames||0)&&(t.body.skipTime||0)<=Ae()-X6&&t.skipFrame&&Gm!==null?Lx++:(Gm=await cge(e,t,n),X6=Ae(),Lx=0),Gm?[Gm]:[]}var cc=[{class:1,label:"person"},{class:2,label:"bicycle"},{class:3,label:"car"},{class:4,label:"motorcycle"},{class:5,label:"airplane"},{class:6,label:"bus"},{class:7,label:"train"},{class:8,label:"truck"},{class:9,label:"boat"},{class:10,label:"traffic light"},{class:11,label:"fire hydrant"},{class:12,label:"stop sign"},{class:13,label:"parking meter"},{class:14,label:"bench"},{class:15,label:"bird"},{class:16,label:"cat"},{class:17,label:"dog"},{class:18,label:"horse"},{class:19,label:"sheep"},{class:20,label:"cow"},{class:21,label:"elephant"},{class:22,label:"bear"},{class:23,label:"zebra"},{class:24,label:"giraffe"},{class:25,label:"backpack"},{class:26,label:"umbrella"},{class:27,label:"handbag"},{class:28,label:"tie"},{class:29,label:"suitcase"},{class:30,label:"frisbee"},{class:31,label:"skis"},{class:32,label:"snowboard"},{class:33,label:"sports ball"},{class:34,label:"kite"},{class:35,label:"baseball bat"},{class:36,label:"baseball glove"},{class:37,label:"skateboard"},{class:38,label:"surfboard"},{class:39,label:"tennis racket"},{class:40,label:"bottle"},{class:41,label:"wine glass"},{class:42,label:"cup"},{class:43,label:"fork"},{class:44,label:"knife"},{class:45,label:"spoon"},{class:46,label:"bowl"},{class:47,label:"banana"},{class:48,label:"apple"},{class:49,label:"sandwich"},{class:50,label:"orange"},{class:51,label:"broccoli"},{class:52,label:"carrot"},{class:53,label:"hot dog"},{class:54,label:"pizza"},{class:55,label:"donut"},{class:56,label:"cake"},{class:57,label:"chair"},{class:58,label:"couch"},{class:59,label:"potted plant"},{class:60,label:"bed"},{class:61,label:"dining table"},{class:62,label:"toilet"},{class:63,label:"tv"},{class:64,label:"laptop"},{class:65,label:"mouse"},{class:66,label:"remote"},{class:67,label:"keyboard"},{class:68,label:"cell phone"},{class:69,label:"microwave"},{class:70,label:"oven"},{class:71,label:"toaster"},{class:72,label:"sink"},{class:73,label:"refrigerator"},{class:74,label:"book"},{class:75,label:"clock"},{class:76,label:"vase"},{class:77,label:"scissors"},{class:78,label:"teddy bear"},{class:79,label:"hair drier"},{class:80,label:"toothbrush"}];var Qs,Sl=0,Hm=[],J6=0,Vx=Number.MAX_SAFE_INTEGER;async function Q6(e){if(be.initial&&(Qs=null),Qs)e.debug&&ae("cached model:",Qs.modelUrl);else{dc(["floormod"],e),Qs=await st(at(e.modelBasePath,e.object.modelPath||""));let t=Object.values(Qs.modelSignature.inputs);Sl=Array.isArray(t)?parseInt(t[0].tensorShape.dim[2].size):0,!Qs||!Qs.modelUrl?ae("load model failed:",e.object.modelPath):e.debug&&ae("load model:",Qs.modelUrl)}return Qs}async function dge(e,t,n){if(!e)return[];let s=[],r=await e.array(),a=pt(e);Q(e);let o=Sn(a,6,1);Q(a);let i=Pn([o[1],o[0],o[3],o[2]],1),l=pt(i);Q(i);let c=pt(o[4]),u=pt(o[5]);o.forEach(f=>Q(f));let d=await $e.nonMaxSuppressionAsync(l,c,n.object.maxDetected,n.object.iouThreshold,n.object.minConfidence);Q(l),Q(c),Q(u);let p=await d.data();Q(d);let h=0;for(let f of p){let m=Math.trunc(100*r[0][f][4])/100,g=r[0][f][5],A=cc[g].label,[y,x]=[r[0][f][0]/Sl,r[0][f][1]/Sl],b=[y,x,r[0][f][2]/Sl-y,r[0][f][3]/Sl-x],w=[Math.trunc(b[0]*t[0]),Math.trunc(b[1]*t[1]),Math.trunc(b[2]*t[0]),Math.trunc(b[3]*t[1])];s.push({id:h++,score:m,class:g,label:A,box:w,boxRaw:b})}return s}async function Ux(e,t){return Vx<(t.object.skipFrames||0)&&(t.object.skipTime||0)<=Ae()-J6&&t.skipFrame&&Hm.length>0?(Vx++,Hm):(Vx=0,!be.kernels.includes("mod")||!be.kernels.includes("sparsetodense")?Hm:new Promise(async n=>{let s=[e.shape[2],e.shape[1]],r=$e.resizeBilinear(e,[Sl,Sl]),a=t.object.enabled?Qs==null?void 0:Qs.execute(r,["tower_0/detections"]):null;J6=Ae(),Q(r);let o=await dge(a,s,t);Hm=o,n(o)}))}var jx={};qp(jx,{connected:()=>Hx,kpt:()=>Gx});var Gx=["head","neck","rightShoulder","rightElbow","rightWrist","chest","leftShoulder","leftElbow","leftWrist","bodyCenter","rightHip","rightKnee","rightAnkle","leftHip","leftKnee","leftAnkle"],Hx={leftLeg:["leftHip","leftKnee","leftAnkle"],rightLeg:["rightHip","rightKnee","rightAnkle"],torso:["leftShoulder","rightShoulder","rightHip","leftHip","leftShoulder"],leftArm:["leftShoulder","leftElbow","leftWrist"],rightArm:["rightShoulder","rightElbow","rightWrist"],head:[]};var pn,e8=0,Zn={id:0,keypoints:[],box:[0,0,0,0],boxRaw:[0,0,0,0],score:0,annotations:{}},qx=Number.MAX_SAFE_INTEGER;async function Xx(e){return be.initial&&(pn=null),pn?e.debug&&ae("cached model:",pn.modelUrl):(pn=await st(at(e.modelBasePath,e.body.modelPath||"")),!pn||!pn.modelUrl?ae("load model failed:",e.body.modelPath):e.debug&&ae("load model:",pn.modelUrl)),pn}function pge(e,t){let[n,s]=e.shape;return j(()=>{let r=(i,l)=>ye(i,W(he(i,Ee(l,"int32")),Ee(l,"int32"))),a=G(e,[s*n]),o=rs(a,0).dataSync()[0];if(o>t){let i=Hs(a,0),l=r(i,n).dataSync()[0],c=he(i,Ee(n,"int32")).dataSync()[0];return[l,c,o]}return[0,0,o]})}async function Kx(e,t){var n;return qx<(((n=t.body)==null?void 0:n.skipFrames)||0)&&t.skipFrame&&Object.keys(Zn.keypoints).length>0&&(t.body.skipTime||0)<=Ae()-e8?(qx++,[Zn]):(qx=0,new Promise(async s=>{var u;let r=j(()=>{if(!(pn==null?void 0:pn.inputs[0].shape))return null;let d=$e.resizeBilinear(e,[pn.inputs[0].shape[2],pn.inputs[0].shape[1]],!1);return W(d,2).sub(1)}),a;if(t.body.enabled&&(a=await(pn==null?void 0:pn.predict(r))),e8=Ae(),Q(r),a){Zn.keypoints.length=0;let d=a.squeeze();Q(a);let p=d.unstack(2);Q(d);for(let h=0;h(((u=t.body)==null?void 0:u.minConfidence)||0)&&Zn.keypoints.push({score:Math.round(100*g)/100,part:Gx[h],positionRaw:[f/pn.inputs[0].shape[2],m/pn.inputs[0].shape[1]],position:[Math.round(e.shape[2]*f/pn.inputs[0].shape[2]),Math.round(e.shape[1]*m/pn.inputs[0].shape[1])]})}p.forEach(h=>Q(h))}Zn.score=Zn.keypoints.reduce((d,p)=>p.score>d?p.score:d,0);let o=Zn.keypoints.map(d=>d.position[0]),i=Zn.keypoints.map(d=>d.position[1]);Zn.box=[Math.min(...o),Math.min(...i),Math.max(...o)-Math.min(...o),Math.max(...i)-Math.min(...i)];let l=Zn.keypoints.map(d=>d.positionRaw[0]),c=Zn.keypoints.map(d=>d.positionRaw[1]);Zn.boxRaw=[Math.min(...l),Math.min(...c),Math.max(...l)-Math.min(...l),Math.max(...c)-Math.min(...c)];for(let[d,p]of Object.entries(Hx)){let h=[];for(let f=0;fA.part===p[f]),g=Zn.keypoints.find(A=>A.part===p[f+1]);m&&g&&m.score>(t.body.minConfidence||0)&&g.score>(t.body.minConfidence||0)&&h.push([m.position,g.position])}Zn.annotations[d]=h}s([Zn])}))}var hge=["angry","disgust","fear","happy","sad","surprise","neutral"],hn,jm=[],t8=0,n8=0,Zx=Number.MAX_SAFE_INTEGER,Yx=[.2989,.587,.114];async function s8(e){var t,n;return be.initial&&(hn=null),hn?e.debug&&ae("cached model:",hn.modelUrl):(hn=await st(at(e.modelBasePath,((t=e.face.emotion)==null?void 0:t.modelPath)||"")),!hn||!hn.modelUrl?ae("load model failed:",(n=e.face.emotion)==null?void 0:n.modelPath):e.debug&&ae("load model:",hn.modelUrl)),hn}async function Jx(e,t,n,s){var r,a;return hn?Zx<(((r=t.face.emotion)==null?void 0:r.skipFrames)||0)&&(((a=t.face.emotion)==null?void 0:a.skipTime)||0)<=Ae()-n8&&t.skipFrame&&t8===s&&jm[n]&&jm[n].length>0?(Zx++,jm[n]):(Zx=0,new Promise(async o=>{var l,c;let i=[];if((l=t.face.emotion)==null?void 0:l.enabled){let u=$e.resizeBilinear(e,[(hn==null?void 0:hn.inputs[0].shape)?hn.inputs[0].shape[2]:0,(hn==null?void 0:hn.inputs[0].shape)?hn.inputs[0].shape[1]:0],!1),[d,p,h]=Sn(u,3,3);Q(u);let f=W(d,Yx[0]),m=W(p,Yx[1]),g=W(h,Yx[2]);Q(d),Q(p),Q(h);let A=Vh([f,m,g]);Q(f),Q(m),Q(g);let y=j(()=>W(ye(A,.5),2));Q(A);let x=await(hn==null?void 0:hn.predict(y));n8=Ae();let b=await x.data();Q(x);for(let w=0;w(((c=t.face.emotion)==null?void 0:c.minConfidence)||0)&&i.push({score:Math.min(.99,Math.trunc(100*b[w])/100),emotion:hge[w]});i.sort((w,k)=>k.score-w.score),Q(y)}jm[n]=i,t8=s,o(i)})):null}var er,Go=0,fge=2.3,Qx=Lr.leftEyeLower0,eb=Lr.rightEyeLower0,pc={leftBounds:[Qx[0],Qx[Qx.length-1]],rightBounds:[eb[0],eb[eb.length-1]]},hc={upperCenter:3,lowerCenter:4,index:71,numCoordinates:76};async function r8(e){var t,n;return be.initial&&(er=null),er?e.debug&&ae("cached model:",er.modelUrl):(er=await st(at(e.modelBasePath,((t=e.face.iris)==null?void 0:t.modelPath)||"")),!er||!er.modelUrl?ae("load model failed:",(n=e.face.iris)==null?void 0:n.modelPath):e.debug&&ae("load model:",er.modelUrl)),Go=er.inputs[0].shape?er.inputs[0].shape[2]:0,Go===-1&&(Go=64),er}function qm(e,t,n,s){for(let r=0;r{let t=e[pc.leftBounds[0]][2],n=e[pc.rightBounds[0]][2];return t-n},a8=(e,t,n,s,r=!1,a)=>{let o=fp(hp(Vm([e[n],e[s]]),fge)),i=pp(o),l=$e.cropAndResize(t,[[o.startPoint[1]/a,o.startPoint[0]/a,o.endPoint[1]/a,o.endPoint[0]/a]],[0],[Go,Go]);if(r&&be.kernels.includes("flipleftright")){let c=$e.flipLeftRight(l);Q(l),l=c}return{box:o,boxSize:i,crop:l}},o8=(e,t,n,s=!1)=>{let r=[];for(let a=0;a{let s=e[Lr[`${n}EyeUpper0`][hc.upperCenter]][2],r=e[Lr[`${n}EyeLower0`][hc.lowerCenter]][2],a=(s+r)/2;return t.map((o,i)=>{let l=a;return i===2?l=s:i===4&&(l=r),[o[0],o[1],l]})};async function l8(e,t,n,s){if(!er)return n.debug&&ae("face mesh iris detection requested, but model is not loaded"),e;let{box:r,boxSize:a,crop:o}=a8(e,t,pc.leftBounds[0],pc.leftBounds[1],!0,s),{box:i,boxSize:l,crop:c}=a8(e,t,pc.rightBounds[0],pc.rightBounds[1],!0,s),u=It([o,c]);Q(o),Q(c);let d=er.predict(u);Q(u);let p=await d.data();Q(d);let h=p.slice(0,hc.numCoordinates*3),{rawCoords:f,iris:m}=o8(h,r,a,!0),g=p.slice(hc.numCoordinates*3),{rawCoords:A,iris:y}=o8(g,i,l),x=mge(e);Math.abs(x)<30?(qm(e,f,"left",null),qm(e,A,"right",null)):x<1?qm(e,f,"left",["EyeUpper0","EyeLower0"]):qm(e,A,"right",["EyeUpper0","EyeLower0"]);let b=i8(e,m,"left"),w=i8(e,y,"right");return e.concat(b).concat(w)}var Br=[],tr=null,xr=0,tb=Number.MAX_SAFE_INTEGER,u8=0,c8=0;async function d8(e,t){var a,o,i,l,c,u,d,p,h,f,m,g,A;if(!t.skipFrame||(c8!==((a=t.face.detector)==null?void 0:a.maxDetected)||!((o=t.face.mesh)==null?void 0:o.enabled))&&tb>(((i=t.face.detector)==null?void 0:i.skipFrames)||0)&&(((l=t.face.description)==null?void 0:l.skipTime)||0)<=Ae()-u8){let y=await j6(e,t);u8=Ae(),Br=[];for(let x of y.boxes){let b=await x.box.startPoint.data(),w=await x.box.endPoint.data(),k=await x.landmarks.array();Br.push({startPoint:b,endPoint:w,landmarks:k,confidence:x.confidence})}y.boxes.forEach(x=>Q([x.box.startPoint,x.box.endPoint,x.landmarks]));for(let x=0;x[_[0]/(e.shape[2]||0),_[1]/(e.shape[1]||0),(_[2]||0)/xr]),y={...hp(Vm(w.mesh),1.5),confidence:y.confidence};for(let _ of Object.keys(Lr))w.annotations[_]=Lr[_].map(T=>w.mesh[T]);((m=t.face.detector)==null?void 0:m.rotation)&&t.face.mesh.enabled&&((g=t.face.description)==null?void 0:g.enabled)&&be.kernels.includes("rotatewithoffset")&&(Q(w.tensor),[x,b,w.tensor]=Px(y,e,xr)),w.box=$x(y,e),w.boxRaw=Dx(y,e),w.score=Math.round(100*P||100*y.confidence||0)/100,w.faceScore=Math.round(100*P)/100,y={...fp(y),confidence:y.confidence,faceConfidence:P}}}else{w.box=$x(y,e),w.boxRaw=Dx(y,e),w.score=Math.round(100*y.confidence||0)/100,w.mesh=y.landmarks.map(k=>[(y.startPoint[0]+y.endPoint[0])/2+(y.endPoint[0]+y.startPoint[0])*k[0]/mp(),(y.startPoint[1]+y.endPoint[1])/2+(y.endPoint[1]+y.startPoint[1])*k[1]/mp()]),w.meshRaw=w.mesh.map(k=>[k[0]/(e.shape[2]||0),k[1]/(e.shape[1]||0),(k[2]||0)/xr]);for(let k of Object.keys(cp))w.annotations[k]=[w.mesh[cp[k]]]}n.push(w),s.push(y)}return((A=t.face.mesh)==null?void 0:A.enabled)&&(Br=s.filter(y=>{var x;return y.confidence>(((x=t.face.detector)==null?void 0:x.minConfidence)||0)})),c8=n.length,n}async function p8(e){var t,n;return be.initial&&(tr=null),tr?e.debug&&ae("cached model:",tr.modelUrl):(tr=await st(at(e.modelBasePath,((t=e.face.mesh)==null?void 0:t.modelPath)||"")),!tr||!tr.modelUrl?ae("load model failed:",(n=e.face.mesh)==null?void 0:n.modelPath):e.debug&&ae("load model:",tr.modelUrl)),xr=tr.inputs[0].shape?tr.inputs[0].shape[2]:0,xr===-1&&(xr=64),tr}var h8=kl,f8=dp;var Yn,Xm=[],m8=0,g8=0,nb=Number.MAX_SAFE_INTEGER;async function A8(e){var n,s;let t=at(e.modelBasePath,((n=e.face.description)==null?void 0:n.modelPath)||"");return be.initial&&(Yn=null),Yn?e.debug&&ae("cached model:",t):(Yn=await st(t),Yn?e.debug&&ae("load model:",t):ae("load model failed:",((s=e.face.description)==null?void 0:s.modelPath)||"")),Yn}function sb(e){return j(()=>{let n=e.image||e.tensor||e;if(!(n instanceof Ye))return null;let s=[[.05,.15,.85,.85]];if(!(Yn==null?void 0:Yn.inputs[0].shape))return null;let r=n.shape.length===3?$e.cropAndResize(Kt(n,0),s,[0],[Yn.inputs[0].shape[2],Yn.inputs[0].shape[1]]):$e.cropAndResize(n,s,[0],[Yn.inputs[0].shape[2],Yn.inputs[0].shape[1]]);return W(r,255)})}async function rb(e,t,n,s){var r,a,o,i;return Yn?nb<(((r=t.face.description)==null?void 0:r.skipFrames)||0)&&(((a=t.face.description)==null?void 0:a.skipTime)||0)<=Ae()-m8&&t.skipFrame&&g8===s&&((o=Xm[n])==null?void 0:o.age)&&((i=Xm[n])==null?void 0:i.age)>0?(nb++,Xm[n]):(nb=0,new Promise(async l=>{var u,d;let c={age:0,gender:"unknown",genderScore:0,descriptor:[]};if((u=t.face.description)==null?void 0:u.enabled){let p=sb(e),h=await(Yn==null?void 0:Yn.predict(p));m8=Ae(),Q(p);let m=await(await h.find(S=>S.shape[1]===1)).data(),g=Math.trunc(200*Math.abs(m[0]-.5))/100;g>(((d=t.face.description)==null?void 0:d.minConfidence)||0)&&(c.gender=m[0]<=.5?"female":"male",c.genderScore=Math.min(.99,g));let A=Hs(h.find(S=>S.shape[1]===100),1),y=(await A.data())[0];Q(A);let b=await h.find(S=>S.shape[1]===100).data();c.age=Math.round(b[y-1]>b[y+1]?10*y-100*b[y-1]:10*y+100*b[y+1])/10;let w=h.find(S=>S.shape[1]===1024),k=w?await w.data():[];c.descriptor=Array.from(k),h.forEach(S=>Q(S))}Xm[n]=c,g8=s,l(c)})):null}function Km(e){return[Math.abs(e.endPoint[0]-e.startPoint[0]),Math.abs(e.endPoint[1]-e.startPoint[1])]}function gp(e){return[e.startPoint[0]+(e.endPoint[0]-e.startPoint[0])/2,e.startPoint[1]+(e.endPoint[1]-e.startPoint[1])/2]}function y8(e,t,n){let s=t.shape[1],r=t.shape[2],a=[[e.startPoint[1]/s,e.startPoint[0]/r,e.endPoint[1]/s,e.endPoint[0]/r]];return $e.cropAndResize(t,a,[0],n)}function x8(e,t){let n=[e.startPoint[0]*t[0],e.startPoint[1]*t[1]],s=[e.endPoint[0]*t[0],e.endPoint[1]*t[1]],r=e.palmLandmarks.map(a=>[a[0]*t[0],a[1]*t[1]]);return{startPoint:n,endPoint:s,palmLandmarks:r,confidence:e.confidence}}function Zm(e,t=1.5){let n=gp(e),s=Km(e),r=[t*s[0]/2,t*s[1]/2],a=[n[0]-r[0],n[1]-r[1]],o=[n[0]+r[0],n[1]+r[1]];return{startPoint:a,endPoint:o,palmLandmarks:e.palmLandmarks}}function Ym(e){let t=gp(e),n=Km(e),r=Math.max(...n)/2,a=[t[0]-r,t[1]-r],o=[t[0]+r,t[1]+r];return{startPoint:a,endPoint:o,palmLandmarks:e.palmLandmarks}}function gge(e){return e-2*Math.PI*Math.floor((e+Math.PI)/(2*Math.PI))}function b8(e,t){let n=Math.PI/2-Math.atan2(-(t[1]-e[1]),t[0]-e[0]);return gge(n)}var v8=(e,t)=>[[1,0,e],[0,1,t],[0,0,1]];function Ho(e,t){let n=0;for(let s=0;s[n.x,n.y]),this.anchorsTensor=ur(this.anchors),this.inputSize=this.model&&this.model.inputs&&this.model.inputs[0].shape?this.model.inputs[0].shape[2]:0,this.inputSizeTensor=Zt([this.inputSize,this.inputSize]),this.doubleInputSizeTensor=Zt([this.inputSize*2,this.inputSize*2])}normalizeBoxes(t){return j(()=>{let n=_e(t,[0,0],[-1,2]),s=_e(t,[0,2],[-1,2]),r=ie(he(n,this.inputSizeTensor),this.anchorsTensor),a=he(s,this.doubleInputSizeTensor),o=W(ye(r,a),this.inputSizeTensor),i=W(ie(r,a),this.inputSizeTensor);return ku([o,i],1)})}normalizeLandmarks(t,n){return j(()=>{let s=ie(he(G(t,[-1,7,2]),this.inputSizeTensor),this.anchors[n]);return W(s,this.inputSizeTensor)})}async getBoxes(t,n){let s={};s.batched=this.model.predict(t),s.predictions=pt(s.batched),s.scores=j(()=>pt(hs(_e(s.predictions,[0,0],[-1,1]))));let r=await s.scores.data();s.boxes=_e(s.predictions,[0,1],[-1,4]),s.norm=this.normalizeBoxes(s.boxes),s.nms=await $e.nonMaxSuppressionAsync(s.norm,s.scores,3*n.hand.maxDetected,n.hand.iouThreshold,n.hand.minConfidence);let a=await s.nms.array(),o=[];for(let i of a){let l=_e(s.norm,[i,0],[1,-1]),c=j(()=>G(this.normalizeLandmarks(_e(s.predictions,[i,5],[1,14]),i),[-1,2]));o.push({box:l,palmLandmarks:c,confidence:r[i]})}for(let i of Object.keys(s))Q(s[i]);return o}async estimateHandBounds(t,n){let s=t.shape[1],r=t.shape[2],a=j(()=>ye(he($e.resizeBilinear(t,[this.inputSize,this.inputSize]),127.5),1)),o=await this.getBoxes(a,n);Q(a);let i=[];if(!o||o.length===0)return i;for(let l of o){let c=await l.box.data(),u=c.slice(0,2),d=c.slice(2,4),p=await l.palmLandmarks.array();Q(l.box),Q(l.palmLandmarks),i.push(x8({startPoint:u,endPoint:d,palmLandmarks:p,confidence:l.confidence},[r/this.inputSize,s/this.inputSize]))}return i}};var yge=5,S8=1.65,C8=[0,5,9,13,17,1,2],xge=0,bge=2,T8=0,lb=class{constructor(t,n){pe(this,"handDetector");pe(this,"handPoseModel");pe(this,"inputSize");pe(this,"storedBoxes");pe(this,"skipped");pe(this,"detectedHands");this.handDetector=t,this.handPoseModel=n,this.inputSize=this.handPoseModel&&this.handPoseModel.inputs[0].shape?this.handPoseModel.inputs[0].shape[2]:0,this.storedBoxes=[],this.skipped=0,this.detectedHands=0}calculateLandmarksBoundingBox(t){let n=t.map(o=>o[0]),s=t.map(o=>o[1]),r=[Math.min(...n),Math.min(...s)],a=[Math.max(...n),Math.max(...s)];return{startPoint:r,endPoint:a}}getBoxForPalmLandmarks(t,n){let s=t.map(a=>ob([...a,1],n)),r=this.calculateLandmarksBoundingBox(s);return Zm(Ym(r),yge)}getBoxForHandLandmarks(t){let n=this.calculateLandmarksBoundingBox(t),s=Zm(Ym(n),S8);s.palmLandmarks=[];for(let r=0;r[o[0]*(h[0]-this.inputSize/2),o[1]*(h[1]-this.inputSize/2),o[2]*h[2]]),l=ab(s,[0,0]),c=i.map(h=>[...ob(h,l),h[2]]),u=k8(r),d=[...gp(n),1],p=[Ho(d,u[0]),Ho(d,u[1])];return c.map(h=>[Math.trunc(h[0]+p[0]),Math.trunc(h[1]+p[1]),Math.trunc(h[2])])}async estimateHands(t,n){let s=!1,r;(this.skipped===0||this.skipped>n.hand.skipFrames&&(n.hand.skipTime||0)<=Ae()-T8||!n.hand.landmarks||!n.skipFrame)&&(r=await this.handDetector.estimateHandBounds(t,n),this.skipped=0),n.skipFrame&&this.skipped++,r&&r.length>0&&(r.length!==this.detectedHands&&this.detectedHands!==n.hand.maxDetected||!n.hand.landmarks)&&(this.detectedHands=0,this.storedBoxes=[...r],this.storedBoxes.length>0&&(s=!0));let a=[];for(let o=0;o=n.hand.minConfidence/4){let x=G(A,[-1,3]),b=await x.array();Q(A),Q(x);let w=this.transformRawCoords(b,h,l,p),k=this.getBoxForHandLandmarks(w);this.storedBoxes[o]={...k,confidence:y};let S={landmarks:w,confidence:y,boxConfidence:i.confidence,fingerConfidence:y,box:{topLeft:k.startPoint,bottomRight:k.endPoint}};a.push(S)}else this.storedBoxes[o]=null;Q(A)}else{let l=Zm(Ym(i),S8),c={confidence:i.confidence,boxConfidence:i.confidence,fingerConfidence:0,box:{topLeft:l.startPoint,bottomRight:l.endPoint},landmarks:[]};a.push(c)}}return this.storedBoxes=this.storedBoxes.filter(o=>o!==null),this.detectedHands=a.length,a.length>n.hand.maxDetected&&(a.length=n.hand.maxDetected),a}};var Ze={thumb:0,index:1,middle:2,ring:3,pinky:4,all:[0,1,2,3,4],nameMapping:{0:"thumb",1:"index",2:"middle",3:"ring",4:"pinky"},pointsMapping:{0:[[0,1],[1,2],[2,3],[3,4]],1:[[0,5],[5,6],[6,7],[7,8]],2:[[0,9],[9,10],[10,11],[11,12]],3:[[0,13],[13,14],[14,15],[15,16]],4:[[0,17],[17,18],[18,19],[19,20]]},getName:e=>Ze.nameMapping[e],getPoints:e=>Ze.pointsMapping[e]},cs={none:0,half:1,full:2,nameMapping:{0:"none",1:"half",2:"full"},getName:e=>cs.nameMapping[e]},qe={verticalUp:0,verticalDown:1,horizontalLeft:2,horizontalRight:3,diagonalUpRight:4,diagonalUpLeft:5,diagonalDownRight:6,diagonalDownLeft:7,nameMapping:{0:"verticalUp",1:"verticalDown",2:"horizontalLeft",3:"horizontalRight",4:"diagonalUpRight",5:"diagonalUpLeft",6:"diagonalDownRight",7:"diagonalDownLeft"},getName:e=>qe.nameMapping[e]},Jm=class{constructor(t){pe(this,"name");pe(this,"curls");pe(this,"directions");pe(this,"weights");pe(this,"weightsRelative");this.name=t,this.curls={},this.directions={},this.weights=[1,1,1,1,1],this.weightsRelative=[1,1,1,1,1]}addCurl(t,n,s){typeof this.curls[t]=="undefined"&&(this.curls[t]=[]),this.curls[t].push([n,s])}addDirection(t,n,s){this.directions[t]||(this.directions[t]=[]),this.directions[t].push([n,s])}setWeight(t,n){this.weights[t]=n;let s=this.weights.reduce((r,a)=>r+a,0);this.weightsRelative=this.weights.map(r=>r*5/s)}matchAgainst(t,n){let s=0;for(let r in t){let a=t[r],o=this.curls[r];if(typeof o=="undefined"){s+=this.weightsRelative[r];continue}for(let[i,l]of o)if(a===i){s+=l*this.weightsRelative[r];break}}for(let r in n){let a=n[r],o=this.directions[r];if(typeof o=="undefined"){s+=this.weightsRelative[r];continue}for(let[i,l]of o)if(a===i){s+=l*this.weightsRelative[r];break}}return s/10}};var jo=new Jm("thumbs up");jo.addCurl(Ze.thumb,cs.none,1);jo.addDirection(Ze.thumb,qe.verticalUp,1);jo.addDirection(Ze.thumb,qe.diagonalUpLeft,.25);jo.addDirection(Ze.thumb,qe.diagonalUpRight,.25);for(let e of[Ze.index,Ze.middle,Ze.ring,Ze.pinky])jo.addCurl(e,cs.full,1),jo.addDirection(e,qe.horizontalLeft,1),jo.addDirection(e,qe.horizontalRight,1);var tn=new Jm("victory");tn.addCurl(Ze.thumb,cs.half,.5);tn.addCurl(Ze.thumb,cs.none,.5);tn.addDirection(Ze.thumb,qe.verticalUp,1);tn.addDirection(Ze.thumb,qe.diagonalUpLeft,1);tn.addCurl(Ze.index,cs.none,1);tn.addDirection(Ze.index,qe.verticalUp,.75);tn.addDirection(Ze.index,qe.diagonalUpLeft,1);tn.addCurl(Ze.middle,cs.none,1);tn.addDirection(Ze.middle,qe.verticalUp,1);tn.addDirection(Ze.middle,qe.diagonalUpLeft,.75);tn.addCurl(Ze.ring,cs.full,1);tn.addDirection(Ze.ring,qe.verticalUp,.2);tn.addDirection(Ze.ring,qe.diagonalUpLeft,1);tn.addDirection(Ze.ring,qe.horizontalLeft,.2);tn.addCurl(Ze.pinky,cs.full,1);tn.addDirection(Ze.pinky,qe.verticalUp,.2);tn.addDirection(Ze.pinky,qe.diagonalUpLeft,1);tn.addDirection(Ze.pinky,qe.horizontalLeft,.2);tn.setWeight(Ze.index,2);tn.setWeight(Ze.middle,2);var N8=[jo,tn];var vge=.7,Cl={HALF_CURL_START_LIMIT:60,NO_CURL_START_LIMIT:130,DISTANCE_VOTE_POWER:1.1,SINGLE_ANGLE_VOTE_POWER:.9,TOTAL_ANGLE_VOTE_POWER:1.6};function E8(e,t,n,s){let r=(t-s)/(e-n),a=Math.atan(r)*180/Math.PI;return a<=0?a=-a:a>0&&(a=180-a),a}function R8(e,t){if(!e||!t)return[0,0];let n=E8(e[0],e[1],t[0],t[1]);if(e.length===2)return n;let s=E8(e[1],e[2],t[1],t[2]);return[n,s]}function $8(e,t=1){let n=0,s=0,r=0;return e>=75&&e<=105?n=1*t:e>=25&&e<=155?s=1*t:r=1*t,[n,s,r]}function wge(e,t,n){let s=e[0]-t[0],r=e[0]-n[0],a=t[0]-n[0],o=e[1]-t[1],i=e[1]-n[1],l=t[1]-n[1],c=e[2]-t[2],u=e[2]-n[2],d=t[2]-n[2],p=Math.sqrt(s*s+o*o+c*c),h=Math.sqrt(r*r+i*i+u*u),f=Math.sqrt(a*a+l*l+d*d),m=(f*f+p*p-h*h)/(2*f*p);m>1?m=1:m<-1&&(m=-1);let g=Math.acos(m);g=57.2958*g%180;let A;return g>Cl.NO_CURL_START_LIMIT?A=cs.none:g>Cl.HALF_CURL_START_LIMIT?A=cs.half:A=cs.full,A}function D8(e,t,n,s){let r;return s===Math.abs(e)?e>0?r=qe.horizontalLeft:r=qe.horizontalRight:s===Math.abs(t)?t>0?r=qe.horizontalLeft:r=qe.horizontalRight:n>0?r=qe.horizontalLeft:r=qe.horizontalRight,r}function _8(e,t,n,s){let r;return s===Math.abs(e)?e<0?r=qe.verticalDown:r=qe.verticalUp:s===Math.abs(t)?t<0?r=qe.verticalDown:r=qe.verticalUp:n<0?r=qe.verticalDown:r=qe.verticalUp,r}function kge(e,t,n,s,r,a,o,i){let l,c=_8(e,t,n,s),u=D8(r,a,o,i);return c===qe.verticalUp?u===qe.horizontalLeft?l=qe.diagonalUpLeft:l=qe.diagonalUpRight:u===qe.horizontalLeft?l=qe.diagonalDownLeft:l=qe.diagonalDownRight,l}function Ige(e,t,n,s){let r=e[0]-t[0],a=e[0]-n[0],o=t[0]-n[0],i=e[1]-t[1],l=e[1]-n[1],c=t[1]-n[1],u=Math.max(Math.abs(r),Math.abs(a),Math.abs(o)),d=Math.max(Math.abs(i),Math.abs(l),Math.abs(c)),p=0,h=0,f=0,m=d/(u+1e-5);m>1.5?p+=Cl.DISTANCE_VOTE_POWER:m>.66?h+=Cl.DISTANCE_VOTE_POWER:f+=Cl.DISTANCE_VOTE_POWER;let g=Math.sqrt(r*r+i*i),A=Math.sqrt(a*a+l*l),y=Math.sqrt(o*o+c*c),x=Math.max(g,A,y),b=e[0],w=e[1],k=n[0],S=n[1];x===g?(k=n[0],S=n[1]):x===y&&(b=t[0],w=t[1]);let F=R8([b,w],[k,S]),R=$8(F,Cl.TOTAL_ANGLE_VOTE_POWER);p+=R[0],h+=R[1],f+=R[2];for(let T of s){let M=$8(T,Cl.SINGLE_ANGLE_VOTE_POWER);p+=M[0],h+=M[1],f+=M[2]}let _;return p===Math.max(p,h,f)?_=_8(l,i,c,d):f===Math.max(h,f)?_=D8(a,r,o,u):_=kge(l,i,c,d,a,r,o,u),_}function P8(e){let t=[],n=[],s=[],r=[];if(!e)return{curls:s,directions:r};for(let a of Ze.all){let o=Ze.getPoints(a),i=[],l=[];for(let c of o){let u=e[c[0]],d=e[c[1]],p=R8(u,d),h=p[0],f=p[1];i.push(h),l.push(f)}t.push(i),n.push(l)}for(let a of Ze.all){let o=a===Ze.thumb?1:0,i=Ze.getPoints(a),l=e[i[o][0]],c=e[i[o+1][1]],u=e[i[3][1]],d=wge(l,c,u),p=Ige(l,c,u,t[a].slice(o));s[a]=d,r[a]=p}return{curls:s,directions:r}}function Qm(e){if(!e||e.length===0)return null;let t=P8(e),n={};for(let s of Ze.all)n[Ze.getName(s)]={curl:cs.getName(t.curls[s]),direction:qe.getName(t.directions[s])};return n}function F8(e){let t=[];if(!e||e.length===0)return t;let n=P8(e);for(let s of N8){let r=s.matchAgainst(n.curls,n.directions);r>=vge&&t.push({name:s.name,confidence:r})}return t}var O8={thumb:[1,2,3,4],index:[5,6,7,8],middle:[9,10,11,12],ring:[13,14,15,16],pinky:[17,18,19,20],palm:[0]},la,ua,M8;async function ub(e,t){let n=await M8.estimateHands(e,t);if(!n)return[];let s=[];for(let r=0;rn[r].landmarks[d]);let o=n[r].landmarks,i=[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,0,0],l=[0,0,0,0];if(o&&o.length>0){for(let u of o)u[0]i[2]&&(i[2]=u[0]),u[1]>i[3]&&(i[3]=u[1]);i[2]-=i[0],i[3]-=i[1],l=[i[0]/(e.shape[2]||0),i[1]/(e.shape[1]||0),i[2]/(e.shape[2]||0),i[3]/(e.shape[1]||0)]}else i=n[r].box?[Math.trunc(Math.max(0,n[r].box.topLeft[0])),Math.trunc(Math.max(0,n[r].box.topLeft[1])),Math.trunc(Math.min(e.shape[2]||0,n[r].box.bottomRight[0])-Math.max(0,n[r].box.topLeft[0])),Math.trunc(Math.min(e.shape[1]||0,n[r].box.bottomRight[1])-Math.max(0,n[r].box.topLeft[1]))]:[0,0,0,0],l=[n[r].box.topLeft[0]/(e.shape[2]||0),n[r].box.topLeft[1]/(e.shape[1]||0),(n[r].box.bottomRight[0]-n[r].box.topLeft[0])/(e.shape[2]||0),(n[r].box.bottomRight[1]-n[r].box.topLeft[1])/(e.shape[1]||0)];let c=Qm(o);s.push({id:r,score:Math.round(100*n[r].confidence)/100,boxScore:Math.round(100*n[r].boxConfidence)/100,fingerScore:Math.round(100*n[r].fingerConfidence)/100,label:"hand",box:i,boxRaw:l,keypoints:o,annotations:a,landmarks:c})}return s}async function cb(e){var n,s,r,a,o,i;be.initial&&(la=null,ua=null),!la||!ua?([la,ua]=await Promise.all([e.hand.enabled?st(at(e.modelBasePath,((n=e.hand.detector)==null?void 0:n.modelPath)||""),{fromTFHub:(((s=e.hand.detector)==null?void 0:s.modelPath)||"").includes("tfhub.dev")}):null,e.hand.landmarks?st(at(e.modelBasePath,((r=e.hand.skeleton)==null?void 0:r.modelPath)||""),{fromTFHub:(((a=e.hand.skeleton)==null?void 0:a.modelPath)||"").includes("tfhub.dev")}):null]),e.hand.enabled&&(!la||!la.modelUrl?ae("load model failed:",((o=e.hand.detector)==null?void 0:o.modelPath)||""):e.debug&&ae("load model:",la.modelUrl),!ua||!ua.modelUrl?ae("load model failed:",((i=e.hand.skeleton)==null?void 0:i.modelPath)||""):e.debug&&ae("load model:",ua.modelUrl))):(e.debug&&ae("cached model:",la.modelUrl),e.debug&&ae("cached model:",ua.modelUrl));let t=new ib(la);return M8=new lb(t,ua),[la,ua]}function Tl(e,t=[1,1]){let n=[e.map(i=>i[0]),e.map(i=>i[1])],s=[Math.min(...n[0]),Math.min(...n[1])],r=[Math.max(...n[0]),Math.max(...n[1])],a=[s[0],s[1],r[0]-s[0],r[1]-s[1]],o=[a[0]/t[0],a[1]/t[1],a[2]/t[0],a[3]/t[1]];return{box:a,boxRaw:o}}function z8(e,t=[1,1]){let n=[e.map(c=>c[0]),e.map(c=>c[1])],s=[Math.min(...n[0]),Math.min(...n[1])],r=[Math.max(...n[0]),Math.max(...n[1])],a=[(s[0]+r[0])/2,(s[1]+r[1])/2],o=Math.max(a[0]-s[0],a[1]-s[1],-a[0]+r[0],-a[1]+r[1]),i=[Math.trunc(a[0]-o),Math.trunc(a[1]-o),Math.trunc(2*o),Math.trunc(2*o)],l=[i[0]/t[0],i[1]/t[1],i[2]/t[0],i[3]/t[1]];return{box:i,boxRaw:l}}function e0(e,t){let n=[e[2]*t,e[3]*t];return[e[0]-(n[0]-e[2])/2,e[1]-(n[1]-e[3])/2,n[0],n[1]]}function db(e){return[Math.max(0,e[1]),Math.max(0,e[0]),Math.min(1,e[3]+e[1]),Math.min(1,e[2]+e[0])]}var Nt=[null,null],Sge=["StatefulPartitionedCall/Postprocessor/Slice","StatefulPartitionedCall/Postprocessor/ExpandDims_1"],qo=[[0,0],[0,0]],Cge=["hand","fist","pinch","point","face","tip","pinchtip"],L8=4,B8=1.6,Tge=512,Nge=1.4,t0=0,pb=0,ca=[0,0],Xt={boxes:[],hands:[]},W8={thumb:[1,2,3,4],index:[5,6,7,8],middle:[9,10,11,12],ring:[13,14,15,16],pinky:[17,18,19,20],palm:[0]};async function V8(e){var t,n;if(be.initial&&(Nt[0]=null),Nt[0])e.debug&&ae("cached model:",Nt[0].modelUrl);else{dc(["tensorlistreserve","enter","tensorlistfromtensor","merge","loopcond","switch","exit","tensorliststack","nextiteration","tensorlistsetitem","tensorlistgetitem","reciprocal","shape","split","where"],e),Nt[0]=await st(at(e.modelBasePath,((t=e.hand.detector)==null?void 0:t.modelPath)||""));let s=Object.values(Nt[0].modelSignature.inputs);qo[0][0]=Array.isArray(s)?parseInt(s[0].tensorShape.dim[1].size):0,qo[0][1]=Array.isArray(s)?parseInt(s[0].tensorShape.dim[2].size):0,!Nt[0]||!Nt[0].modelUrl?ae("load model failed:",(n=e.hand.detector)==null?void 0:n.modelPath):e.debug&&ae("load model:",Nt[0].modelUrl)}return Nt[0]}async function U8(e){var t,n;if(be.initial&&(Nt[1]=null),Nt[1])e.debug&&ae("cached model:",Nt[1].modelUrl);else{Nt[1]=await st(at(e.modelBasePath,((t=e.hand.skeleton)==null?void 0:t.modelPath)||""));let s=Object.values(Nt[1].modelSignature.inputs);qo[1][0]=Array.isArray(s)?parseInt(s[0].tensorShape.dim[1].size):0,qo[1][1]=Array.isArray(s)?parseInt(s[0].tensorShape.dim[2].size):0,!Nt[1]||!Nt[1].modelUrl?ae("load model failed:",(n=e.hand.skeleton)==null?void 0:n.modelPath):e.debug&&ae("load model:",Nt[1].modelUrl)}return Nt[1]}async function Ege(e,t){let n=[];if(!e||!Nt[0])return n;let s={},r=(e.shape[2]||1)/(e.shape[1]||1),a=Math.min(Math.round((e.shape[1]||0)/8)*8,Tge),o=Math.round(a*r/8)*8;s.resize=$e.resizeBilinear(e,[a,o]),s.cast=de(s.resize,"int32"),[s.rawScores,s.rawBoxes]=await Nt[0].executeAsync(s.cast,Sge),s.boxes=pt(s.rawBoxes,[0,2]),s.scores=pt(s.rawScores,[0]);let i=as(s.scores,1);Q(i[L8]),i.splice(L8,1),s.filtered=Pn(i,1),Q(i),s.max=rs(s.filtered,1),s.argmax=Hs(s.filtered,1);let l=0;s.nms=await $e.nonMaxSuppressionAsync(s.boxes,s.max,t.hand.maxDetected,t.hand.iouThreshold,t.hand.minConfidence);let c=await s.nms.data(),u=await s.max.data(),d=await s.argmax.data();for(let p of Array.from(c)){let h=_e(s.boxes,p,1),f=await h.data();Q(h);let m=[f[1],f[0],f[3]-f[1],f[2]-f[0]],g=e0(m,Nge),A=db(g),y=[Math.trunc(m[0]*ca[0]),Math.trunc(m[1]*ca[1]),Math.trunc(m[2]*ca[0]),Math.trunc(m[3]*ca[1])],x=u[p],b=Cge[d[p]],w={id:l++,score:x,box:y,boxRaw:g,boxCrop:A,label:b};n.push(w)}return Object.keys(s).forEach(p=>Q(s[p])),n.sort((p,h)=>h.score-p.score),n.length>(t.hand.maxDetected||1)&&(n.length=t.hand.maxDetected||1),n}async function hb(e,t,n){let s={id:t.id,score:Math.round(100*t.score)/100,boxScore:Math.round(100*t.score)/100,fingerScore:0,box:t.box,boxRaw:t.boxRaw,label:t.label,keypoints:[],landmarks:{},annotations:{}};if(e&&Nt[1]&&n.hand.landmarks&&t.score>(n.hand.minConfidence||0)){let r={};r.crop=$e.cropAndResize(e,[t.boxCrop],[0],[qo[1][0],qo[1][1]],"bilinear"),r.cast=de(r.crop,"float32"),r.div=he(r.cast,255),[r.score,r.keypoints]=Nt[1].execute(r.div);let a=(await r.score.data())[0],o=(100-Math.trunc(100/(1+Math.exp(a))))/100;if(o>=(n.hand.minConfidence||0)){s.fingerScore=o,r.reshaped=G(r.keypoints,[-1,3]);let c=(await r.reshaped.array()).map(u=>[u[0]/qo[1][1],u[1]/qo[1][0],u[2]||0]).map(u=>[u[0]*t.boxRaw[2],u[1]*t.boxRaw[3],u[2]||0]);s.keypoints=c.map(u=>[ca[0]*(u[0]+t.boxRaw[0]),ca[1]*(u[1]+t.boxRaw[1]),u[2]||0]),s.landmarks=Qm(s.keypoints);for(let u of Object.keys(W8))s.annotations[u]=W8[u].map(d=>s.landmarks&&s.keypoints[d]?s.keypoints[d]:null)}Object.keys(r).forEach(i=>Q(r[i]))}return s}async function fb(e,t){var n,s;return!Nt[0]||!Nt[1]||!((n=Nt[0])==null?void 0:n.inputs[0].shape)||!((s=Nt[1])==null?void 0:s.inputs[0].shape)?[]:(ca=[e.shape[2]||0,e.shape[1]||0],t0++,t.skipFrame&&t0<=(t.hand.skipFrames||0)&&(t.hand.skipTime||0)<=Ae()-pb?Xt.hands:new Promise(async r=>{t.skipFrame&&Xt.hands.length===t.hand.maxDetected?Xt.hands=await Promise.all(Xt.boxes.map(o=>hb(e,o,t))):t.skipFrame&&t0<3*(t.hand.skipFrames||0)&&(t.hand.skipTime||0)<=3*(Ae()-pb)&&Xt.hands.length>0?Xt.hands=await Promise.all(Xt.boxes.map(o=>hb(e,o,t))):(Xt.boxes=await Ege(e,t),pb=Ae(),Xt.hands=await Promise.all(Xt.boxes.map(o=>hb(e,o,t))),t0=0);let a=[...Xt.boxes];if(Xt.boxes.length=0,t.cacheSensitivity>0)for(let o=0;o.05&&i.box[3]/(e.shape[1]||1)>.05&&Xt.hands[o].fingerScore&&Xt.hands[o].fingerScore>(t.hand.minConfidence||0)){let l=e0(i.box,B8),c=e0(i.boxRaw,B8),u=db(c);Xt.boxes.push({...a[o],box:l,boxRaw:c,boxCrop:u})}}for(let o=0;os0,horizontal:()=>mb,kpt:()=>n0,relative:()=>Ab,vertical:()=>gb});var n0=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"],mb=[["leftEye","rightEye"],["leftEar","rightEar"],["leftShoulder","rightShoulder"],["leftElbow","rightElbow"],["leftWrist","rightWrist"],["leftHip","rightHip"],["leftKnee","rightKnee"],["leftAnkle","rightAnkle"]],gb=[["leftKnee","leftShoulder"],["rightKnee","rightShoulder"],["leftAnkle","leftKnee"],["rightAnkle","rightKnee"]],Ab=[[["leftHip","rightHip"],["leftShoulder","rightShoulder"]],[["leftElbow","rightElbow"],["leftShoulder","rightShoulder"]]],s0={leftLeg:["leftHip","leftKnee","leftAnkle"],rightLeg:["rightHip","rightKnee","rightAnkle"],torso:["leftShoulder","rightShoulder","rightHip","leftHip","leftShoulder"],leftArm:["leftShoulder","leftElbow","leftWrist"],rightArm:["rightShoulder","rightElbow","rightWrist"],head:[]};var G8=.005,vs={keypoints:[],padding:[[0,0],[0,0],[0,0],[0,0]]};function xb(e){for(let t of mb){let n=e.keypoints.findIndex(r=>r.part===t[0]),s=e.keypoints.findIndex(r=>r.part===t[1]);if(e.keypoints[n]&&e.keypoints[s]&&e.keypoints[n].position[0]r&&r.part===t[0]),s=e.keypoints.findIndex(r=>r&&r.part===t[1]);e.keypoints[n]&&e.keypoints[s]&&e.keypoints[n].position[1]c&&c.part===t[0]),r=e.keypoints.findIndex(c=>c&&c.part===t[1]),a=e.keypoints.findIndex(c=>c&&c.part===n[0]),o=e.keypoints.findIndex(c=>c&&c.part===n[1]);if(!e.keypoints[a]||!e.keypoints[o])continue;let i=e.keypoints[s]?[Math.abs(e.keypoints[a].position[0]-e.keypoints[s].position[0]),Math.abs(e.keypoints[o].position[0]-e.keypoints[s].position[0])]:[0,0],l=e.keypoints[r]?[Math.abs(e.keypoints[o].position[0]-e.keypoints[r].position[0]),Math.abs(e.keypoints[a].position[0]-e.keypoints[r].position[0])]:[0,0];if(i[0]>i[1]||l[0]>l[1]){let c=e.keypoints[s];e.keypoints[s]=e.keypoints[r],e.keypoints[r]=c}}}function H8(e){for(let t=0;te.shape[1]?Math.trunc((e.shape[2]-e.shape[1])/2):0,e.shape[2]>e.shape[1]?Math.trunc((e.shape[2]-e.shape[1])/2):0],[e.shape[1]>e.shape[2]?Math.trunc((e.shape[1]-e.shape[2])/2):0,e.shape[1]>e.shape[2]?Math.trunc((e.shape[1]-e.shape[2])/2):0],[0,0]],n.pad=qs(e,vs.padding),n.resize=$e.resizeBilinear(n.pad,[t,t]);let s=de(n.resize,"int32");return Object.keys(n).forEach(r=>Q(n[r])),s}function q8(e,t){e.keypoints=e.keypoints.filter(s=>s&&s.position);for(let s of e.keypoints)s.position=[s.position[0]*(t[0]+vs.padding[2][0]+vs.padding[2][1])/t[0]-vs.padding[2][0],s.position[1]*(t[1]+vs.padding[1][0]+vs.padding[1][1])/t[1]-vs.padding[1][0]],s.positionRaw=[s.position[0]/t[0],s.position[1]/t[1]];let n=Tl(e.keypoints.map(s=>s.position),t);return e.box=n.box,e.boxRaw=n.boxRaw,e}var Fn,r0=0,bb=Number.MAX_SAFE_INTEGER,Nl={boxes:[],bodies:[],last:0};async function X8(e){return be.initial&&(Fn=null),Fn?e.debug&&ae("cached model:",Fn.modelUrl):(dc(["size"],e),Fn=await st(at(e.modelBasePath,e.body.modelPath||"")),!Fn||!Fn.modelUrl?ae("load model failed:",e.body.modelPath):e.debug&&ae("load model:",Fn.modelUrl)),r0=Fn.inputs[0].shape?Fn.inputs[0].shape[2]:0,r0===-1&&(r0=256),Fn}async function Rge(e,t,n,s){let r=e[0][0],a=[],o=0;for(let d=0;dt.body.minConfidence){let p=[(s[3]-s[1])*r[d][1]+s[1],(s[2]-s[0])*r[d][0]+s[0]];a.push({score:Math.round(100*o)/100,part:n0[d],positionRaw:p,position:[Math.round((n.shape[2]||0)*p[0]),Math.round((n.shape[1]||0)*p[1])]})}o=a.reduce((d,p)=>p.score>d?p.score:d,0);let i=[],l=Tl(a.map(d=>d.position),[n.shape[2],n.shape[1]]),c={};for(let[d,p]of Object.entries(s0)){let h=[];for(let f=0;fA.part===p[f]),g=a.find(A=>A.part===p[f+1]);m&&g&&m.score>(t.body.minConfidence||0)&&g.score>(t.body.minConfidence||0)&&h.push([m.position,g.position])}c[d]=h}let u={id:0,score:o,box:l.box,boxRaw:l.boxRaw,keypoints:a,annotations:c};return xb(u),i.push(u),i}async function $ge(e,t,n,s){let r=[];for(let a=0;at.body.minConfidence){let l=[];for(let p=0;p<17;p++){let h=o[3*p+2];if(h>t.body.minConfidence){let f=[(s[3]-s[1])*o[3*p+1]+s[1],(s[2]-s[0])*o[3*p+0]+s[0]];l.push({part:n0[p],score:Math.round(100*h)/100,positionRaw:f,position:[Math.round((n.shape[2]||0)*f[0]),Math.round((n.shape[1]||0)*f[1])]})}}let c=Tl(l.map(p=>p.position),[n.shape[2],n.shape[1]]),u={};for(let[p,h]of Object.entries(s0)){let f=[];for(let m=0;my.part===h[m]),A=l.find(y=>y.part===h[m+1]);g&&A&&g.score>(t.body.minConfidence||0)&&A.score>(t.body.minConfidence||0)&&f.push([g.position,A.position])}u[p]=f}let d={id:a,score:i,box:c.box,boxRaw:c.boxRaw,keypoints:[...l],annotations:u};xb(d),r.push(d)}}return r.sort((a,o)=>o.score-a.score),r.length>t.body.maxDetected&&(r.length=t.body.maxDetected),r}async function vb(e,t){return!Fn||!(Fn==null?void 0:Fn.inputs[0].shape)?[]:(t.skipFrame||(Nl.boxes.length=0),bb++,t.skipFrame&&bb<=(t.body.skipFrames||0)&&(t.body.skipTime||0)<=Ae()-Nl.last?Nl.bodies:new Promise(async n=>{let s={};bb=0,s.input=j8(e,r0),s.res=await(Fn==null?void 0:Fn.predict(s.input)),Nl.last=Ae();let r=await s.res.array();Nl.bodies=s.res.shape[2]===17?await Rge(r,t,e,[0,0,1,1]):await $ge(r,t,e,[0,0,1,1]);for(let a of Nl.bodies)q8(a,[e.shape[2]||1,e.shape[1]||1]),H8(a.keypoints);Object.keys(s).forEach(a=>Q(s[a])),n(Nl.bodies)}))}var ws,a0=[],K8=0,wb=Number.MAX_SAFE_INTEGER,o0=2.5;async function Z8(e){if(!ws||be.initial){ws=await st(at(e.modelBasePath,e.object.modelPath||""));let t=Object.values(ws.modelSignature.inputs);if(ws.inputSize=Array.isArray(t)?parseInt(t[0].tensorShape.dim[2].size):null,!ws.inputSize)throw new Error(`cannot determine model inputSize: ${e.object.modelPath}`);!ws||!ws.modelUrl?ae("load model failed:",e.object.modelPath):e.debug&&ae("load model:",ws.modelUrl)}else e.debug&&ae("cached model:",ws.modelUrl);return ws}async function Dge(e,t,n,s){let r=0,a=[];for(let c of[1,2,4])j(async()=>{var g,A;let u=c*13,d=(g=e.find(y=>y.shape[1]===u**2&&y.shape[2]===cc.length))==null?void 0:g.squeeze(),p=(A=e.find(y=>y.shape[1]===u**2&&y.shape[2]s.object.minConfidence&&x!==61){let w=(.5+Math.trunc(y%u))/u,k=(.5+Math.trunc(y/u))/u,S=f[y].map(U=>U*(u/c/t)),[E,P]=[w-o0/c*S[0],k-o0/c*S[1]],[F,R]=[w+o0/c*S[2]-E,k+o0/c*S[3]-P],_=[E,P,F,R];_=_.map(U=>Math.max(0,Math.min(U,1)));let T=[_[0]*n[0],_[1]*n[1],_[2]*n[0],_[3]*n[1]],M={id:r++,score:Math.round(100*b)/100,class:x+1,label:cc[x].label,box:T.map(U=>Math.trunc(U)),boxRaw:_};a.push(M)}}});e.forEach(c=>Q(c));let o=a.map(c=>[c.boxRaw[1],c.boxRaw[0],c.boxRaw[3],c.boxRaw[2]]),i=a.map(c=>c.score),l=[];if(o&&o.length>0){let c=await $e.nonMaxSuppressionAsync(o,i,s.object.maxDetected,s.object.iouThreshold,s.object.minConfidence);l=await c.data(),Q(c)}return a=a.filter((c,u)=>l.includes(u)).sort((c,u)=>u.score-c.score),a}async function kb(e,t){return wb<(t.object.skipFrames||0)&&(t.object.skipTime||0)<=Ae()-K8&&t.skipFrame&&a0.length>0?(wb++,a0):(wb=0,!be.kernels.includes("mod")||!be.kernels.includes("sparsetodense")?a0:new Promise(async n=>{let s=[e.shape[2],e.shape[1]],r=$e.resizeBilinear(e,[ws.inputSize,ws.inputSize],!1),a=he(r,255),o=a.transpose([0,3,1,2]);Q(a),Q(r);let i;t.object.enabled&&(i=await ws.predict(o)),K8=Ae(),Q(o);let l=await Dge(i,ws.inputSize,s,t);a0=l,n(l)}))}var Ap=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"],_ge=Ap.length,yp=Ap.reduce((e,t,n)=>(e[t]=n,e),{}),Pge=[["leftHip","leftShoulder"],["leftElbow","leftShoulder"],["leftElbow","leftWrist"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["rightHip","rightShoulder"],["rightElbow","rightShoulder"],["rightElbow","rightWrist"],["rightHip","rightKnee"],["rightKnee","rightAnkle"],["leftShoulder","rightShoulder"],["leftHip","rightHip"]],hAe=Pge.map(([e,t])=>[yp[e],yp[t]]),Y8=[["nose","leftEye"],["leftEye","leftEar"],["nose","rightEye"],["rightEye","rightEar"],["nose","leftShoulder"],["leftShoulder","leftElbow"],["leftElbow","leftWrist"],["leftShoulder","leftHip"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["nose","rightShoulder"],["rightShoulder","rightElbow"],["rightElbow","rightWrist"],["rightShoulder","rightHip"],["rightHip","rightKnee"],["rightKnee","rightAnkle"]];function J8(e){let t=e.reduce(({maxX:n,maxY:s,minX:r,minY:a},{position:{x:o,y:i}})=>({maxX:Math.max(n,o),maxY:Math.max(s,i),minX:Math.min(r,o),minY:Math.min(a,i)}),{maxX:Number.NEGATIVE_INFINITY,maxY:Number.NEGATIVE_INFINITY,minX:Number.POSITIVE_INFINITY,minY:Number.POSITIVE_INFINITY});return[t.minX,t.minY,t.maxX-t.minX,t.maxY-t.minY]}function Q8(e,[t,n],[s,r]){let a=t/s,o=n/r,i=(c,u)=>({id:u,score:c.score,boxRaw:[c.box[0]/r,c.box[1]/s,c.box[2]/r,c.box[3]/s],box:[Math.trunc(c.box[0]*o),Math.trunc(c.box[1]*a),Math.trunc(c.box[2]*o),Math.trunc(c.box[3]*a)],keypoints:c.keypoints.map(({score:d,part:p,position:h})=>({score:d,part:p,position:[Math.trunc(h.x*o),Math.trunc(h.y*a)],positionRaw:[h.x/s,h.y/s]}))});return e.map((c,u)=>i(c,u))}var Ib=class{constructor(t,n){pe(this,"priorityQueue");pe(this,"numberOfElements");pe(this,"getElementValue");this.priorityQueue=new Array(t),this.numberOfElements=-1,this.getElementValue=n}enqueue(t){this.priorityQueue[++this.numberOfElements]=t,this.swim(this.numberOfElements)}dequeue(){let t=this.priorityQueue[0];return this.exchange(0,this.numberOfElements--),this.sink(0),this.priorityQueue[this.numberOfElements+1]=null,t}empty(){return this.numberOfElements===-1}size(){return this.numberOfElements+1}all(){return this.priorityQueue.slice(0,this.numberOfElements+1)}max(){return this.priorityQueue[0]}swim(t){for(;t>0&&this.less(Math.floor(t/2),t);)this.exchange(t,Math.floor(t/2)),t=Math.floor(t/2)}sink(t){for(;2*t<=this.numberOfElements;){let n=2*t;if(nn?n:e}function eT(e,t,n,s){let r=n-e,a=s-t;return r*r+a*a}function Nb(e,t){return{x:e.x+t.x,y:e.y+t.y}}var ks,Fge=["MobilenetV1/offset_2/BiasAdd","MobilenetV1/heatmap_2/BiasAdd","MobilenetV1/displacement_fwd_2/BiasAdd","MobilenetV1/displacement_bwd_2/BiasAdd"],i0=1,fc=16,Oge=50**2;function tT(e,t,n,s,r,a,o=2){let i=A=>({y:a.get(A.y,A.x,e),x:a.get(A.y,A.x,a.shape[2]/2+e)}),l=(A,y,x)=>({y:Tb(Math.round(A.y/fc),0,y-1),x:Tb(Math.round(A.x/fc),0,x-1)}),[c,u]=s.shape,d=l(t.position,c,u),p=i(d),f=Nb(t.position,p);for(let A=0;A[yp[p],yp[h]]),o=a.map(([,p])=>p),i=a.map(([p])=>p),l=t.shape[2],c=o.length,u=new Array(l),d=Cb(e.part,fc,n);u[e.part.id]={score:e.score,part:Ap[e.part.id],position:d};for(let p=c-1;p>=0;--p){let h=o[p],f=i[p];u[h]&&!u[f]&&(u[f]=tT(p,u[h],f,t,n,r))}for(let p=0;pt){i=!1;break}if(!i)break}return i}function Lge(e,t){let[n,s,r]=t.shape,a=new Ib(n*s*r,({score:o})=>o);for(let o=0;o{var o;let a=(o=r[s])==null?void 0:o.position;return a?eT(n,t,a.y,a.x)<=Oge:!1})}function Bge(e,t){return t.reduce((s,{position:r,score:a},o)=>(nT(e,r,o)||(s+=a),s),0)/t.length}function Wge(e,t,n,s,r,a){let o=[],i=Lge(a,t);for(;o.lengthh.score>a);let d=Bge(o,u),p=J8(u);d>a&&o.push({keypoints:u,box:p,score:Math.round(100*d)/100})}return o}async function Eb(e,t){let n=j(()=>{if(!ks.inputs[0].shape)return[];let o=$e.resizeBilinear(e,[ks.inputs[0].shape[2],ks.inputs[0].shape[1]]),i=ye(he(de(o,"float32"),127.5),1),c=ks.execute(i,Fge).map(u=>pt(u,[0]));return c[1]=c[1].sigmoid(),c}),s=await Promise.all(n.map(o=>o.buffer()));for(let o of n)Q(o);let r=await Wge(s[0],s[1],s[2],s[3],t.body.maxDetected,t.body.minConfidence);return ks.inputs[0].shape?Q8(r,[e.shape[1],e.shape[2]],[ks.inputs[0].shape[2],ks.inputs[0].shape[1]]):[]}async function sT(e){return!ks||be.initial?(ks=await st(at(e.modelBasePath,e.body.modelPath||"")),!ks||!ks.modelUrl?ae("load model failed:",e.body.modelPath):e.debug&&ae("load model:",ks.modelUrl)):e.debug&&ae("cached model:",ks.modelUrl),ks}var zs,Rb=!1;async function $b(e){return!zs||be.initial?(zs=await st(at(e.modelBasePath,e.segmentation.modelPath||"")),!zs||!zs.modelUrl?ae("load model failed:",e.segmentation.modelPath):e.debug&&ae("load model:",zs.modelUrl)):e.debug&&ae("cached model:",zs.modelUrl),zs}async function rT(e,t,n){var m,g;if(Rb)return{data:[],canvas:null,alpha:null};Rb=!0,zs||await $b(n);let s=uc(e,n),r=((m=s.canvas)==null?void 0:m.width)||0,a=((g=s.canvas)==null?void 0:g.height)||0;if(!s.tensor)return{data:[],canvas:null,alpha:null};let o={};o.resize=$e.resizeBilinear(s.tensor,[zs.inputs[0].shape?zs.inputs[0].shape[1]:0,zs.inputs[0].shape?zs.inputs[0].shape[2]:0],!1),Q(s.tensor),o.norm=he(o.resize,255),o.res=zs.predict(o.norm),o.squeeze=pt(o.res,0),o.squeeze.shape[2]===2?(o.softmax=$u(o.squeeze),[o.bg,o.fg]=as(o.softmax,2),o.expand=Kt(o.fg,2),o.pad=Kt(o.expand,0),o.crop=$e.cropAndResize(o.pad,[[0,0,.5,.5]],[0],[r,a]),o.data=pt(o.crop,0)):o.data=$e.resizeBilinear(o.squeeze,[a,r]);let i=Array.from(await o.data.data());if(be.node&&!be.Canvas&&typeof ImageData=="undefined")return n.debug&&ae("canvas support missing"),Object.keys(o).forEach(A=>Q(o[A])),{data:i,canvas:null,alpha:null};let l=Kn(r,a);await Gs.toPixels(o.data,l);let c=l.getContext("2d");n.segmentation.blur&&n.segmentation.blur>0&&(c.filter=`blur(${n.segmentation.blur}px)`);let u=c.getImageData(0,0,r,a),d=Kn(r,a),p=d.getContext("2d");s.canvas&&p.drawImage(s.canvas,0,0),p.globalCompositeOperation="darken",n.segmentation.blur&&n.segmentation.blur>0&&(p.filter=`blur(${n.segmentation.blur}px)`),p.drawImage(l,0,0),p.globalCompositeOperation="source-over",p.filter="none";let h=p.getImageData(0,0,r,a);for(let A=0;AQ(o[A])),Rb=!1,{data:i,canvas:f||d,alpha:l}}var l0=class{constructor(){pe(this,"age",null);pe(this,"agegenderrace",null);pe(this,"blazeposedetect",null);pe(this,"blazepose",null);pe(this,"centernet",null);pe(this,"efficientpose",null);pe(this,"embedding",null);pe(this,"emotion",null);pe(this,"facedetect",null);pe(this,"faceiris",null);pe(this,"facemesh",null);pe(this,"faceres",null);pe(this,"gender",null);pe(this,"handpose",null);pe(this,"handskeleton",null);pe(this,"handtrack",null);pe(this,"movenet",null);pe(this,"nanodet",null);pe(this,"posenet",null);pe(this,"segmentation",null);pe(this,"antispoof",null)}};function Db(e){for(let t of Object.keys(e.models))e.models[t]=null}async function aT(e){var t,n,s,r,a,o,i,l,c,u,d,p,h,f,m,g,A,y,x,b,w,k,S,E,P,F,R,_,T,M,U;be.initial&&Db(e),e.config.hand.enabled&&(!e.models.handpose&&((n=(t=e.config.hand.detector)==null?void 0:t.modelPath)==null?void 0:n.includes("handdetect"))&&([e.models.handpose,e.models.handskeleton]=await cb(e.config)),!e.models.handskeleton&&e.config.hand.landmarks&&((r=(s=e.config.hand.detector)==null?void 0:s.modelPath)==null?void 0:r.includes("handdetect"))&&([e.models.handpose,e.models.handskeleton]=await cb(e.config))),e.config.face.enabled&&!e.models.facedetect&&(e.models.facedetect=H6(e.config)),e.config.face.enabled&&((a=e.config.face.mesh)==null?void 0:a.enabled)&&!e.models.facemesh&&(e.models.facemesh=p8(e.config)),e.config.face.enabled&&((o=e.config.face.iris)==null?void 0:o.enabled)&&!e.models.faceiris&&(e.models.faceiris=r8(e.config)),e.config.face.enabled&&((i=e.config.face.antispoof)==null?void 0:i.enabled)&&!e.models.antispoof&&(e.models.antispoof=F6(e.config)),e.config.hand.enabled&&!e.models.handtrack&&((c=(l=e.config.hand.detector)==null?void 0:l.modelPath)==null?void 0:c.includes("handtrack"))&&(e.models.handtrack=V8(e.config)),e.config.hand.enabled&&e.config.hand.landmarks&&!e.models.handskeleton&&((d=(u=e.config.hand.detector)==null?void 0:u.modelPath)==null?void 0:d.includes("handtrack"))&&(e.models.handskeleton=U8(e.config)),e.config.body.enabled&&!e.models.posenet&&((h=(p=e.config.body)==null?void 0:p.modelPath)==null?void 0:h.includes("posenet"))&&(e.models.posenet=sT(e.config)),e.config.body.enabled&&!e.models.efficientpose&&((m=(f=e.config.body)==null?void 0:f.modelPath)==null?void 0:m.includes("efficientpose"))&&(e.models.efficientpose=Xx(e.config)),e.config.body.enabled&&!e.models.blazepose&&((A=(g=e.config.body)==null?void 0:g.modelPath)==null?void 0:A.includes("blazepose"))&&(e.models.blazepose=Z6(e.config)),e.config.body.enabled&&!e.models.blazeposedetect&&((y=e.config.body.detector)==null?void 0:y.modelPath)&&((b=(x=e.config.body)==null?void 0:x.modelPath)==null?void 0:b.includes("blazepose"))&&(e.models.blazeposedetect=K6(e.config)),e.config.body.enabled&&!e.models.efficientpose&&((k=(w=e.config.body)==null?void 0:w.modelPath)==null?void 0:k.includes("efficientpose"))&&(e.models.efficientpose=Xx(e.config)),e.config.body.enabled&&!e.models.movenet&&((E=(S=e.config.body)==null?void 0:S.modelPath)==null?void 0:E.includes("movenet"))&&(e.models.movenet=X8(e.config)),e.config.object.enabled&&!e.models.nanodet&&((F=(P=e.config.object)==null?void 0:P.modelPath)==null?void 0:F.includes("nanodet"))&&(e.models.nanodet=Z8(e.config)),e.config.object.enabled&&!e.models.centernet&&((_=(R=e.config.object)==null?void 0:R.modelPath)==null?void 0:_.includes("centernet"))&&(e.models.centernet=Q6(e.config)),e.config.face.enabled&&((T=e.config.face.emotion)==null?void 0:T.enabled)&&!e.models.emotion&&(e.models.emotion=s8(e.config)),e.config.face.enabled&&((M=e.config.face.description)==null?void 0:M.enabled)&&!e.models.faceres&&(e.models.faceres=A8(e.config)),e.config.segmentation.enabled&&!e.models.segmentation&&(e.models.segmentation=$b(e.config)),e.config.face.enabled&&((U=e.config.face.agegenderrace)==null?void 0:U.enabled)&&!e.models.agegenderrace&&(e.models.agegenderrace=D6(e.config));for await(let H of Object.keys(e.models))e.models[H]&&typeof e.models[H]!="undefined"&&(e.models[H]=await e.models[H])}async function oT(e){let t=["const","placeholder","noop","pad","squeeze","add","sub","mul","div"];for(let n of Object.keys(e.models))if(e.models[n]){let s=[];Array.isArray(e.models[n])?s=e.models[n].filter(r=>r!==null).map(r=>r&&r.executor?r:r.model):s=[e.models[n]];for(let r of s){if(!r){e.config.debug&&ae("model marked as loaded but not defined:",n);continue}let a=[],o=r==null?void 0:r.executor;if(o&&o.graph.nodes)for(let l of Object.values(o.graph.nodes)){let c=l.op.toLowerCase();a.includes(c)||a.push(c)}else!o&&e.config.debug&&ae("model signature not determined:",n);let i=[];for(let l of a)!t.includes(l)&&!e.env.kernels.includes(l)&&!e.env.kernels.includes(l.replace("_",""))&&!e.env.kernels.includes(l.replace("native",""))&&!e.env.kernels.includes(l.replace("v2",""))&&i.push(l);i.length>0&&e.config.debug&&ae("model validation:",n,i)}}}var zt={name:"humangl",priority:999,canvas:null,gl:null,extensions:[],webGLattr:{alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!1,desynchronized:!0}};function Vge(){let e=zt.gl;!e||(zt.extensions=e.getSupportedExtensions())}async function iT(e){var t;if(e.config.backend==="humangl"&&(zt.name in ss().registry&&(!zt.gl||!zt.gl.getParameter(zt.gl.VERSION))&&(ae("error: humangl backend invalid context"),Db(e)),!S2(zt.name))){try{zt.canvas=await Kn(100,100)}catch(s){ae("error: cannot create canvas:",s);return}try{zt.gl=(t=zt.canvas)==null?void 0:t.getContext("webgl2",zt.webGLattr),zt.canvas&&(zt.canvas.addEventListener("webglcontextlost",async s=>{throw ae("error: humangl:",s.type),ae("possible browser memory leak using webgl or conflict with multiple backend registrations"),e.emit("error"),new Error("browser webgl error")}),zt.canvas.addEventListener("webglcontextrestored",s=>{ae("error: humangl context restored:",s)}),zt.canvas.addEventListener("webglcontextcreationerror",s=>{ae("error: humangl context create:",s)}))}catch(s){ae("error: cannot get WebGL context:",s);return}try{pm(2,zt.gl)}catch(s){ae("error: cannot set WebGL context:",s);return}try{let s=new vm(zt.gl);Ki(zt.name,()=>new Kd(s),zt.priority)}catch(s){ae("error: cannot register WebGL backend:",s);return}try{Xr("webgl").forEach(r=>{let a={...r,backendName:zt.name};Kr(a)})}catch(s){ae("error: cannot update WebGL backend registration:",s);return}let n=Tr().getGPGPUContext?Tr().getGPGPUContext().gl:null;if(n)ae(`humangl webgl version:${n.getParameter(n.VERSION)} renderer:${n.getParameter(n.RENDERER)}`);else{ae("error: no current gl context:",n,zt.gl);return}try{Ir.set("WEBGL_VERSION",2)}catch(s){ae("error: cannot set WebGL backend flags:",s);return}Vge(),ae("backend registered:",zt.name)}}async function u0(e,t=!1){if(e.state="backend",t||be.initial||e.config.backend&&e.config.backend.length>0&&ir()!==e.config.backend){let n=Ae();if(e.config.backend&&e.config.backend.length>0){if(typeof window=="undefined"&&typeof WorkerGlobalScope!="undefined"&&e.config.debug&&e.config.debug&&ae("running inside web worker"),be.browser&&e.config.backend==="tensorflow"&&(e.config.debug&&ae("override: backend set to tensorflow while running in browser"),e.config.backend="humangl"),be.node&&(e.config.backend==="webgl"||e.config.backend==="humangl")&&(e.config.debug&&ae(`override: backend set to ${e.config.backend} while running in nodejs`),e.config.backend="tensorflow"),be.browser&&e.config.backend==="webgpu")if(typeof navigator=="undefined"||typeof navigator.gpu=="undefined")ae("override: backend set to webgpu but browser does not support webgpu"),e.config.backend="humangl";else{let r=await navigator.gpu.requestAdapter();e.config.debug&&ae("enumerated webgpu adapter:",r)}e.config.backend==="humangl"&&await iT(e);let s=Object.keys(ss().registryFactory);if(e.config.debug&&ae("available backends:",s),s.includes(e.config.backend)||(ae(`error: backend ${e.config.backend} not found in registry`),e.config.backend=be.node?"tensorflow":"webgl",e.config.debug&&ae(`override: setting backend ${e.config.backend}`)),e.config.debug&&ae("setting backend:",e.config.backend),e.config.backend==="wasm"){if(e.config.debug&&ae("wasm path:",e.config.wasmPath),typeof(wl==null?void 0:wl.setWasmPaths)!="undefined")await b6(e.config.wasmPath);else throw new Error("wasm backend is not loaded");let r=await K().getAsync("WASM_HAS_SIMD_SUPPORT"),a=await K().getAsync("WASM_HAS_MULTITHREAD_SUPPORT");e.config.debug&&ae(`wasm execution: ${r?"SIMD":"no SIMD"} ${a?"multithreaded":"singlethreaded"}`),e.config.debug&&!r&&ae("warning: wasm simd support is not enabled")}try{await g3(e.config.backend),await Wh()}catch(r){return ae("error: cannot set backend:",e.config.backend,r),!1}}if(ir()==="humangl"&&(Ir.set("CHECK_COMPUTATION_FOR_ERRORS",!1),Ir.set("WEBGL_CPU_FORWARD",!0),Ir.set("WEBGL_USE_SHAPES_UNIFORMS",!0),Ir.set("CPU_HANDOFF_SIZE_THRESHOLD",256),typeof e.config.deallocate!="undefined"&&e.config.deallocate&&(ae("changing webgl: WEBGL_DELETE_TEXTURE_THRESHOLD:",!0),Ir.set("WEBGL_DELETE_TEXTURE_THRESHOLD",0)),Tr().getGPGPUContext)){let s=await Tr().getGPGPUContext().gl;e.config.debug&&ae(`gl version:${s.getParameter(s.VERSION)} renderer:${s.getParameter(s.RENDERER)}`)}ir()==="webgpu",m3(),await Wh(),e.performance.backend=Math.trunc(Ae()-n),e.config.backend=ir(),be.updateBackend()}return!0}function dc(e,t){for(let n of e){let s={kernelName:n,backendName:t.backend,kernelFunc:()=>{t.debug&&ae("kernelFunc",n,t.backend)}};Kr(s)}be.kernels=Xr(ir()).map(n=>n.kernelName.toLowerCase())}var da={color:"rgba(173, 216, 230, 0.6)",labelColor:"rgba(173, 216, 230, 1)",shadowColor:"black",font:'small-caps 14px "Segoe UI"',lineHeight:18,lineWidth:4,pointSize:2,roundRect:8,drawPoints:!1,drawLabels:!0,drawBoxes:!0,drawGestures:!0,drawPolygons:!0,drawGaze:!0,fillPolygons:!1,useDepth:!0,useCurves:!1,bufferedOutput:!0},El=e=>{if(e&&e.getContext)return e.getContext("2d");throw new Error("invalid canvas")},mc=e=>Math.round(e*180/Math.PI);function _b(e,t,n,s=0,r){e.fillStyle=r.useDepth&&s?`rgba(${127.5+2*s}, ${127.5-2*s}, 255, 0.3)`:r.color,e.beginPath(),e.arc(t,n,r.pointSize,0,2*Math.PI),e.fill()}function xp(e,t,n,s,r,a){if(e.beginPath(),a.useCurves){let o=(t+t+s)/2,i=(n+n+r)/2;e.ellipse(o,i,s/2,r/2,0,0,2*Math.PI)}else e.lineWidth=a.lineWidth,e.moveTo(t+a.roundRect,n),e.lineTo(t+s-a.roundRect,n),e.quadraticCurveTo(t+s,n,t+s,n+a.roundRect),e.lineTo(t+s,n+r-a.roundRect),e.quadraticCurveTo(t+s,n+r,t+s-a.roundRect,n+r),e.lineTo(t+a.roundRect,n+r),e.quadraticCurveTo(t,n+r,t,n+r-a.roundRect),e.lineTo(t,n+a.roundRect),e.quadraticCurveTo(t,n,t+a.roundRect,n),e.closePath();e.stroke()}function lT(e,t=[],n){if(!(t===void 0||t.length===0)){e.beginPath(),e.moveTo(t[0][0],t[0][1]);for(let s of t){let r=s[2]||0;e.strokeStyle=n.useDepth&&r?`rgba(${127.5+2*r}, ${127.5-2*r}, 255, 0.3)`:n.color,e.fillStyle=n.useDepth&&r?`rgba(${127.5+2*r}, ${127.5-2*r}, 255, 0.3)`:n.color,e.lineTo(s[0],Math.round(s[1]))}e.stroke(),n.fillPolygons&&(e.closePath(),e.fill())}}function Uge(e,t=[],n){if(!(t===void 0||t.length===0)){if(!n.useCurves||t.length<=2){lT(e,t,n);return}e.moveTo(t[0][0],t[0][1]);for(let s=0;s1&&l[1].length>0){let c=i[1]>0?`#${i[1]}`:"",u=`${i[0]} ${c}: ${l[1]}`;s.shadowColor&&s.shadowColor!==""&&(r.fillStyle=s.shadowColor,r.fillText(u,8,2+a*s.lineHeight)),r.fillStyle=s.labelColor,r.fillText(u,6,0+a*s.lineHeight),a+=1}}}}async function Fb(e,t,n){var a,o,i,l,c;let s=$n(da,n);if(!t||!e)return;let r=El(e);for(let u of t){if(r.font=s.font,r.strokeStyle=s.color,r.fillStyle=s.color,s.drawBoxes&&xp(r,u.box[0],u.box[1],u.box[2],u.box[3],s),s.drawLabels){let d=[];if(d.push(`face: ${Math.trunc(100*u.score)}%`),u.genderScore&&d.push(`${u.gender||""} ${Math.trunc(100*u.genderScore)}%`),u.age&&d.push(`age: ${u.age||""}`),u.iris&&d.push(`distance: ${u.iris}`),u.real&&d.push(`real: ${Math.trunc(100*u.real)}%`),u.emotion&&u.emotion.length>0){let p=u.emotion.map(h=>`${Math.trunc(100*h.score)}% ${h.emotion}`);p.length>3&&(p.length=3),d.push(p.join(" "))}u.rotation&&u.rotation.angle&&u.rotation.gaze&&(u.rotation.angle.roll&&d.push(`roll: ${mc(u.rotation.angle.roll)}\xB0 yaw:${mc(u.rotation.angle.yaw)}\xB0 pitch:${mc(u.rotation.angle.pitch)}\xB0`),u.rotation.gaze.bearing&&d.push(`gaze: ${mc(u.rotation.gaze.bearing)}\xB0`)),d.length===0&&d.push("face"),r.fillStyle=s.color;for(let p=d.length-1;p>=0;p--){let h=Math.max(u.box[0],0),f=p*s.lineHeight+u.box[1];s.shadowColor&&s.shadowColor!==""&&(r.fillStyle=s.shadowColor,r.fillText(d[p],h+5,f+16)),r.fillStyle=s.labelColor,r.fillText(d[p],h+4,f+15)}}if(r.lineWidth=1,u.mesh&&u.mesh.length>0){if(s.drawPoints)for(let d of u.mesh)_b(r,d[0],d[1],d[2],s);if(s.drawPolygons){if(r.lineWidth=1,u.mesh.length>450)for(let d=0;du.mesh[h]);lT(r,p,s)}if(u.annotations&&u.annotations.leftEyeIris&&u.annotations.leftEyeIris[0]){r.strokeStyle=s.useDepth?"rgba(255, 200, 255, 0.3)":s.color,r.beginPath();let d=Math.abs(u.annotations.leftEyeIris[3][0]-u.annotations.leftEyeIris[1][0])/2,p=Math.abs(u.annotations.leftEyeIris[4][1]-u.annotations.leftEyeIris[2][1])/2;r.ellipse(u.annotations.leftEyeIris[0][0],u.annotations.leftEyeIris[0][1],d,p,0,0,2*Math.PI),r.stroke(),s.fillPolygons&&(r.fillStyle=s.useDepth?"rgba(255, 255, 200, 0.3)":s.color,r.fill())}if(u.annotations&&u.annotations.rightEyeIris&&u.annotations.rightEyeIris[0]){r.strokeStyle=s.useDepth?"rgba(255, 200, 255, 0.3)":s.color,r.beginPath();let d=Math.abs(u.annotations.rightEyeIris[3][0]-u.annotations.rightEyeIris[1][0])/2,p=Math.abs(u.annotations.rightEyeIris[4][1]-u.annotations.rightEyeIris[2][1])/2;r.ellipse(u.annotations.rightEyeIris[0][0],u.annotations.rightEyeIris[0][1],d,p,0,0,2*Math.PI),r.stroke(),s.fillPolygons&&(r.fillStyle=s.useDepth?"rgba(255, 255, 200, 0.3)":s.color,r.fill())}if(s.drawGaze&&((a=u.rotation)==null?void 0:a.angle)){r.strokeStyle="pink";let d=u.box[0]+u.box[2]/2-u.box[3]*mc(u.rotation.angle.yaw)/90,p=u.box[1]+u.box[3]/2+u.box[2]*mc(u.rotation.angle.pitch)/90,h=new Path2D(` +`;var bx=(e,t,n)=>{let s=new RegExp("\\b"+t+" \\w+ (\\w+)","ig");e.replace(s,(r,a)=>(n[a]=0,r))},E6=class{constructor(t,n,s){de(this,"uniform",{});de(this,"attribute",{});de(this,"gl");de(this,"id");de(this,"compile",(t,n)=>{let s=this.gl.createShader(n);if(this.gl.shaderSource(s,t),this.gl.compileShader(s),!this.gl.getShaderParameter(s,this.gl.COMPILE_STATUS))throw new Error(`filter: gl compile failed: ${this.gl.getShaderInfoLog(s)}`);return s});this.gl=t;let r=this.compile(n,this.gl.VERTEX_SHADER),a=this.compile(s,this.gl.FRAGMENT_SHADER);if(this.id=this.gl.createProgram(),this.gl.attachShader(this.id,r),this.gl.attachShader(this.id,a),this.gl.linkProgram(this.id),!this.gl.getProgramParameter(this.id,this.gl.LINK_STATUS))throw new Error(`filter: gl link failed: ${this.gl.getProgramInfoLog(this.id)}`);this.gl.useProgram(this.id),bx(n,"attribute",this.attribute);for(let o in this.attribute)this.attribute[o]=this.gl.getAttribLocation(this.id,o);bx(n,"uniform",this.uniform),bx(s,"uniform",this.uniform);for(let o in this.uniform)this.uniform[o]=this.gl.getUniformLocation(this.id,o)}};function R6(){let e=0,t=null,n=!1,s=-1,r=[null,null],a=[],o=null,i=null,l=Kn(100,100),c={},u={INTERMEDIATE:1},d=l.getContext("webgl");if(!d)throw new Error("filter: cannot get webgl context");function p(y,x){if(!(y===l.width&&x===l.height)){if(l.width=y,l.height=x,!o){let b=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,-1,1,0,0,1,-1,1,1,1,1,1,0]);o=d.createBuffer(),d.bindBuffer(d.ARRAY_BUFFER,o),d.bufferData(d.ARRAY_BUFFER,b,d.STATIC_DRAW),d.pixelStorei(d.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!0)}d.viewport(0,0,l.width,l.height),r=[null,null]}}function h(y,x){let b=d.createFramebuffer();d.bindFramebuffer(d.FRAMEBUFFER,b);let w=d.createRenderbuffer();d.bindRenderbuffer(d.RENDERBUFFER,w);let k=d.createTexture();return d.bindTexture(d.TEXTURE_2D,k),d.texImage2D(d.TEXTURE_2D,0,d.RGBA,y,x,0,d.RGBA,d.UNSIGNED_BYTE,null),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_MAG_FILTER,d.LINEAR),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_MIN_FILTER,d.LINEAR),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_WRAP_S,d.CLAMP_TO_EDGE),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_WRAP_T,d.CLAMP_TO_EDGE),d.framebufferTexture2D(d.FRAMEBUFFER,d.COLOR_ATTACHMENT0,d.TEXTURE_2D,k,0),d.bindTexture(d.TEXTURE_2D,null),d.bindFramebuffer(d.FRAMEBUFFER,null),{fbo:b,texture:k}}function f(y){return r[y]=r[y]||h(l.width,l.height),r[y]}function m(y=0){var k,S;if(!i)return;let x=null,b=null,w=!1;e===0?x=t:x=((k=f(s))==null?void 0:k.texture)||null,e++,n&&!(y&u.INTERMEDIATE)?(b=null,w=e%2==0):(s=(s+1)%2,b=((S=f(s))==null?void 0:S.fbo)||null),d.bindTexture(d.TEXTURE_2D,x),d.bindFramebuffer(d.FRAMEBUFFER,b),d.uniform1f(i.uniform.flipY,w?-1:1),d.drawArrays(d.TRIANGLES,0,6)}function g(y){if(c[y])return i=c[y],d.useProgram((i==null?void 0:i.id)||null),i;i=new E6(d,k6,y);let x=Float32Array.BYTES_PER_ELEMENT,b=4*x;return d.enableVertexAttribArray(i.attribute.pos),d.vertexAttribPointer(i.attribute.pos,2,d.FLOAT,!1,b,0*x),d.enableVertexAttribArray(i.attribute.uv),d.vertexAttribPointer(i.attribute.uv,2,d.FLOAT,!1,b,2*x),c[y]=i,i}let A={colorMatrix:y=>{let x=new Float32Array(y);x[4]/=255,x[9]/=255,x[14]/=255,x[19]/=255;let b=x[18]===1&&x[3]===0&&x[8]===0&&x[13]===0&&x[15]===0&&x[16]===0&&x[17]===0&&x[19]===0?S6:I6,w=g(b);d.uniform1fv(w==null?void 0:w.uniform.m,x),m()},brightness:y=>{let x=(y||0)+1;A.colorMatrix([x,0,0,0,0,0,x,0,0,0,0,0,x,0,0,0,0,0,1,0])},saturation:y=>{let x=(y||0)*2/3+1,b=(x-1)*-.5;A.colorMatrix([x,b,b,0,0,b,x,b,0,0,b,b,x,0,0,0,0,0,1,0])},desaturate:()=>{A.saturation(-1)},contrast:y=>{let x=(y||0)+1,b=-128*(x-1);A.colorMatrix([x,0,0,0,b,0,x,0,0,b,0,0,x,0,b,0,0,0,1,0])},negative:()=>{A.contrast(-2)},hue:y=>{y=(y||0)/180*Math.PI;let x=Math.cos(y),b=Math.sin(y),w=.213,k=.715,S=.072;A.colorMatrix([w+x*(1-w)+b*-w,k+x*-k+b*-k,S+x*-S+b*(1-S),0,0,w+x*-w+b*.143,k+x*(1-k)+b*.14,S+x*-S+b*-.283,0,0,w+x*-w+b*-(1-w),k+x*-k+b*k,S+x*(1-S)+b*S,0,0,0,0,0,1,0])},desaturateLuminance:()=>{A.colorMatrix([.2764723,.929708,.0938197,0,-37.1,.2764723,.929708,.0938197,0,-37.1,.2764723,.929708,.0938197,0,-37.1,0,0,0,1,0])},sepia:()=>{A.colorMatrix([.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0])},brownie:()=>{A.colorMatrix([.5997023498159715,.34553243048391263,-.2708298674538042,0,47.43192855600873,-.037703249837783157,.8609577587992641,.15059552388459913,0,-36.96841498319127,.24113635128153335,-.07441037908422492,.44972182064877153,0,-7.562075277591283,0,0,0,1,0])},vintagePinhole:()=>{A.colorMatrix([.6279345635605994,.3202183420819367,-.03965408211312453,0,9.651285835294123,.02578397704808868,.6441188644374771,.03259127616149294,0,7.462829176470591,.0466055556782719,-.0851232987247891,.5241648018700465,0,5.159190588235296,0,0,0,1,0])},kodachrome:()=>{A.colorMatrix([1.1285582396593525,-.3967382283601348,-.03992559172921793,0,63.72958762196502,-.16404339962244616,1.0835251566291304,-.05498805115633132,0,24.732407896706203,-.16786010706155763,-.5603416277695248,1.6014850761964943,0,35.62982807460946,0,0,0,1,0])},technicolor:()=>{A.colorMatrix([1.9125277891456083,-.8545344976951645,-.09155508482755585,0,11.793603434377337,-.3087833385928097,1.7658908555458428,-.10601743074722245,0,-70.35205161461398,-.231103377548616,-.7501899197440212,1.847597816108189,0,30.950940869491138,0,0,0,1,0])},polaroid:()=>{A.colorMatrix([1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0])},shiftToBGR:()=>{A.colorMatrix([0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0])},convolution:y=>{let x=new Float32Array(y),b=1/l.width,w=1/l.height,k=g(N6);d.uniform1fv(k==null?void 0:k.uniform.m,x),d.uniform2f(k==null?void 0:k.uniform.px,b,w),m()},detectEdges:()=>{A.convolution.call(this,[0,1,0,1,-4,1,0,1,0])},sobelX:()=>{A.convolution.call(this,[-1,0,1,-2,0,2,-1,0,1])},sobelY:()=>{A.convolution.call(this,[-1,-2,-1,0,0,0,1,2,1])},sharpen:y=>{let x=y||1;A.convolution.call(this,[0,-1*x,0,-1*x,1+4*x,-1*x,0,-1*x,0])},emboss:y=>{let x=y||1;A.convolution.call(this,[-2*x,-1*x,0,-1*x,1,1*x,0,1*x,2*x])},blur:y=>{let x=y/7/l.width,b=y/7/l.height,w=g(T6);d.uniform2f(w==null?void 0:w.uniform.px,0,b),m(u.INTERMEDIATE),d.uniform2f(w==null?void 0:w.uniform.px,x,0),m()},pixelate:y=>{let x=y/l.width,b=y/l.height,w=g(C6);d.uniform2f(w==null?void 0:w.uniform.size,x,b),m()}};this.add=function(y){let x=Array.prototype.slice.call(arguments,1),b=A[y];a.push({func:b,args:x})},this.reset=function(){a=[]},this.get=function(){return a},this.apply=function(y){p(y.width,y.height),e=0,t||(t=d.createTexture()),d.bindTexture(d.TEXTURE_2D,t),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_WRAP_S,d.CLAMP_TO_EDGE),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_WRAP_T,d.CLAMP_TO_EDGE),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_MIN_FILTER,d.NEAREST),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_MAG_FILTER,d.NEAREST),d.texImage2D(d.TEXTURE_2D,0,d.RGBA,d.RGBA,d.UNSIGNED_BYTE,y);for(let x=0;x0,r=e.naturalHeight||e.videoHeight||e.height||e.shape&&e.shape[2]>0;if(!s||!r)return t.debug&&ae("cannot determine input dimensions"),{tensor:null,canvas:lt};let a=s,o=r;if(a>Lm&&(a=Lm,o=Math.trunc(a*r/s)),o>Lm&&(o=Lm,a=Math.trunc(o*s/r)),(t.filter.width||0)>0?a=t.filter.width:(t.filter.height||0)>0&&(a=s*((t.filter.height||0)/r)),(t.filter.height||0)>0?o=t.filter.height:(t.filter.width||0)>0&&(o=r*((t.filter.width||0)/s)),!a||!o)throw new Error("input cannot determine dimension");(!lt||(lt==null?void 0:lt.width)!==a||(lt==null?void 0:lt.height)!==o)&&(lt=Kn(a,o));let i=lt.getContext("2d");if(typeof ImageData!="undefined"&&e instanceof ImageData?i.putImageData(e,0,0):t.filter.flip&&typeof i.translate!="undefined"?(i.translate(s,0),i.scale(-1,1),i.drawImage(e,0,0,s,r,0,0,lt==null?void 0:lt.width,lt==null?void 0:lt.height),i.setTransform(1,0,0,1,0,0)):i.drawImage(e,0,0,s,r,0,0,lt==null?void 0:lt.width,lt==null?void 0:lt.height),(!qt||lt.width!==qt.width||(lt==null?void 0:lt.height)!==(qt==null?void 0:qt.height))&&(qt=Kn(lt.width,lt.height)),t.filter.enabled&&ye.webgl.supported){if(_t||(_t=ye.browser?new R6:null),ye.filter=!!_t,!_t)return{tensor:null,canvas:lt};_t.reset(),t.filter.brightness!==0&&_t.add("brightness",t.filter.brightness),t.filter.contrast!==0&&_t.add("contrast",t.filter.contrast),t.filter.sharpness!==0&&_t.add("sharpen",t.filter.sharpness),t.filter.blur!==0&&_t.add("blur",t.filter.blur),t.filter.saturation!==0&&_t.add("saturation",t.filter.saturation),t.filter.hue!==0&&_t.add("hue",t.filter.hue),t.filter.negative&&_t.add("negative"),t.filter.sepia&&_t.add("sepia"),t.filter.vintage&&_t.add("brownie"),t.filter.sepia&&_t.add("sepia"),t.filter.kodachrome&&_t.add("kodachrome"),t.filter.technicolor&&_t.add("technicolor"),t.filter.polaroid&&_t.add("polaroid"),t.filter.pixelate!==0&&_t.add("pixelate",t.filter.pixelate),_t.get()>0?qt=_t.apply(lt):qt=_t.draw(lt)}else vx(lt,qt),_t&&(_t=null),ye.filter=!!_t;if(!n)return{tensor:null,canvas:qt};if(!qt)throw new Error("cannot create output canvas");let l,c=3;if(typeof ImageData!="undefined"&&e instanceof ImageData||e.data&&e.width&&e.height)if(ye.browser&&Gs)l=Gs?Gs.fromPixels(e):null;else{c=e.data.length/e.height/e.width;let p=new Uint8Array(e.data.buffer);l=Gt(p,[e.height,e.width,c],"int32")}else if((!Bo||qt.width!==Bo.width||(qt==null?void 0:qt.height)!==(Bo==null?void 0:Bo.height))&&(Bo=Kn(qt.width,qt.height)),Gs&&ye.browser)t.backend==="webgl"||t.backend==="humangl"||t.backend==="webgpu"?l=Gs.fromPixels(qt):(Bo=vx(qt),l=Gs.fromPixels(Bo));else{let f=vx(qt).getContext("2d").getImageData(0,0,a,o);c=f.data.length/a/o;let m=new Uint8Array(f.data.buffer);l=Gt(m,[a,o,c])}if(c===4){let p=Ru(l,[0,0,0],[-1,-1,3]);Q(l),l=p}if(!l)throw new Error("cannot create tensor from input");let u=he(l,"float32"),d=Kt(u,0);return Q([l,u]),{tensor:d,canvas:t.filter.return?qt:null}}}var wx=0,kx=1,Ix=0,Z0e=async e=>{let t=48,n=$e.resizeBilinear(e,[Math.trunc((e.shape[1]||1)/t),Math.trunc((e.shape[2]||1)/t)]),s=async()=>{let o=Ie(n),i=await o.data();return Q(o),i[0]},r=async()=>{let o=await n.data(),i=0;for(let l=0;l10*e.cacheSensitivity?0:s,r=r&&kx>0,r}var Sx=class{constructor(){de(this,"browser");de(this,"node");de(this,"worker");de(this,"platform","");de(this,"agent","");de(this,"backends",[]);de(this,"initial");de(this,"filter");de(this,"tfjs");de(this,"offscreen");de(this,"perfadd",!1);de(this,"wasm",{supported:void 0,backend:void 0,simd:void 0,multithread:void 0});de(this,"webgl",{supported:void 0,backend:void 0,version:void 0,renderer:void 0});de(this,"webgpu",{supported:void 0,backend:void 0,adapter:void 0});de(this,"cpu",{model:void 0,flags:[]});de(this,"kernels",[]);de(this,"Canvas");de(this,"Image");de(this,"ImageData");if(this.browser=typeof navigator!="undefined",this.node=typeof process!="undefined",this.tfjs={version:up},this.offscreen=typeof OffscreenCanvas!="undefined",this.initial=!0,this.worker=this.browser&&this.offscreen?typeof WorkerGlobalScope!="undefined":void 0,typeof navigator!="undefined"){let t=navigator.userAgent.match(/\(([^()]+)\)/g);if(t&&t[0]){let n=t[0].match(/\(([^()]+)\)/g);this.platform=n&&n[0]?n[0].replace(/\(|\)/g,""):"",this.agent=navigator.userAgent.replace(t[0],""),this.platform[1]&&(this.agent=this.agent.replace(t[1],"")),this.agent=this.agent.replace(/ /g," ")}}else typeof process!="undefined"&&(this.platform=`${process.platform} ${process.arch}`,this.agent=`NodeJS ${process.version}`)}async updateBackend(){var s;this.backends=Object.keys(ss().registryFactory),this.wasm.supported=typeof WebAssembly!="undefined",this.wasm.backend=this.backends.includes("wasm"),this.wasm.supported&&this.wasm.backend&&ir()==="wasm"&&(this.wasm.simd=await K().getAsync("WASM_HAS_SIMD_SUPPORT"),this.wasm.multithread=await K().getAsync("WASM_HAS_MULTITHREAD_SUPPORT"));let t=Kn(100,100),n=t?t.getContext("webgl2"):void 0;if(this.webgl.supported=typeof n!="undefined",this.webgl.backend=this.backends.includes("webgl"),this.webgl.supported&&this.webgl.backend&&(ir()==="webgl"||ir()==="humangl")){let r=Tr().gpgpu!=="undefined"?await Tr().getGPGPUContext().gl:null;r&&(this.webgl.version=r.getParameter(r.VERSION),this.webgl.renderer=r.getParameter(r.RENDERER))}this.webgpu.supported=this.browser&&typeof navigator.gpu!="undefined",this.webgpu.backend=this.backends.includes("webgpu"),this.webgpu.supported&&(this.webgpu.adapter=(s=await navigator.gpu.requestAdapter())==null?void 0:s.name),this.kernels=Xr(ir()).map(r=>r.kernelName.toLowerCase())}async updateCPU(){var n;let t={model:"",flags:[]};if(this.node&&((n=this.platform)==null?void 0:n.startsWith("linux"))){let s=xa("fs");try{let r=s.readFileSync("/proc/cpuinfo").toString();for(let a of r.split(` +`))a.startsWith("model name")&&(t.model=a.match(/:(.*)/g)[0].replace(":","").trim()),a.startsWith("flags")&&(t.flags=a.match(/:(.*)/g)[0].replace(":","").trim().split(" ").sort())}catch(r){}}this.cpu?this.cpu=t:Object.defineProperty(this,"cpu",{value:t})}},ye=new Sx;var Cx="2.4.0";var Wo;var m2e=Number.MAX_SAFE_INTEGER;async function D6(e){return ye.initial&&(Wo=null),Wo?e.debug&&ae("cached model:",Wo.modelUrl):(Wo=await st(at(e.modelBasePath,e.face.agegenderrace.modelPath)),!Wo||!Wo.modelUrl?ae("load model failed:",e.face.agegenderrace.modelPath):e.debug&&ae("load model:",Wo.modelUrl)),Wo}var cn,Bm=[],Tx=Number.MAX_SAFE_INTEGER,_6=0,P6=0;async function F6(e){var t,n;return ye.initial&&(cn=null),cn?e.debug&&ae("cached model:",cn.modelUrl):(cn=await st(at(e.modelBasePath,((t=e.face.antispoof)==null?void 0:t.modelPath)||"")),!cn||!cn.modelUrl?ae("load model failed:",(n=e.face.antispoof)==null?void 0:n.modelPath):e.debug&&ae("load model:",cn.modelUrl)),cn}async function Nx(e,t,n,s){var o,i;if(!cn)return null;let r=(((o=t.face.antispoof)==null?void 0:o.skipTime)||0)>pe()-P6,a=Tx<(((i=t.face.antispoof)==null?void 0:i.skipFrames)||0);return t.skipAllowed&&r&&a&&_6===s&&Bm[n]?(Tx++,Bm[n]):(Tx=0,new Promise(async l=>{let c=$e.resizeBilinear(e,[(cn==null?void 0:cn.inputs[0].shape)?cn.inputs[0].shape[2]:0,(cn==null?void 0:cn.inputs[0].shape)?cn.inputs[0].shape[1]:0],!1),u=cn==null?void 0:cn.predict(c),d=(await u.data())[0];Bm[n]=Math.round(100*d)/100,_6=s,P6=pe(),Q([c,u]),l(Bm[n])}))}var Lr={silhouette:[10,338,297,332,284,251,389,356,454,323,361,288,397,365,379,378,400,377,152,148,176,149,150,136,172,58,132,93,234,127,162,21,54,103,67,109],lipsUpperOuter:[61,185,40,39,37,0,267,269,270,409,291],lipsLowerOuter:[146,91,181,84,17,314,405,321,375,291],lipsUpperInner:[78,191,80,81,82,13,312,311,310,415,308],lipsLowerInner:[78,95,88,178,87,14,317,402,318,324,308],rightEyeUpper0:[246,161,160,159,158,157,173],rightEyeLower0:[33,7,163,144,145,153,154,155,133],rightEyeUpper1:[247,30,29,27,28,56,190],rightEyeLower1:[130,25,110,24,23,22,26,112,243],rightEyeUpper2:[113,225,224,223,222,221,189],rightEyeLower2:[226,31,228,229,230,231,232,233,244],rightEyeLower3:[143,111,117,118,119,120,121,128,245],rightEyebrowUpper:[156,70,63,105,66,107,55,193],rightEyebrowLower:[35,124,46,53,52,65],rightEyeIris:[473,474,475,476,477],leftEyeUpper0:[466,388,387,386,385,384,398],leftEyeLower0:[263,249,390,373,374,380,381,382,362],leftEyeUpper1:[467,260,259,257,258,286,414],leftEyeLower1:[359,255,339,254,253,252,256,341,463],leftEyeUpper2:[342,445,444,443,442,441,413],leftEyeLower2:[446,261,448,449,450,451,452,453,464],leftEyeLower3:[372,340,346,347,348,349,350,357,465],leftEyebrowUpper:[383,300,293,334,296,336,285,417],leftEyebrowLower:[265,353,276,283,282,295],leftEyeIris:[468,469,470,471,472],midwayBetweenEyes:[168],noseTip:[1],noseBottom:[2],noseRightCorner:[98],noseLeftCorner:[327],rightCheek:[205],leftCheek:[425]},Ex={count:468,mouth:13,symmetryLine:[13,Lr.midwayBetweenEyes[0]]},cp={leftEye:0,rightEye:1,nose:2,mouth:3,leftEar:4,rightEar:5,symmetryLine:[3,2]},Rx=[{key:"EyeUpper0",indices:[9,10,11,12,13,14,15]},{key:"EyeUpper1",indices:[25,26,27,28,29,30,31]},{key:"EyeUpper2",indices:[41,42,43,44,45,46,47]},{key:"EyeLower0",indices:[0,1,2,3,4,5,6,7,8]},{key:"EyeLower1",indices:[16,17,18,19,20,21,22,23,24]},{key:"EyeLower2",indices:[32,33,34,35,36,37,38,39,40]},{key:"EyeLower3",indices:[54,55,56,57,58,59,60,61,62]}],dp=[[.499976992607117,.652534008026123],[.500025987625122,.547487020492554],[.499974012374878,.602371990680695],[.482113003730774,.471979022026062],[.500150978565216,.527155995368958],[.499909996986389,.498252987861633],[.499523013830185,.40106201171875],[.289712011814117,.380764007568359],[.499954998493195,.312398016452789],[.499987006187439,.269918978214264],[.500023007392883,.107050001621246],[.500023007392883,.666234016418457],[.5000159740448,.679224014282227],[.500023007392883,.692348003387451],[.499976992607117,.695277988910675],[.499976992607117,.70593398809433],[.499976992607117,.719385027885437],[.499976992607117,.737019002437592],[.499967992305756,.781370997428894],[.499816000461578,.562981009483337],[.473773002624512,.573909997940063],[.104906998574734,.254140973091125],[.365929991006851,.409575998783112],[.338757991790771,.41302502155304],[.311120003461838,.409460008144379],[.274657994508743,.389131009578705],[.393361985683441,.403706014156342],[.345234006643295,.344011008739471],[.370094001293182,.346076011657715],[.319321990013123,.347265005111694],[.297903001308441,.353591024875641],[.24779200553894,.410809993743896],[.396889001131058,.842755019664764],[.280097991228104,.375599980354309],[.106310002505779,.399955987930298],[.2099249958992,.391353011131287],[.355807989835739,.534406006336212],[.471751004457474,.65040397644043],[.474155008792877,.680191993713379],[.439785003662109,.657229006290436],[.414617002010345,.66654098033905],[.450374007225037,.680860996246338],[.428770989179611,.682690978050232],[.374971002340317,.727805018424988],[.486716985702515,.547628998756409],[.485300987958908,.527395009994507],[.257764995098114,.314490020275116],[.401223003864288,.455172002315521],[.429818987846375,.548614978790283],[.421351999044418,.533740997314453],[.276895999908447,.532056987285614],[.483370006084442,.499586999416351],[.33721199631691,.282882988452911],[.296391993761063,.293242990970612],[.169294998049736,.193813979625702],[.447580009698868,.302609980106354],[.392390012741089,.353887975215912],[.354490011930466,.696784019470215],[.067304998636246,.730105042457581],[.442739009857178,.572826027870178],[.457098007202148,.584792017936707],[.381974011659622,.694710969924927],[.392388999462128,.694203019142151],[.277076005935669,.271932005882263],[.422551989555359,.563233017921448],[.385919004678726,.281364023685455],[.383103013038635,.255840003490448],[.331431001424789,.119714021682739],[.229923993349075,.232002973556519],[.364500999450684,.189113974571228],[.229622006416321,.299540996551514],[.173287004232407,.278747975826263],[.472878992557526,.666198015213013],[.446828007698059,.668527007102966],[.422762006521225,.673889994621277],[.445307999849319,.580065965652466],[.388103008270264,.693961024284363],[.403039008378983,.706539988517761],[.403629004955292,.693953037261963],[.460041999816895,.557139039039612],[.431158006191254,.692366003990173],[.452181994915009,.692366003990173],[.475387006998062,.692366003990173],[.465828001499176,.779190003871918],[.472328990697861,.736225962638855],[.473087012767792,.717857003211975],[.473122000694275,.704625964164734],[.473033010959625,.695277988910675],[.427942007780075,.695277988910675],[.426479011774063,.703539967536926],[.423162013292313,.711845993995667],[.4183090031147,.720062971115112],[.390094995498657,.639572978019714],[.013953999616206,.560034036636353],[.499913990497589,.58014702796936],[.413199990987778,.69539999961853],[.409626007080078,.701822996139526],[.468080013990402,.601534962654114],[.422728985548019,.585985004901886],[.463079988956451,.593783974647522],[.37211999297142,.47341400384903],[.334562003612518,.496073007583618],[.411671012639999,.546965003013611],[.242175996303558,.14767599105835],[.290776997804642,.201445996761322],[.327338010072708,.256527006626129],[.399509996175766,.748921036720276],[.441727995872498,.261676013469696],[.429764986038208,.187834024429321],[.412198007106781,.108901023864746],[.288955003023148,.398952007293701],[.218936994671822,.435410976409912],[.41278201341629,.398970007896423],[.257135003805161,.355440020561218],[.427684992551804,.437960982322693],[.448339998722076,.536936044692993],[.178560003638268,.45755398273468],[.247308000922203,.457193970680237],[.286267012357712,.467674970626831],[.332827985286713,.460712015628815],[.368755996227264,.447206974029541],[.398963987827301,.432654976844788],[.476410001516342,.405806005001068],[.189241006970406,.523923993110657],[.228962004184723,.348950982093811],[.490725994110107,.562400996685028],[.404670000076294,.485132992267609],[.019469000399113,.401564002037048],[.426243007183075,.420431017875671],[.396993011236191,.548797011375427],[.266469985246658,.376977026462555],[.439121007919312,.51895797252655],[.032313998788595,.644356966018677],[.419054001569748,.387154996395111],[.462783008813858,.505746960639954],[.238978996872902,.779744982719421],[.198220998048782,.831938028335571],[.107550002634525,.540755033493042],[.183610007166862,.740257024765015],[.134409993886948,.333683013916016],[.385764002799988,.883153975009918],[.490967005491257,.579378008842468],[.382384985685349,.508572995662689],[.174399003386497,.397670984268188],[.318785011768341,.39623498916626],[.343364000320435,.400596976280212],[.396100014448166,.710216999053955],[.187885001301765,.588537991046906],[.430987000465393,.944064974784851],[.318993002176285,.898285031318665],[.266247987747192,.869701027870178],[.500023007392883,.190576016902924],[.499976992607117,.954452991485596],[.366169989109039,.398822009563446],[.393207013607025,.39553701877594],[.410373002290726,.391080021858215],[.194993004202843,.342101991176605],[.388664990663528,.362284004688263],[.365961998701096,.355970978736877],[.343364000320435,.355356991291046],[.318785011768341,.35834002494812],[.301414996385574,.363156020641327],[.058132998645306,.319076001644135],[.301414996385574,.387449026107788],[.499987989664078,.618434011936188],[.415838003158569,.624195992946625],[.445681989192963,.566076993942261],[.465844005346298,.620640993118286],[.49992299079895,.351523995399475],[.288718998432159,.819945991039276],[.335278987884521,.852819979190826],[.440512001514435,.902418971061707],[.128294005990028,.791940987110138],[.408771991729736,.373893976211548],[.455606997013092,.451801002025604],[.499877005815506,.908990025520325],[.375436991453171,.924192011356354],[.11421000212431,.615022003650665],[.448662012815475,.695277988910675],[.4480200111866,.704632043838501],[.447111994028091,.715808033943176],[.444831997156143,.730794012546539],[.430011987686157,.766808986663818],[.406787008047104,.685672998428345],[.400738000869751,.681069016456604],[.392399996519089,.677703022956848],[.367855995893478,.663918972015381],[.247923001646996,.601333022117615],[.452769994735718,.420849978923798],[.43639200925827,.359887003898621],[.416164010763168,.368713974952698],[.413385987281799,.692366003990173],[.228018000721931,.683571994304657],[.468268007040024,.352671027183533],[.411361992359161,.804327011108398],[.499989002943039,.469825029373169],[.479153990745544,.442654013633728],[.499974012374878,.439637005329132],[.432112008333206,.493588984012604],[.499886006116867,.866917014122009],[.49991300702095,.821729004383087],[.456548988819122,.819200992584229],[.344549000263214,.745438992977142],[.37890899181366,.574010014533997],[.374292999505997,.780184984207153],[.319687992334366,.570737957954407],[.357154995203018,.604269981384277],[.295284003019333,.621580958366394],[.447750002145767,.862477004528046],[.410986006259918,.508723020553589],[.31395098567009,.775308012962341],[.354128003120422,.812552988529205],[.324548006057739,.703992962837219],[.189096003770828,.646299958229065],[.279776990413666,.71465802192688],[.1338230073452,.682700991630554],[.336768001317978,.644733011722565],[.429883986711502,.466521978378296],[.455527991056442,.548622965812683],[.437114000320435,.558896005153656],[.467287987470627,.529924988746643],[.414712011814117,.335219979286194],[.37704598903656,.322777986526489],[.344107985496521,.320150971412659],[.312875986099243,.32233202457428],[.283526003360748,.333190023899078],[.241245999932289,.382785975933075],[.102986000478268,.468762993812561],[.267612010240555,.424560010433197],[.297879010438919,.433175981044769],[.333433985710144,.433878004550934],[.366427004337311,.426115989685059],[.396012008190155,.416696012020111],[.420121014118195,.41022801399231],[.007561000064015,.480777025222778],[.432949006557465,.569517970085144],[.458638995885849,.479089021682739],[.473466008901596,.545744001865387],[.476087987422943,.563830018043518],[.468472003936768,.555056989192963],[.433990985155106,.582361996173859],[.483518004417419,.562983989715576],[.482482999563217,.57784903049469],[.42645001411438,.389798998832703],[.438998997211456,.39649498462677],[.450067013502121,.400434017181396],[.289712011814117,.368252992630005],[.276670008897781,.363372981548309],[.517862021923065,.471948027610779],[.710287988185883,.380764007568359],[.526226997375488,.573909997940063],[.895093023777008,.254140973091125],[.634069979190826,.409575998783112],[.661242008209229,.41302502155304],[.688880026340485,.409460008144379],[.725341975688934,.389131009578705],[.606630027294159,.40370500087738],[.654766023159027,.344011008739471],[.629905998706818,.346076011657715],[.680678009986877,.347265005111694],[.702096998691559,.353591024875641],[.75221198797226,.410804986953735],[.602918028831482,.842862963676453],[.719901978969574,.375599980354309],[.893692970275879,.399959981441498],[.790081977844238,.391354024410248],[.643998026847839,.534487962722778],[.528249025344849,.65040397644043],[.525849997997284,.680191040039062],[.560214996337891,.657229006290436],[.585384011268616,.66654098033905],[.549625992774963,.680860996246338],[.57122802734375,.682691991329193],[.624852001667023,.72809898853302],[.513050019741058,.547281980514526],[.51509702205658,.527251958847046],[.742246985435486,.314507007598877],[.598631024360657,.454979002475739],[.570338010787964,.548575043678284],[.578631997108459,.533622980117798],[.723087012767792,.532054007053375],[.516445994377136,.499638974666595],[.662801027297974,.282917976379395],[.70362401008606,.293271005153656],[.830704987049103,.193813979625702],[.552385985851288,.302568018436432],[.607609987258911,.353887975215912],[.645429015159607,.696707010269165],[.932694971561432,.730105042457581],[.557260990142822,.572826027870178],[.542901992797852,.584792017936707],[.6180260181427,.694710969924927],[.607590973377228,.694203019142151],[.722943007946014,.271963000297546],[.577413976192474,.563166975975037],[.614082992076874,.281386971473694],[.616907000541687,.255886018276215],[.668509006500244,.119913995265961],[.770092010498047,.232020974159241],[.635536015033722,.189248979091644],[.77039098739624,.299556016921997],[.826722025871277,.278755009174347],[.527121007442474,.666198015213013],[.553171992301941,.668527007102966],[.577238023281097,.673889994621277],[.554691970348358,.580065965652466],[.611896991729736,.693961024284363],[.59696102142334,.706539988517761],[.596370995044708,.693953037261963],[.539958000183105,.557139039039612],[.568841993808746,.692366003990173],[.547818005084991,.692366003990173],[.52461302280426,.692366003990173],[.534089982509613,.779141008853912],[.527670979499817,.736225962638855],[.526912987232208,.717857003211975],[.526877999305725,.704625964164734],[.526966989040375,.695277988910675],[.572058022022247,.695277988910675],[.573521018028259,.703539967536926],[.57683801651001,.711845993995667],[.581691026687622,.720062971115112],[.609944999217987,.639909982681274],[.986046016216278,.560034036636353],[.5867999792099,.69539999961853],[.590372025966644,.701822996139526],[.531915009021759,.601536989212036],[.577268004417419,.585934996604919],[.536915004253387,.593786001205444],[.627542972564697,.473352015018463],[.665585994720459,.495950996875763],[.588353991508484,.546862006187439],[.757824003696442,.14767599105835],[.709249973297119,.201507985591888],[.672684013843536,.256581008434296],[.600408971309662,.74900496006012],[.55826598405838,.261672019958496],[.570303976535797,.187870979309082],[.588165998458862,.109044015407562],[.711045026779175,.398952007293701],[.781069993972778,.435405015945435],[.587247014045715,.398931980133057],[.742869973182678,.355445981025696],[.572156012058258,.437651991844177],[.55186802148819,.536570012569427],[.821442008018494,.457556009292603],[.752701997756958,.457181990146637],[.71375697851181,.467626988887787],[.66711300611496,.460672974586487],[.631101012229919,.447153985500336],[.6008620262146,.432473003864288],[.523481011390686,.405627012252808],[.810747981071472,.523926019668579],[.771045982837677,.348959028720856],[.509127020835876,.562718033790588],[.595292985439301,.485023975372314],[.980530977249146,.401564002037048],[.573499977588654,.420000016689301],[.602994978427887,.548687994480133],[.733529984951019,.376977026462555],[.560611009597778,.519016981124878],[.967685997486115,.644356966018677],[.580985009670258,.387160003185272],[.537728011608124,.505385041236877],[.760966002941132,.779752969741821],[.801778972148895,.831938028335571],[.892440974712372,.54076099395752],[.816350996494293,.740260004997253],[.865594983100891,.333687007427216],[.614073991775513,.883246004581451],[.508952975273132,.579437971115112],[.617941975593567,.508316040039062],[.825608015060425,.397674977779388],[.681214988231659,.39623498916626],[.656635999679565,.400596976280212],[.603900015354156,.710216999053955],[.81208598613739,.588539004325867],[.56801301240921,.944564998149872],[.681007981300354,.898285031318665],[.733752012252808,.869701027870178],[.633830010890961,.398822009563446],[.606792986392975,.39553701877594],[.589659988880157,.391062021255493],[.805015981197357,.342108011245728],[.611334979534149,.362284004688263],[.634037971496582,.355970978736877],[.656635999679565,.355356991291046],[.681214988231659,.35834002494812],[.698584973812103,.363156020641327],[.941866993904114,.319076001644135],[.698584973812103,.387449026107788],[.584177017211914,.624107003211975],[.554318010807037,.566076993942261],[.534153997898102,.62064003944397],[.711217999458313,.819975018501282],[.664629995822906,.852871000766754],[.559099972248077,.902631998062134],[.871706008911133,.791940987110138],[.591234028339386,.373893976211548],[.544341027736664,.451583981513977],[.624562978744507,.924192011356354],[.88577002286911,.615028977394104],[.551338016986847,.695277988910675],[.551980018615723,.704632043838501],[.552887976169586,.715808033943176],[.555167973041534,.730794012546539],[.569944024085999,.767035007476807],[.593203008174896,.685675978660583],[.599261999130249,.681069016456604],[.607599973678589,.677703022956848],[.631937980651855,.663500010967255],[.752032995223999,.601315021514893],[.547226011753082,.420395016670227],[.563543975353241,.359827995300293],[.583841025829315,.368713974952698],[.586614012718201,.692366003990173],[.771915018558502,.683578014373779],[.531597018241882,.352482974529266],[.588370978832245,.804440975189209],[.52079701423645,.442565023899078],[.567984998226166,.493479013442993],[.543282985687256,.819254994392395],[.655317008495331,.745514988899231],[.621008992195129,.574018001556396],[.625559985637665,.78031200170517],[.680198013782501,.570719003677368],[.64276397228241,.604337990283966],[.704662978649139,.621529996395111],[.552012026309967,.862591981887817],[.589071989059448,.508637011051178],[.685944974422455,.775357007980347],[.645735025405884,.812640011310577],[.675342977046967,.703978002071381],[.810858011245728,.646304965019226],[.72012197971344,.714666962623596],[.866151988506317,.682704985141754],[.663187026977539,.644596993923187],[.570082008838654,.466325998306274],[.544561982154846,.548375964164734],[.562758982181549,.558784961700439],[.531987011432648,.530140042304993],[.585271000862122,.335177004337311],[.622952997684479,.32277899980545],[.655896008014679,.320163011550903],[.687132000923157,.322345972061157],[.716481983661652,.333200991153717],[.758756995201111,.382786989212036],[.897013008594513,.468769013881683],[.732392013072968,.424547016620636],[.70211398601532,.433162987232208],[.66652500629425,.433866024017334],[.633504986763,.426087975502014],[.603875994682312,.416586995124817],[.579657971858978,.409945011138916],[.992439985275269,.480777025222778],[.567192018032074,.569419980049133],[.54136598110199,.478899002075195],[.526564002037048,.546118021011353],[.523913025856018,.563830018043518],[.531529009342194,.555056989192963],[.566035985946655,.582329034805298],[.51631098985672,.563053965568542],[.5174720287323,.577877044677734],[.573594987392426,.389806985855103],[.560697972774506,.395331978797913],[.549755990505219,.399751007556915],[.710287988185883,.368252992630005],[.723330020904541,.363372981548309]],kl=[127,34,139,11,0,37,232,231,120,72,37,39,128,121,47,232,121,128,104,69,67,175,171,148,157,154,155,118,50,101,73,39,40,9,151,108,48,115,131,194,204,211,74,40,185,80,42,183,40,92,186,230,229,118,202,212,214,83,18,17,76,61,146,160,29,30,56,157,173,106,204,194,135,214,192,203,165,98,21,71,68,51,45,4,144,24,23,77,146,91,205,50,187,201,200,18,91,106,182,90,91,181,85,84,17,206,203,36,148,171,140,92,40,39,193,189,244,159,158,28,247,246,161,236,3,196,54,68,104,193,168,8,117,228,31,189,193,55,98,97,99,126,47,100,166,79,218,155,154,26,209,49,131,135,136,150,47,126,217,223,52,53,45,51,134,211,170,140,67,69,108,43,106,91,230,119,120,226,130,247,63,53,52,238,20,242,46,70,156,78,62,96,46,53,63,143,34,227,173,155,133,123,117,111,44,125,19,236,134,51,216,206,205,154,153,22,39,37,167,200,201,208,36,142,100,57,212,202,20,60,99,28,158,157,35,226,113,160,159,27,204,202,210,113,225,46,43,202,204,62,76,77,137,123,116,41,38,72,203,129,142,64,98,240,49,102,64,41,73,74,212,216,207,42,74,184,169,170,211,170,149,176,105,66,69,122,6,168,123,147,187,96,77,90,65,55,107,89,90,180,101,100,120,63,105,104,93,137,227,15,86,85,129,102,49,14,87,86,55,8,9,100,47,121,145,23,22,88,89,179,6,122,196,88,95,96,138,172,136,215,58,172,115,48,219,42,80,81,195,3,51,43,146,61,171,175,199,81,82,38,53,46,225,144,163,110,246,33,7,52,65,66,229,228,117,34,127,234,107,108,69,109,108,151,48,64,235,62,78,191,129,209,126,111,35,143,163,161,246,117,123,50,222,65,52,19,125,141,221,55,65,3,195,197,25,7,33,220,237,44,70,71,139,122,193,245,247,130,33,71,21,162,153,158,159,170,169,150,188,174,196,216,186,92,144,160,161,2,97,167,141,125,241,164,167,37,72,38,12,145,159,160,38,82,13,63,68,71,226,35,111,158,153,154,101,50,205,206,92,165,209,198,217,165,167,97,220,115,218,133,112,243,239,238,241,214,135,169,190,173,133,171,208,32,125,44,237,86,87,178,85,86,179,84,85,180,83,84,181,201,83,182,137,93,132,76,62,183,61,76,184,57,61,185,212,57,186,214,207,187,34,143,156,79,239,237,123,137,177,44,1,4,201,194,32,64,102,129,213,215,138,59,166,219,242,99,97,2,94,141,75,59,235,24,110,228,25,130,226,23,24,229,22,23,230,26,22,231,112,26,232,189,190,243,221,56,190,28,56,221,27,28,222,29,27,223,30,29,224,247,30,225,238,79,20,166,59,75,60,75,240,147,177,215,20,79,166,187,147,213,112,233,244,233,128,245,128,114,188,114,217,174,131,115,220,217,198,236,198,131,134,177,132,58,143,35,124,110,163,7,228,110,25,356,389,368,11,302,267,452,350,349,302,303,269,357,343,277,452,453,357,333,332,297,175,152,377,384,398,382,347,348,330,303,304,270,9,336,337,278,279,360,418,262,431,304,408,409,310,415,407,270,409,410,450,348,347,422,430,434,313,314,17,306,307,375,387,388,260,286,414,398,335,406,418,364,367,416,423,358,327,251,284,298,281,5,4,373,374,253,307,320,321,425,427,411,421,313,18,321,405,406,320,404,405,315,16,17,426,425,266,377,400,369,322,391,269,417,465,464,386,257,258,466,260,388,456,399,419,284,332,333,417,285,8,346,340,261,413,441,285,327,460,328,355,371,329,392,439,438,382,341,256,429,420,360,364,394,379,277,343,437,443,444,283,275,440,363,431,262,369,297,338,337,273,375,321,450,451,349,446,342,467,293,334,282,458,461,462,276,353,383,308,324,325,276,300,293,372,345,447,382,398,362,352,345,340,274,1,19,456,248,281,436,427,425,381,256,252,269,391,393,200,199,428,266,330,329,287,273,422,250,462,328,258,286,384,265,353,342,387,259,257,424,431,430,342,353,276,273,335,424,292,325,307,366,447,345,271,303,302,423,266,371,294,455,460,279,278,294,271,272,304,432,434,427,272,407,408,394,430,431,395,369,400,334,333,299,351,417,168,352,280,411,325,319,320,295,296,336,319,403,404,330,348,349,293,298,333,323,454,447,15,16,315,358,429,279,14,15,316,285,336,9,329,349,350,374,380,252,318,402,403,6,197,419,318,319,325,367,364,365,435,367,397,344,438,439,272,271,311,195,5,281,273,287,291,396,428,199,311,271,268,283,444,445,373,254,339,263,466,249,282,334,296,449,347,346,264,447,454,336,296,299,338,10,151,278,439,455,292,407,415,358,371,355,340,345,372,390,249,466,346,347,280,442,443,282,19,94,370,441,442,295,248,419,197,263,255,359,440,275,274,300,383,368,351,412,465,263,467,466,301,368,389,380,374,386,395,378,379,412,351,419,436,426,322,373,390,388,2,164,393,370,462,461,164,0,267,302,11,12,374,373,387,268,12,13,293,300,301,446,261,340,385,384,381,330,266,425,426,423,391,429,355,437,391,327,326,440,457,438,341,382,362,459,457,461,434,430,394,414,463,362,396,369,262,354,461,457,316,403,402,315,404,403,314,405,404,313,406,405,421,418,406,366,401,361,306,408,407,291,409,408,287,410,409,432,436,410,434,416,411,264,368,383,309,438,457,352,376,401,274,275,4,421,428,262,294,327,358,433,416,367,289,455,439,462,370,326,2,326,370,305,460,455,254,449,448,255,261,446,253,450,449,252,451,450,256,452,451,341,453,452,413,464,463,441,413,414,258,442,441,257,443,442,259,444,443,260,445,444,467,342,445,459,458,250,289,392,290,290,328,460,376,433,435,250,290,392,411,416,433,341,463,464,453,464,465,357,465,412,343,412,399,360,363,440,437,399,456,420,456,363,401,435,288,372,383,353,339,255,249,448,261,255,133,243,190,133,155,112,33,246,247,33,130,25,398,384,286,362,398,414,362,463,341,263,359,467,263,249,255,466,467,260,75,60,166,238,239,79,162,127,139,72,11,37,121,232,120,73,72,39,114,128,47,233,232,128,103,104,67,152,175,148,173,157,155,119,118,101,74,73,40,107,9,108,49,48,131,32,194,211,184,74,185,191,80,183,185,40,186,119,230,118,210,202,214,84,83,17,77,76,146,161,160,30,190,56,173,182,106,194,138,135,192,129,203,98,54,21,68,5,51,4,145,144,23,90,77,91,207,205,187,83,201,18,181,91,182,180,90,181,16,85,17,205,206,36,176,148,140,165,92,39,245,193,244,27,159,28,30,247,161,174,236,196,103,54,104,55,193,8,111,117,31,221,189,55,240,98,99,142,126,100,219,166,218,112,155,26,198,209,131,169,135,150,114,47,217,224,223,53,220,45,134,32,211,140,109,67,108,146,43,91,231,230,120,113,226,247,105,63,52,241,238,242,124,46,156,95,78,96,70,46,63,116,143,227,116,123,111,1,44,19,3,236,51,207,216,205,26,154,22,165,39,167,199,200,208,101,36,100,43,57,202,242,20,99,56,28,157,124,35,113,29,160,27,211,204,210,124,113,46,106,43,204,96,62,77,227,137,116,73,41,72,36,203,142,235,64,240,48,49,64,42,41,74,214,212,207,183,42,184,210,169,211,140,170,176,104,105,69,193,122,168,50,123,187,89,96,90,66,65,107,179,89,180,119,101,120,68,63,104,234,93,227,16,15,85,209,129,49,15,14,86,107,55,9,120,100,121,153,145,22,178,88,179,197,6,196,89,88,96,135,138,136,138,215,172,218,115,219,41,42,81,5,195,51,57,43,61,208,171,199,41,81,38,224,53,225,24,144,110,105,52,66,118,229,117,227,34,234,66,107,69,10,109,151,219,48,235,183,62,191,142,129,126,116,111,143,7,163,246,118,117,50,223,222,52,94,19,141,222,221,65,196,3,197,45,220,44,156,70,139,188,122,245,139,71,162,145,153,159,149,170,150,122,188,196,206,216,92,163,144,161,164,2,167,242,141,241,0,164,37,11,72,12,144,145,160,12,38,13,70,63,71,31,226,111,157,158,154,36,101,205,203,206,165,126,209,217,98,165,97,237,220,218,237,239,241,210,214,169,140,171,32,241,125,237,179,86,178,180,85,179,181,84,180,182,83,181,194,201,182,177,137,132,184,76,183,185,61,184,186,57,185,216,212,186,192,214,187,139,34,156,218,79,237,147,123,177,45,44,4,208,201,32,98,64,129,192,213,138,235,59,219,141,242,97,97,2,141,240,75,235,229,24,228,31,25,226,230,23,229,231,22,230,232,26,231,233,112,232,244,189,243,189,221,190,222,28,221,223,27,222,224,29,223,225,30,224,113,247,225,99,60,240,213,147,215,60,20,166,192,187,213,243,112,244,244,233,245,245,128,188,188,114,174,134,131,220,174,217,236,236,198,134,215,177,58,156,143,124,25,110,7,31,228,25,264,356,368,0,11,267,451,452,349,267,302,269,350,357,277,350,452,357,299,333,297,396,175,377,381,384,382,280,347,330,269,303,270,151,9,337,344,278,360,424,418,431,270,304,409,272,310,407,322,270,410,449,450,347,432,422,434,18,313,17,291,306,375,259,387,260,424,335,418,434,364,416,391,423,327,301,251,298,275,281,4,254,373,253,375,307,321,280,425,411,200,421,18,335,321,406,321,320,405,314,315,17,423,426,266,396,377,369,270,322,269,413,417,464,385,386,258,248,456,419,298,284,333,168,417,8,448,346,261,417,413,285,326,327,328,277,355,329,309,392,438,381,382,256,279,429,360,365,364,379,355,277,437,282,443,283,281,275,363,395,431,369,299,297,337,335,273,321,348,450,349,359,446,467,283,293,282,250,458,462,300,276,383,292,308,325,283,276,293,264,372,447,346,352,340,354,274,19,363,456,281,426,436,425,380,381,252,267,269,393,421,200,428,371,266,329,432,287,422,290,250,328,385,258,384,446,265,342,386,387,257,422,424,430,445,342,276,422,273,424,306,292,307,352,366,345,268,271,302,358,423,371,327,294,460,331,279,294,303,271,304,436,432,427,304,272,408,395,394,431,378,395,400,296,334,299,6,351,168,376,352,411,307,325,320,285,295,336,320,319,404,329,330,349,334,293,333,366,323,447,316,15,315,331,358,279,317,14,316,8,285,9,277,329,350,253,374,252,319,318,403,351,6,419,324,318,325,397,367,365,288,435,397,278,344,439,310,272,311,248,195,281,375,273,291,175,396,199,312,311,268,276,283,445,390,373,339,295,282,296,448,449,346,356,264,454,337,336,299,337,338,151,294,278,455,308,292,415,429,358,355,265,340,372,388,390,466,352,346,280,295,442,282,354,19,370,285,441,295,195,248,197,457,440,274,301,300,368,417,351,465,251,301,389,385,380,386,394,395,379,399,412,419,410,436,322,387,373,388,326,2,393,354,370,461,393,164,267,268,302,12,386,374,387,312,268,13,298,293,301,265,446,340,380,385,381,280,330,425,322,426,391,420,429,437,393,391,326,344,440,438,458,459,461,364,434,394,428,396,262,274,354,457,317,316,402,316,315,403,315,314,404,314,313,405,313,421,406,323,366,361,292,306,407,306,291,408,291,287,409,287,432,410,427,434,411,372,264,383,459,309,457,366,352,401,1,274,4,418,421,262,331,294,358,435,433,367,392,289,439,328,462,326,94,2,370,289,305,455,339,254,448,359,255,446,254,253,449,253,252,450,252,256,451,256,341,452,414,413,463,286,441,414,286,258,441,258,257,442,257,259,443,259,260,444,260,467,445,309,459,250,305,289,290,305,290,460,401,376,435,309,250,392,376,411,433,453,341,464,357,453,465,343,357,412,437,343,399,344,360,440,420,437,456,360,420,363,361,401,288,265,372,353,390,339,249,339,448,255];var J0e=[127,234,132,58,172,150,149,148,152,377,378,379,397,288,361,454,356,70,63,105,66,107,336,296,334,293,300,168,6,195,4,98,97,2,326,327,33,160,158,133,153,144,362,385,387,263,373,380,57,40,37,0,267,270,287,321,314,17,84,91,78,81,13,311,308,402,14,178],Q0e=[33,133,362,263,1,62,308,159,145,386,374,6,102,331,2,13,14,70,105,107,336,334,300,54,10,284,50,280,234,454,58,288,152],ege=[33,133,362,263,1,78,308],v2e=J0e.map(e=>dp[e]),w2e=Q0e.map(e=>dp[e]),k2e=ege.map(e=>dp[e]);var O6=e=>({startPoint:_e(e,[0,0],[-1,2]),endPoint:_e(e,[0,2],[-1,2])});var pp=e=>[Math.abs(e.endPoint[0]-e.startPoint[0]),Math.abs(e.endPoint[1]-e.startPoint[1])],Wm=e=>[e.startPoint[0]+(e.endPoint[0]-e.startPoint[0])/2,e.startPoint[1]+(e.endPoint[1]-e.startPoint[1])/2],$x=(e,t)=>e?[Math.trunc(Math.max(0,e.startPoint[0])),Math.trunc(Math.max(0,e.startPoint[1])),Math.trunc(Math.min(t.shape[2]||0,e.endPoint[0])-Math.max(0,e.startPoint[0])),Math.trunc(Math.min(t.shape[1]||0,e.endPoint[1])-Math.max(0,e.startPoint[1]))]:[0,0,0,0],Dx=(e,t)=>e?[e.startPoint[0]/(t.shape[2]||0),e.startPoint[1]/(t.shape[1]||0),(e.endPoint[0]-e.startPoint[0])/(t.shape[2]||0),(e.endPoint[1]-e.startPoint[1])/(t.shape[1]||0)]:[0,0,0,0],M6=(e,t)=>{let n=[e.startPoint[0]*t[0],e.startPoint[1]*t[1]],s=[e.endPoint[0]*t[0],e.endPoint[1]*t[1]];return{startPoint:n,endPoint:s}},_x=(e,t,n)=>{let s=t.shape[1],r=t.shape[2];return $e.cropAndResize(t,[[e.startPoint[1]/s,e.startPoint[0]/r,e.endPoint[1]/s,e.endPoint[0]/r]],[0],n)},hp=(e,t=1.5)=>{let n=Wm(e),s=pp(e),r=[t*s[0]/2,t*s[1]/2];return{startPoint:[n[0]-r[0],n[1]-r[1]],endPoint:[n[0]+r[0],n[1]+r[1]],landmarks:e.landmarks}},fp=e=>{let t=Wm(e),n=pp(e),s=Math.max(...n)/2;return{startPoint:[Math.round(t[0]-s),Math.round(t[1]-s)],endPoint:[Math.round(t[0]+s),Math.round(t[1]+s)],landmarks:e.landmarks}},Vm=e=>{let t=e.map(s=>s[0]),n=e.map(s=>s[1]);return{startPoint:[Math.min(...t),Math.min(...n)],endPoint:[Math.max(...t),Math.max(...n)],landmarks:e}},Um=[[1,0,0],[0,1,0],[0,0,1]],tge=e=>e-2*Math.PI*Math.floor((e+Math.PI)/(2*Math.PI)),nge=(e,t)=>tge(Math.PI/2-Math.atan2(-(t[1]-e[1]),t[0]-e[0]));var z6=(e,t)=>[[1,0,e],[0,1,t],[0,0,1]],Il=(e,t)=>{let n=0;for(let s=0;s{let n=[];for(let s=0;s{let n=[],s=e.length;for(let r=0;r{let n=Math.cos(e),s=Math.sin(e),r=[[n,-s,0],[s,n,0],[0,0,1]],a=z6(t[0],t[1]),o=L6(a,r),i=z6(-t[0],-t[1]);return L6(o,i)},rge=e=>{let t=[[e[0][0],e[1][0]],[e[0][1],e[1][1]]],n=[e[0][2],e[1][2]],s=[-Il(t[0],n),-Il(t[1],n)];return[t[0].concat(s[0]),t[1].concat(s[1]),[0,0,1]]},age=(e,t)=>[Il(e,t[0]),Il(e,t[1])];function W6(e){let t={strides:[e/16,e/8],anchors:[2,6]},n=[];for(let s=0;s[a[0]/r*(d[0]-r/2),a[1]/r*(d[1]-r/2),d[2]||0]),i=n!==0?B6(n,[0,0]):Um,l=n!==0?o.map(d=>[...age(d,i),d[2]]):o,c=n!==0?rge(s):Um,u=[...Wm({startPoint:t.startPoint,endPoint:t.endPoint}),1];return l.map(d=>[Math.round(d[0]+Il(u,c[0])),Math.round(d[1]+Il(u,c[1])),Math.round(d[2]||0)])}function Px(e,t,n){let s=e.landmarks.length>=Ex.count?Ex.symmetryLine:cp.symmetryLine,r=nge(e.landmarks[s[0]],e.landmarks[s[1]]),a=Wm({startPoint:e.startPoint,endPoint:e.endPoint}),o=[a[0]/t.shape[2],a[1]/t.shape[1]],i=$e.rotateWithOffset(t,r,0,o),l=B6(-r,a),c=_x({startPoint:e.startPoint,endPoint:e.endPoint},i,[n,n]),u=fe(c,255);return Q(c),Q(i),[r,l,u]}var U6=6,Os,Fx=[],G6=null,Ms=0,mp=()=>Ms;async function H6(e){var t,n;return ye.initial&&(Os=null),Os?e.debug&&ae("cached model:",Os.modelUrl):(Os=await st(at(e.modelBasePath,((t=e.face.detector)==null?void 0:t.modelPath)||"")),!Os||!Os.modelUrl?ae("load model failed:",(n=e.face.detector)==null?void 0:n.modelPath):e.debug&&ae("load model:",Os.modelUrl)),Ms=Os.inputs[0].shape?Os.inputs[0].shape[2]:0,Ms===-1&&(Ms=64),Fx=W6(Ms),G6=ur(Fx),Os}function oge(e){let t=_e(e,[0,1],[-1,2]),n=ie(t,G6),s=_e(e,[0,3],[-1,2]),r=fe(s,Ms),a=fe(n,Ms),o=fe(r,2),i=xe(a,o),l=ie(a,o),c=W(i,Ms),u=W(l,Ms);return ku([c,u],1)}async function j6(e,t){var c,u,d,p;if(!e||e.isDisposedInternal||e.shape.length!==4||e.shape[1]<1||e.shape[2]<1)return{boxes:[]};let[n,s,r]=j(()=>{let h=$e.resizeBilinear(e,[Ms,Ms]),f=xe(fe(h,127.5),.5),m=Os==null?void 0:Os.execute(f),g;if(Array.isArray(m)){let b=m.sort((E,$)=>E.size-$.size),w=It([b[0],b[2]],2),k=It([b[1],b[3]],2),S=It([k,w],1);g=pt(S,0)}else g=pt(m);let A=oge(g),y=_e(g,[0,0],[-1,1]),x=pt(hs(y));return[g,A,x]}),a=await $e.nonMaxSuppressionAsync(s,r,((c=t.face.detector)==null?void 0:c.maxDetected)||0,((u=t.face.detector)==null?void 0:u.iouThreshold)||0,((d=t.face.detector)==null?void 0:d.minConfidence)||0),o=await a.array();Q(a);let i=[],l=await r.data();for(let h=0;h(((p=t.face.detector)==null?void 0:p.minConfidence)||0)){let m=_e(s,[o[h],0],[1,-1]),g=j(()=>G(pt(_e(n,[o[h],U6-1],[1,-1])),[U6,-1]));i.push({box:O6(m),landmarks:g,anchor:Fx[o[h]],confidence:f}),Q(m)}}return Q(n),Q(s),Q(r),{boxes:i,scaleFactor:[e.shape[2]/Ms,e.shape[1]/Ms]}}var zx={};qp(zx,{connected:()=>Mx,kpt:()=>Ox});var Ox=["nose","leftEyeInside","leftEye","leftEyeOutside","rightEyeInside","rightEye","rightEyeOutside","leftEar","rightEar","leftMouth","rightMouth","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftPalm","rightPalm","leftIndex","rightIndex","leftPinky","rightPinky","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle","leftHeel","rightHeel","leftFoot","rightFoot","bodyCenter","bodyTop","leftThumb","leftHand","rightThumb","rightHand"],Mx={leftLeg:["leftHip","leftKnee","leftAnkle","leftHeel","leftFoot"],rightLeg:["rightHip","rightKnee","rightAnkle","rightHeel","rightFoot"],torso:["leftShoulder","rightShoulder","rightHip","leftHip","leftShoulder"],leftArm:["leftShoulder","leftElbow","leftWrist","leftPalm"],rightArm:["rightShoulder","rightElbow","rightWrist","rightPalm"],leftHand:[],rightHand:[],head:[]};var q6={initial:!0},dn=[null,null],Vo=[[0,0],[0,0]],Lx=Number.MAX_SAFE_INTEGER,Bx,Gm=null,Uo=[[0,0],[0,0],[0,0],[0,0]],X6=0;async function K6(e){var t,n,s;if(q6.initial&&(dn[0]=null),!dn[0]&&((t=e.body.detector)==null?void 0:t.modelPath)){dn[0]=await st(at(e.modelBasePath,((n=e.body.detector)==null?void 0:n.modelPath)||""));let r=Object.values(dn[0].modelSignature.inputs);Vo[0][0]=Array.isArray(r)?parseInt(r[0].tensorShape.dim[1].size):0,Vo[0][1]=Array.isArray(r)?parseInt(r[0].tensorShape.dim[2].size):0,!dn[0]||!dn[0].modelUrl?ae("load model failed:",(s=e.body.detector)==null?void 0:s.modelPath):e.debug&&ae("load model:",dn[0].modelUrl)}else e.debug&&dn[0]&&ae("cached model:",dn[0].modelUrl);return dn[0]}async function Z6(e){var t;if(q6.initial&&(dn[1]=null),dn[1])e.debug&&ae("cached model:",dn[1].modelUrl);else{dn[1]=await st(at(e.modelBasePath,e.body.modelPath||""));let n=Object.values(dn[1].modelSignature.inputs);Vo[1][0]=Array.isArray(n)?parseInt(n[0].tensorShape.dim[1].size):0,Vo[1][1]=Array.isArray(n)?parseInt(n[0].tensorShape.dim[2].size):0,((t=e.body.modelPath)==null?void 0:t.includes("lite"))?Bx=["ld_3d","output_segmentation","output_heatmap","world_3d","output_poseflag"]:Bx=["Identity","Identity_2","Identity_3","Identity_4","Identity_1"],!dn[1]||!dn[1].modelUrl?ae("load model failed:",e.body.modelPath):e.debug&&ae("load model:",dn[1].modelUrl)}return dn[1]}function ige(e,t){let n=e.map(o=>o.position[0]),s=e.map(o=>o.position[1]),r=[Math.min(...n),Math.min(...s),Math.max(...n)-Math.min(...n),Math.max(...s)-Math.min(...s)],a=[r[0]/t[0],r[1]/t[1],r[2]/t[0],r[3]/t[1]];return{keypointsBox:r,keypointsBoxRaw:a}}async function lge(e){let t={};if(!e.shape||!e.shape[1]||!e.shape[2])return e;Uo=[[0,0],[e.shape[2]>e.shape[1]?Math.trunc((e.shape[2]-e.shape[1])/2):0,e.shape[2]>e.shape[1]?Math.trunc((e.shape[2]-e.shape[1])/2):0],[e.shape[1]>e.shape[2]?Math.trunc((e.shape[1]-e.shape[2])/2):0,e.shape[1]>e.shape[2]?Math.trunc((e.shape[1]-e.shape[2])/2):0],[0,0]],t.pad=qs(e,Uo),t.resize=$e.resizeBilinear(t.pad,[Vo[1][0],Vo[1][1]]);let n=fe(t.resize,255);return Object.keys(t).forEach(s=>Q(t[s])),n}function uge(e,t){for(let n of e)n.position=[n.position[0]*(t[0]+Uo[2][0]+Uo[2][1])/t[0]-Uo[2][0],n.position[1]*(t[1]+Uo[1][0]+Uo[1][1])/t[1]-Uo[1][0],n.position[2]],n.positionRaw=[n.position[0]/t[0],n.position[1]/t[1],n.position[2]];return e}var Y6=e=>1-1/(1+Math.exp(e));async function cge(e,t,n){var h;let s={};s.input=await lge(e),[s.ld,s.segmentation,s.heatmap,s.world,s.poseflag]=await((h=dn[1])==null?void 0:h.execute(s.input,Bx));let r=(await s.poseflag.data())[0],a=Math.max(0,(r-.8)/(1-.8)),o=await s.ld.data(),i=[],l=5;for(let f=0;fQ(s[f]));let d={};for(let[f,m]of Object.entries(Mx)){let g=[];for(let A=0;Ab.part===m[A]),x=c.find(b=>b.part===m[A+1]);y&&x&&y.score>(t.body.minConfidence||0)&&x.score>(t.body.minConfidence||0)&&g.push([y.position,x.position])}d[f]=g}return{id:0,score:Math.trunc(100*a)/100,box:u.keypointsBox,boxRaw:u.keypointsBoxRaw,keypoints:c,annotations:d}}async function Wx(e,t){let n=[e.shape[2]||0,e.shape[1]||0],s=(t.body.skipTime||0)>pe()-X6,r=Lx<(t.body.skipFrames||0);return t.skipAllowed&&s&&r&&Gm!==null?Lx++:(Gm=await cge(e,t,n),X6=pe(),Lx=0),Gm?[Gm]:[]}var cc=[{class:1,label:"person"},{class:2,label:"bicycle"},{class:3,label:"car"},{class:4,label:"motorcycle"},{class:5,label:"airplane"},{class:6,label:"bus"},{class:7,label:"train"},{class:8,label:"truck"},{class:9,label:"boat"},{class:10,label:"traffic light"},{class:11,label:"fire hydrant"},{class:12,label:"stop sign"},{class:13,label:"parking meter"},{class:14,label:"bench"},{class:15,label:"bird"},{class:16,label:"cat"},{class:17,label:"dog"},{class:18,label:"horse"},{class:19,label:"sheep"},{class:20,label:"cow"},{class:21,label:"elephant"},{class:22,label:"bear"},{class:23,label:"zebra"},{class:24,label:"giraffe"},{class:25,label:"backpack"},{class:26,label:"umbrella"},{class:27,label:"handbag"},{class:28,label:"tie"},{class:29,label:"suitcase"},{class:30,label:"frisbee"},{class:31,label:"skis"},{class:32,label:"snowboard"},{class:33,label:"sports ball"},{class:34,label:"kite"},{class:35,label:"baseball bat"},{class:36,label:"baseball glove"},{class:37,label:"skateboard"},{class:38,label:"surfboard"},{class:39,label:"tennis racket"},{class:40,label:"bottle"},{class:41,label:"wine glass"},{class:42,label:"cup"},{class:43,label:"fork"},{class:44,label:"knife"},{class:45,label:"spoon"},{class:46,label:"bowl"},{class:47,label:"banana"},{class:48,label:"apple"},{class:49,label:"sandwich"},{class:50,label:"orange"},{class:51,label:"broccoli"},{class:52,label:"carrot"},{class:53,label:"hot dog"},{class:54,label:"pizza"},{class:55,label:"donut"},{class:56,label:"cake"},{class:57,label:"chair"},{class:58,label:"couch"},{class:59,label:"potted plant"},{class:60,label:"bed"},{class:61,label:"dining table"},{class:62,label:"toilet"},{class:63,label:"tv"},{class:64,label:"laptop"},{class:65,label:"mouse"},{class:66,label:"remote"},{class:67,label:"keyboard"},{class:68,label:"cell phone"},{class:69,label:"microwave"},{class:70,label:"oven"},{class:71,label:"toaster"},{class:72,label:"sink"},{class:73,label:"refrigerator"},{class:74,label:"book"},{class:75,label:"clock"},{class:76,label:"vase"},{class:77,label:"scissors"},{class:78,label:"teddy bear"},{class:79,label:"hair drier"},{class:80,label:"toothbrush"}];var Qs,Sl=0,Hm=[],J6=0,Vx=Number.MAX_SAFE_INTEGER;async function Q6(e){if(ye.initial&&(Qs=null),Qs)e.debug&&ae("cached model:",Qs.modelUrl);else{dc(["floormod"],e),Qs=await st(at(e.modelBasePath,e.object.modelPath||""));let t=Object.values(Qs.modelSignature.inputs);Sl=Array.isArray(t)?parseInt(t[0].tensorShape.dim[2].size):0,!Qs||!Qs.modelUrl?ae("load model failed:",e.object.modelPath):e.debug&&ae("load model:",Qs.modelUrl)}return Qs}async function dge(e,t,n){if(!e)return[];let s=[],r=await e.array(),a=pt(e);Q(e);let o=Sn(a,6,1);Q(a);let i=Pn([o[1],o[0],o[3],o[2]],1),l=pt(i);Q(i);let c=pt(o[4]),u=pt(o[5]);o.forEach(f=>Q(f));let d=await $e.nonMaxSuppressionAsync(l,c,n.object.maxDetected,n.object.iouThreshold,n.object.minConfidence);Q(l),Q(c),Q(u);let p=await d.data();Q(d);let h=0;for(let f of p){let m=Math.trunc(100*r[0][f][4])/100,g=r[0][f][5],A=cc[g].label,[y,x]=[r[0][f][0]/Sl,r[0][f][1]/Sl],b=[y,x,r[0][f][2]/Sl-y,r[0][f][3]/Sl-x],w=[Math.trunc(b[0]*t[0]),Math.trunc(b[1]*t[1]),Math.trunc(b[2]*t[0]),Math.trunc(b[3]*t[1])];s.push({id:h++,score:m,class:g,label:A,box:w,boxRaw:b})}return s}async function Ux(e,t){let n=(t.object.skipTime||0)>pe()-J6,s=Vx<(t.object.skipFrames||0);return t.skipAllowed&&n&&s&&Hm.length>0?(Vx++,Hm):(Vx=0,!ye.kernels.includes("mod")||!ye.kernels.includes("sparsetodense")?Hm:new Promise(async r=>{let a=[e.shape[2],e.shape[1]],o=$e.resizeBilinear(e,[Sl,Sl]),i=t.object.enabled?Qs==null?void 0:Qs.execute(o,["tower_0/detections"]):null;J6=pe(),Q(o);let l=await dge(i,a,t);Hm=l,r(l)}))}var jx={};qp(jx,{connected:()=>Hx,kpt:()=>Gx});var Gx=["head","neck","rightShoulder","rightElbow","rightWrist","chest","leftShoulder","leftElbow","leftWrist","bodyCenter","rightHip","rightKnee","rightAnkle","leftHip","leftKnee","leftAnkle"],Hx={leftLeg:["leftHip","leftKnee","leftAnkle"],rightLeg:["rightHip","rightKnee","rightAnkle"],torso:["leftShoulder","rightShoulder","rightHip","leftHip","leftShoulder"],leftArm:["leftShoulder","leftElbow","leftWrist"],rightArm:["rightShoulder","rightElbow","rightWrist"],head:[]};var pn,e8=0,Zn={id:0,keypoints:[],box:[0,0,0,0],boxRaw:[0,0,0,0],score:0,annotations:{}},qx=Number.MAX_SAFE_INTEGER;async function Xx(e){return ye.initial&&(pn=null),pn?e.debug&&ae("cached model:",pn.modelUrl):(pn=await st(at(e.modelBasePath,e.body.modelPath||"")),!pn||!pn.modelUrl?ae("load model failed:",e.body.modelPath):e.debug&&ae("load model:",pn.modelUrl)),pn}function pge(e,t){let[n,s]=e.shape;return j(()=>{let r=(i,l)=>xe(i,W(fe(i,Ee(l,"int32")),Ee(l,"int32"))),a=G(e,[s*n]),o=rs(a,0).dataSync()[0];if(o>t){let i=Hs(a,0),l=r(i,n).dataSync()[0],c=fe(i,Ee(n,"int32")).dataSync()[0];return[l,c,o]}return[0,0,o]})}async function Kx(e,t){let n=(t.body.skipTime||0)>pe()-e8,s=qx<(t.body.skipFrames||0);return t.skipAllowed&&n&&s&&Object.keys(Zn.keypoints).length>0?(qx++,[Zn]):(qx=0,new Promise(async r=>{var d;let a=j(()=>{if(!(pn==null?void 0:pn.inputs[0].shape))return null;let p=$e.resizeBilinear(e,[pn.inputs[0].shape[2],pn.inputs[0].shape[1]],!1);return W(p,2).sub(1)}),o;if(t.body.enabled&&(o=await(pn==null?void 0:pn.predict(a))),e8=pe(),Q(a),o){Zn.keypoints.length=0;let p=o.squeeze();Q(o);let h=p.unstack(2);Q(p);for(let f=0;f(((d=t.body)==null?void 0:d.minConfidence)||0)&&Zn.keypoints.push({score:Math.round(100*A)/100,part:Gx[f],positionRaw:[m/pn.inputs[0].shape[2],g/pn.inputs[0].shape[1]],position:[Math.round(e.shape[2]*m/pn.inputs[0].shape[2]),Math.round(e.shape[1]*g/pn.inputs[0].shape[1])]})}h.forEach(f=>Q(f))}Zn.score=Zn.keypoints.reduce((p,h)=>h.score>p?h.score:p,0);let i=Zn.keypoints.map(p=>p.position[0]),l=Zn.keypoints.map(p=>p.position[1]);Zn.box=[Math.min(...i),Math.min(...l),Math.max(...i)-Math.min(...i),Math.max(...l)-Math.min(...l)];let c=Zn.keypoints.map(p=>p.positionRaw[0]),u=Zn.keypoints.map(p=>p.positionRaw[1]);Zn.boxRaw=[Math.min(...c),Math.min(...u),Math.max(...c)-Math.min(...c),Math.max(...u)-Math.min(...u)];for(let[p,h]of Object.entries(Hx)){let f=[];for(let m=0;my.part===h[m]),A=Zn.keypoints.find(y=>y.part===h[m+1]);g&&A&&g.score>(t.body.minConfidence||0)&&A.score>(t.body.minConfidence||0)&&f.push([g.position,A.position])}Zn.annotations[p]=f}r([Zn])}))}var hge=["angry","disgust","fear","happy","sad","surprise","neutral"],hn,jm=[],t8=0,n8=0,Zx=Number.MAX_SAFE_INTEGER,Yx=[.2989,.587,.114];async function s8(e){var t,n;return ye.initial&&(hn=null),hn?e.debug&&ae("cached model:",hn.modelUrl):(hn=await st(at(e.modelBasePath,((t=e.face.emotion)==null?void 0:t.modelPath)||"")),!hn||!hn.modelUrl?ae("load model failed:",(n=e.face.emotion)==null?void 0:n.modelPath):e.debug&&ae("load model:",hn.modelUrl)),hn}async function Jx(e,t,n,s){var o,i;if(!hn)return null;let r=Zx<(((o=t.face.emotion)==null?void 0:o.skipFrames)||0),a=(((i=t.face.emotion)==null?void 0:i.skipTime)||0)>pe()-n8;return t.skipAllowed&&a&&r&&t8===s&&jm[n]&&jm[n].length>0?(Zx++,jm[n]):(Zx=0,new Promise(async l=>{var u,d;let c=[];if((u=t.face.emotion)==null?void 0:u.enabled){let p=$e.resizeBilinear(e,[(hn==null?void 0:hn.inputs[0].shape)?hn.inputs[0].shape[2]:0,(hn==null?void 0:hn.inputs[0].shape)?hn.inputs[0].shape[1]:0],!1),[h,f,m]=Sn(p,3,3);Q(p);let g=W(h,Yx[0]),A=W(f,Yx[1]),y=W(m,Yx[2]);Q(h),Q(f),Q(m);let x=Vh([g,A,y]);Q(g),Q(A),Q(y);let b=j(()=>W(xe(x,.5),2));Q(x);let w=await(hn==null?void 0:hn.predict(b));n8=pe();let k=await w.data();Q(w);for(let S=0;S(((d=t.face.emotion)==null?void 0:d.minConfidence)||0)&&c.push({score:Math.min(.99,Math.trunc(100*k[S])/100),emotion:hge[S]});c.sort((S,E)=>E.score-S.score),Q(b)}jm[n]=c,t8=s,l(c)}))}var er,Go=0,fge=2.3,Qx=Lr.leftEyeLower0,eb=Lr.rightEyeLower0,pc={leftBounds:[Qx[0],Qx[Qx.length-1]],rightBounds:[eb[0],eb[eb.length-1]]},hc={upperCenter:3,lowerCenter:4,index:71,numCoordinates:76};async function r8(e){var t,n;return ye.initial&&(er=null),er?e.debug&&ae("cached model:",er.modelUrl):(er=await st(at(e.modelBasePath,((t=e.face.iris)==null?void 0:t.modelPath)||"")),!er||!er.modelUrl?ae("load model failed:",(n=e.face.iris)==null?void 0:n.modelPath):e.debug&&ae("load model:",er.modelUrl)),Go=er.inputs[0].shape?er.inputs[0].shape[2]:0,Go===-1&&(Go=64),er}function qm(e,t,n,s){for(let r=0;r{let t=e[pc.leftBounds[0]][2],n=e[pc.rightBounds[0]][2];return t-n},a8=(e,t,n,s,r=!1,a)=>{let o=fp(hp(Vm([e[n],e[s]]),fge)),i=pp(o),l=$e.cropAndResize(t,[[o.startPoint[1]/a,o.startPoint[0]/a,o.endPoint[1]/a,o.endPoint[0]/a]],[0],[Go,Go]);if(r&&ye.kernels.includes("flipleftright")){let c=$e.flipLeftRight(l);Q(l),l=c}return{box:o,boxSize:i,crop:l}},o8=(e,t,n,s=!1)=>{let r=[];for(let a=0;a{let s=e[Lr[`${n}EyeUpper0`][hc.upperCenter]][2],r=e[Lr[`${n}EyeLower0`][hc.lowerCenter]][2],a=(s+r)/2;return t.map((o,i)=>{let l=a;return i===2?l=s:i===4&&(l=r),[o[0],o[1],l]})};async function l8(e,t,n,s){if(!er)return n.debug&&ae("face mesh iris detection requested, but model is not loaded"),e;let{box:r,boxSize:a,crop:o}=a8(e,t,pc.leftBounds[0],pc.leftBounds[1],!0,s),{box:i,boxSize:l,crop:c}=a8(e,t,pc.rightBounds[0],pc.rightBounds[1],!0,s),u=It([o,c]);Q(o),Q(c);let d=er.predict(u);Q(u);let p=await d.data();Q(d);let h=p.slice(0,hc.numCoordinates*3),{rawCoords:f,iris:m}=o8(h,r,a,!0),g=p.slice(hc.numCoordinates*3),{rawCoords:A,iris:y}=o8(g,i,l),x=mge(e);Math.abs(x)<30?(qm(e,f,"left",null),qm(e,A,"right",null)):x<1?qm(e,f,"left",["EyeUpper0","EyeLower0"]):qm(e,A,"right",["EyeUpper0","EyeLower0"]);let b=i8(e,m,"left"),w=i8(e,y,"right");return e.concat(b).concat(w)}var Br=[],tr=null,xr=0,tb=Number.MAX_SAFE_INTEGER,u8=0,c8=0;async function d8(e,t){var i,l,c,u,d,p,h,f,m,g,A;let n=(((i=t.face.detector)==null?void 0:i.skipTime)||0)>pe()-u8,s=tb<(((l=t.face.detector)==null?void 0:l.skipFrames)||0);if(!t.skipAllowed||!n||!s||c8===0){let y=await j6(e,t);u8=pe(),Br=[];for(let x of y.boxes){let b=await x.box.startPoint.data(),w=await x.box.endPoint.data(),k=await x.landmarks.array();Br.push({startPoint:b,endPoint:w,landmarks:k,confidence:x.confidence})}y.boxes.forEach(x=>Q([x.box.startPoint,x.box.endPoint,x.landmarks]));for(let x=0;x[P[0]/(e.shape[2]||0),P[1]/(e.shape[1]||0),(P[2]||0)/xr]),y={...hp(Vm(w.mesh),1.5),confidence:y.confidence};for(let P of Object.keys(Lr))w.annotations[P]=Lr[P].map(T=>w.mesh[T]);((m=t.face.detector)==null?void 0:m.rotation)&&t.face.mesh.enabled&&((g=t.face.description)==null?void 0:g.enabled)&&ye.kernels.includes("rotatewithoffset")&&(Q(w.tensor),[x,b,w.tensor]=Px(y,e,xr)),w.box=$x(y,e),w.boxRaw=Dx(y,e),w.score=Math.round(100*$||100*y.confidence||0)/100,w.faceScore=Math.round(100*$)/100,y={...fp(y),confidence:y.confidence,faceConfidence:$}}}else{w.box=$x(y,e),w.boxRaw=Dx(y,e),w.score=Math.round(100*y.confidence||0)/100,w.mesh=y.landmarks.map(k=>[(y.startPoint[0]+y.endPoint[0])/2+(y.endPoint[0]+y.startPoint[0])*k[0]/mp(),(y.startPoint[1]+y.endPoint[1])/2+(y.endPoint[1]+y.startPoint[1])*k[1]/mp()]),w.meshRaw=w.mesh.map(k=>[k[0]/(e.shape[2]||0),k[1]/(e.shape[1]||0),(k[2]||0)/xr]);for(let k of Object.keys(cp))w.annotations[k]=[w.mesh[cp[k]]]}r.push(w),a.push(y)}return((A=t.face.mesh)==null?void 0:A.enabled)&&(Br=a.filter(y=>{var x;return y.confidence>(((x=t.face.detector)==null?void 0:x.minConfidence)||0)})),c8=r.length,r}async function p8(e){var t,n;return ye.initial&&(tr=null),tr?e.debug&&ae("cached model:",tr.modelUrl):(tr=await st(at(e.modelBasePath,((t=e.face.mesh)==null?void 0:t.modelPath)||"")),!tr||!tr.modelUrl?ae("load model failed:",(n=e.face.mesh)==null?void 0:n.modelPath):e.debug&&ae("load model:",tr.modelUrl)),xr=tr.inputs[0].shape?tr.inputs[0].shape[2]:0,xr===-1&&(xr=64),tr}var h8=kl,f8=dp;var Yn,Xm=[],m8=0,g8=0,nb=Number.MAX_SAFE_INTEGER;async function A8(e){var n,s;let t=at(e.modelBasePath,((n=e.face.description)==null?void 0:n.modelPath)||"");return ye.initial&&(Yn=null),Yn?e.debug&&ae("cached model:",t):(Yn=await st(t),Yn?e.debug&&ae("load model:",t):ae("load model failed:",((s=e.face.description)==null?void 0:s.modelPath)||"")),Yn}function sb(e){return j(()=>{let n=e.image||e.tensor||e;if(!(n instanceof Ye))return null;let s=[[.05,.15,.85,.85]];if(!(Yn==null?void 0:Yn.inputs[0].shape))return null;let r=n.shape.length===3?$e.cropAndResize(Kt(n,0),s,[0],[Yn.inputs[0].shape[2],Yn.inputs[0].shape[1]]):$e.cropAndResize(n,s,[0],[Yn.inputs[0].shape[2],Yn.inputs[0].shape[1]]);return W(r,255)})}async function rb(e,t,n,s){var o,i,l,c;if(!Yn)return null;let r=nb<(((o=t.face.description)==null?void 0:o.skipFrames)||0),a=(((i=t.face.description)==null?void 0:i.skipTime)||0)>pe()-m8;return t.skipAllowed&&r&&a&&g8===s&&((l=Xm[n])==null?void 0:l.age)&&((c=Xm[n])==null?void 0:c.age)>0?(nb++,Xm[n]):(nb=0,new Promise(async u=>{var p,h;let d={age:0,gender:"unknown",genderScore:0,descriptor:[]};if((p=t.face.description)==null?void 0:p.enabled){let f=sb(e),m=await(Yn==null?void 0:Yn.predict(f));m8=pe(),Q(f);let A=await(await m.find($=>$.shape[1]===1)).data(),y=Math.trunc(200*Math.abs(A[0]-.5))/100;y>(((h=t.face.description)==null?void 0:h.minConfidence)||0)&&(d.gender=A[0]<=.5?"female":"male",d.genderScore=Math.min(.99,y));let x=Hs(m.find($=>$.shape[1]===100),1),b=(await x.data())[0];Q(x);let k=await m.find($=>$.shape[1]===100).data();d.age=Math.round(k[b-1]>k[b+1]?10*b-100*k[b-1]:10*b+100*k[b+1])/10;let S=m.find($=>$.shape[1]===1024),E=S?await S.data():[];d.descriptor=Array.from(E),m.forEach($=>Q($))}Xm[n]=d,g8=s,u(d)}))}function Km(e){return[Math.abs(e.endPoint[0]-e.startPoint[0]),Math.abs(e.endPoint[1]-e.startPoint[1])]}function gp(e){return[e.startPoint[0]+(e.endPoint[0]-e.startPoint[0])/2,e.startPoint[1]+(e.endPoint[1]-e.startPoint[1])/2]}function y8(e,t,n){let s=t.shape[1],r=t.shape[2],a=[[e.startPoint[1]/s,e.startPoint[0]/r,e.endPoint[1]/s,e.endPoint[0]/r]];return $e.cropAndResize(t,a,[0],n)}function x8(e,t){let n=[e.startPoint[0]*t[0],e.startPoint[1]*t[1]],s=[e.endPoint[0]*t[0],e.endPoint[1]*t[1]],r=e.palmLandmarks.map(a=>[a[0]*t[0],a[1]*t[1]]);return{startPoint:n,endPoint:s,palmLandmarks:r,confidence:e.confidence}}function Zm(e,t=1.5){let n=gp(e),s=Km(e),r=[t*s[0]/2,t*s[1]/2],a=[n[0]-r[0],n[1]-r[1]],o=[n[0]+r[0],n[1]+r[1]];return{startPoint:a,endPoint:o,palmLandmarks:e.palmLandmarks}}function Ym(e){let t=gp(e),n=Km(e),r=Math.max(...n)/2,a=[t[0]-r,t[1]-r],o=[t[0]+r,t[1]+r];return{startPoint:a,endPoint:o,palmLandmarks:e.palmLandmarks}}function gge(e){return e-2*Math.PI*Math.floor((e+Math.PI)/(2*Math.PI))}function b8(e,t){let n=Math.PI/2-Math.atan2(-(t[1]-e[1]),t[0]-e[0]);return gge(n)}var v8=(e,t)=>[[1,0,e],[0,1,t],[0,0,1]];function Ho(e,t){let n=0;for(let s=0;s[n.x,n.y]),this.anchorsTensor=ur(this.anchors),this.inputSize=this.model&&this.model.inputs&&this.model.inputs[0].shape?this.model.inputs[0].shape[2]:0,this.inputSizeTensor=Zt([this.inputSize,this.inputSize]),this.doubleInputSizeTensor=Zt([this.inputSize*2,this.inputSize*2])}normalizeBoxes(t){return j(()=>{let n=_e(t,[0,0],[-1,2]),s=_e(t,[0,2],[-1,2]),r=ie(fe(n,this.inputSizeTensor),this.anchorsTensor),a=fe(s,this.doubleInputSizeTensor),o=W(xe(r,a),this.inputSizeTensor),i=W(ie(r,a),this.inputSizeTensor);return ku([o,i],1)})}normalizeLandmarks(t,n){return j(()=>{let s=ie(fe(G(t,[-1,7,2]),this.inputSizeTensor),this.anchors[n]);return W(s,this.inputSizeTensor)})}async getBoxes(t,n){let s={};s.batched=this.model.predict(t),s.predictions=pt(s.batched),s.scores=j(()=>pt(hs(_e(s.predictions,[0,0],[-1,1]))));let r=await s.scores.data();s.boxes=_e(s.predictions,[0,1],[-1,4]),s.norm=this.normalizeBoxes(s.boxes),s.nms=await $e.nonMaxSuppressionAsync(s.norm,s.scores,3*n.hand.maxDetected,n.hand.iouThreshold,n.hand.minConfidence);let a=await s.nms.array(),o=[];for(let i of a){let l=_e(s.norm,[i,0],[1,-1]),c=j(()=>G(this.normalizeLandmarks(_e(s.predictions,[i,5],[1,14]),i),[-1,2]));o.push({box:l,palmLandmarks:c,confidence:r[i]})}for(let i of Object.keys(s))Q(s[i]);return o}async estimateHandBounds(t,n){let s=t.shape[1],r=t.shape[2],a=j(()=>xe(fe($e.resizeBilinear(t,[this.inputSize,this.inputSize]),127.5),1)),o=await this.getBoxes(a,n);Q(a);let i=[];if(!o||o.length===0)return i;for(let l of o){let c=await l.box.data(),u=c.slice(0,2),d=c.slice(2,4),p=await l.palmLandmarks.array();Q(l.box),Q(l.palmLandmarks),i.push(x8({startPoint:u,endPoint:d,palmLandmarks:p,confidence:l.confidence},[r/this.inputSize,s/this.inputSize]))}return i}};var yge=5,S8=1.65,C8=[0,5,9,13,17,1,2],xge=0,bge=2,T8=0,lb=class{constructor(t,n){de(this,"handDetector");de(this,"handPoseModel");de(this,"inputSize");de(this,"storedBoxes");de(this,"skipped");de(this,"detectedHands");this.handDetector=t,this.handPoseModel=n,this.inputSize=this.handPoseModel&&this.handPoseModel.inputs[0].shape?this.handPoseModel.inputs[0].shape[2]:0,this.storedBoxes=[],this.skipped=Number.MAX_SAFE_INTEGER,this.detectedHands=0}calculateLandmarksBoundingBox(t){let n=t.map(o=>o[0]),s=t.map(o=>o[1]),r=[Math.min(...n),Math.min(...s)],a=[Math.max(...n),Math.max(...s)];return{startPoint:r,endPoint:a}}getBoxForPalmLandmarks(t,n){let s=t.map(a=>ob([...a,1],n)),r=this.calculateLandmarksBoundingBox(s);return Zm(Ym(r),yge)}getBoxForHandLandmarks(t){let n=this.calculateLandmarksBoundingBox(t),s=Zm(Ym(n),S8);s.palmLandmarks=[];for(let r=0;r[o[0]*(h[0]-this.inputSize/2),o[1]*(h[1]-this.inputSize/2),o[2]*h[2]]),l=ab(s,[0,0]),c=i.map(h=>[...ob(h,l),h[2]]),u=k8(r),d=[...gp(n),1],p=[Ho(d,u[0]),Ho(d,u[1])];return c.map(h=>[Math.trunc(h[0]+p[0]),Math.trunc(h[1]+p[1]),Math.trunc(h[2])])}async estimateHands(t,n){let s=!1,r,a=(n.hand.skipTime||0)>pe()-T8,o=this.skipped<(n.hand.skipFrames||0);n.skipAllowed&&a&&o&&(r=await this.handDetector.estimateHandBounds(t,n),this.skipped=0),n.skipAllowed&&this.skipped++,r&&r.length>0&&(r.length!==this.detectedHands&&this.detectedHands!==n.hand.maxDetected||!n.hand.landmarks)&&(this.detectedHands=0,this.storedBoxes=[...r],this.storedBoxes.length>0&&(s=!0));let i=[];for(let l=0;l=n.hand.minConfidence/4){let w=G(x,[-1,3]),k=await w.array();Q(x),Q(w);let S=this.transformRawCoords(k,m,u,f),E=this.getBoxForHandLandmarks(S);this.storedBoxes[l]={...E,confidence:b};let $={landmarks:S,confidence:b,boxConfidence:c.confidence,fingerConfidence:b,box:{topLeft:E.startPoint,bottomRight:E.endPoint}};i.push($)}else this.storedBoxes[l]=null;Q(x)}else{let u=Zm(Ym(c),S8),d={confidence:c.confidence,boxConfidence:c.confidence,fingerConfidence:0,box:{topLeft:u.startPoint,bottomRight:u.endPoint},landmarks:[]};i.push(d)}}return this.storedBoxes=this.storedBoxes.filter(l=>l!==null),this.detectedHands=i.length,i.length>n.hand.maxDetected&&(i.length=n.hand.maxDetected),i}};var Ze={thumb:0,index:1,middle:2,ring:3,pinky:4,all:[0,1,2,3,4],nameMapping:{0:"thumb",1:"index",2:"middle",3:"ring",4:"pinky"},pointsMapping:{0:[[0,1],[1,2],[2,3],[3,4]],1:[[0,5],[5,6],[6,7],[7,8]],2:[[0,9],[9,10],[10,11],[11,12]],3:[[0,13],[13,14],[14,15],[15,16]],4:[[0,17],[17,18],[18,19],[19,20]]},getName:e=>Ze.nameMapping[e],getPoints:e=>Ze.pointsMapping[e]},cs={none:0,half:1,full:2,nameMapping:{0:"none",1:"half",2:"full"},getName:e=>cs.nameMapping[e]},qe={verticalUp:0,verticalDown:1,horizontalLeft:2,horizontalRight:3,diagonalUpRight:4,diagonalUpLeft:5,diagonalDownRight:6,diagonalDownLeft:7,nameMapping:{0:"verticalUp",1:"verticalDown",2:"horizontalLeft",3:"horizontalRight",4:"diagonalUpRight",5:"diagonalUpLeft",6:"diagonalDownRight",7:"diagonalDownLeft"},getName:e=>qe.nameMapping[e]},Jm=class{constructor(t){de(this,"name");de(this,"curls");de(this,"directions");de(this,"weights");de(this,"weightsRelative");this.name=t,this.curls={},this.directions={},this.weights=[1,1,1,1,1],this.weightsRelative=[1,1,1,1,1]}addCurl(t,n,s){typeof this.curls[t]=="undefined"&&(this.curls[t]=[]),this.curls[t].push([n,s])}addDirection(t,n,s){this.directions[t]||(this.directions[t]=[]),this.directions[t].push([n,s])}setWeight(t,n){this.weights[t]=n;let s=this.weights.reduce((r,a)=>r+a,0);this.weightsRelative=this.weights.map(r=>r*5/s)}matchAgainst(t,n){let s=0;for(let r in t){let a=t[r],o=this.curls[r];if(typeof o=="undefined"){s+=this.weightsRelative[r];continue}for(let[i,l]of o)if(a===i){s+=l*this.weightsRelative[r];break}}for(let r in n){let a=n[r],o=this.directions[r];if(typeof o=="undefined"){s+=this.weightsRelative[r];continue}for(let[i,l]of o)if(a===i){s+=l*this.weightsRelative[r];break}}return s/10}};var jo=new Jm("thumbs up");jo.addCurl(Ze.thumb,cs.none,1);jo.addDirection(Ze.thumb,qe.verticalUp,1);jo.addDirection(Ze.thumb,qe.diagonalUpLeft,.25);jo.addDirection(Ze.thumb,qe.diagonalUpRight,.25);for(let e of[Ze.index,Ze.middle,Ze.ring,Ze.pinky])jo.addCurl(e,cs.full,1),jo.addDirection(e,qe.horizontalLeft,1),jo.addDirection(e,qe.horizontalRight,1);var tn=new Jm("victory");tn.addCurl(Ze.thumb,cs.half,.5);tn.addCurl(Ze.thumb,cs.none,.5);tn.addDirection(Ze.thumb,qe.verticalUp,1);tn.addDirection(Ze.thumb,qe.diagonalUpLeft,1);tn.addCurl(Ze.index,cs.none,1);tn.addDirection(Ze.index,qe.verticalUp,.75);tn.addDirection(Ze.index,qe.diagonalUpLeft,1);tn.addCurl(Ze.middle,cs.none,1);tn.addDirection(Ze.middle,qe.verticalUp,1);tn.addDirection(Ze.middle,qe.diagonalUpLeft,.75);tn.addCurl(Ze.ring,cs.full,1);tn.addDirection(Ze.ring,qe.verticalUp,.2);tn.addDirection(Ze.ring,qe.diagonalUpLeft,1);tn.addDirection(Ze.ring,qe.horizontalLeft,.2);tn.addCurl(Ze.pinky,cs.full,1);tn.addDirection(Ze.pinky,qe.verticalUp,.2);tn.addDirection(Ze.pinky,qe.diagonalUpLeft,1);tn.addDirection(Ze.pinky,qe.horizontalLeft,.2);tn.setWeight(Ze.index,2);tn.setWeight(Ze.middle,2);var N8=[jo,tn];var vge=.7,Cl={HALF_CURL_START_LIMIT:60,NO_CURL_START_LIMIT:130,DISTANCE_VOTE_POWER:1.1,SINGLE_ANGLE_VOTE_POWER:.9,TOTAL_ANGLE_VOTE_POWER:1.6};function E8(e,t,n,s){let r=(t-s)/(e-n),a=Math.atan(r)*180/Math.PI;return a<=0?a=-a:a>0&&(a=180-a),a}function R8(e,t){if(!e||!t)return[0,0];let n=E8(e[0],e[1],t[0],t[1]);if(e.length===2)return n;let s=E8(e[1],e[2],t[1],t[2]);return[n,s]}function $8(e,t=1){let n=0,s=0,r=0;return e>=75&&e<=105?n=1*t:e>=25&&e<=155?s=1*t:r=1*t,[n,s,r]}function wge(e,t,n){let s=e[0]-t[0],r=e[0]-n[0],a=t[0]-n[0],o=e[1]-t[1],i=e[1]-n[1],l=t[1]-n[1],c=e[2]-t[2],u=e[2]-n[2],d=t[2]-n[2],p=Math.sqrt(s*s+o*o+c*c),h=Math.sqrt(r*r+i*i+u*u),f=Math.sqrt(a*a+l*l+d*d),m=(f*f+p*p-h*h)/(2*f*p);m>1?m=1:m<-1&&(m=-1);let g=Math.acos(m);g=57.2958*g%180;let A;return g>Cl.NO_CURL_START_LIMIT?A=cs.none:g>Cl.HALF_CURL_START_LIMIT?A=cs.half:A=cs.full,A}function D8(e,t,n,s){let r;return s===Math.abs(e)?e>0?r=qe.horizontalLeft:r=qe.horizontalRight:s===Math.abs(t)?t>0?r=qe.horizontalLeft:r=qe.horizontalRight:n>0?r=qe.horizontalLeft:r=qe.horizontalRight,r}function _8(e,t,n,s){let r;return s===Math.abs(e)?e<0?r=qe.verticalDown:r=qe.verticalUp:s===Math.abs(t)?t<0?r=qe.verticalDown:r=qe.verticalUp:n<0?r=qe.verticalDown:r=qe.verticalUp,r}function kge(e,t,n,s,r,a,o,i){let l,c=_8(e,t,n,s),u=D8(r,a,o,i);return c===qe.verticalUp?u===qe.horizontalLeft?l=qe.diagonalUpLeft:l=qe.diagonalUpRight:u===qe.horizontalLeft?l=qe.diagonalDownLeft:l=qe.diagonalDownRight,l}function Ige(e,t,n,s){let r=e[0]-t[0],a=e[0]-n[0],o=t[0]-n[0],i=e[1]-t[1],l=e[1]-n[1],c=t[1]-n[1],u=Math.max(Math.abs(r),Math.abs(a),Math.abs(o)),d=Math.max(Math.abs(i),Math.abs(l),Math.abs(c)),p=0,h=0,f=0,m=d/(u+1e-5);m>1.5?p+=Cl.DISTANCE_VOTE_POWER:m>.66?h+=Cl.DISTANCE_VOTE_POWER:f+=Cl.DISTANCE_VOTE_POWER;let g=Math.sqrt(r*r+i*i),A=Math.sqrt(a*a+l*l),y=Math.sqrt(o*o+c*c),x=Math.max(g,A,y),b=e[0],w=e[1],k=n[0],S=n[1];x===g?(k=n[0],S=n[1]):x===y&&(b=t[0],w=t[1]);let F=R8([b,w],[k,S]),R=$8(F,Cl.TOTAL_ANGLE_VOTE_POWER);p+=R[0],h+=R[1],f+=R[2];for(let T of s){let M=$8(T,Cl.SINGLE_ANGLE_VOTE_POWER);p+=M[0],h+=M[1],f+=M[2]}let P;return p===Math.max(p,h,f)?P=_8(l,i,c,d):f===Math.max(h,f)?P=D8(a,r,o,u):P=kge(l,i,c,d,a,r,o,u),P}function P8(e){let t=[],n=[],s=[],r=[];if(!e)return{curls:s,directions:r};for(let a of Ze.all){let o=Ze.getPoints(a),i=[],l=[];for(let c of o){let u=e[c[0]],d=e[c[1]],p=R8(u,d),h=p[0],f=p[1];i.push(h),l.push(f)}t.push(i),n.push(l)}for(let a of Ze.all){let o=a===Ze.thumb?1:0,i=Ze.getPoints(a),l=e[i[o][0]],c=e[i[o+1][1]],u=e[i[3][1]],d=wge(l,c,u),p=Ige(l,c,u,t[a].slice(o));s[a]=d,r[a]=p}return{curls:s,directions:r}}function Qm(e){if(!e||e.length===0)return null;let t=P8(e),n={};for(let s of Ze.all)n[Ze.getName(s)]={curl:cs.getName(t.curls[s]),direction:qe.getName(t.directions[s])};return n}function F8(e){let t=[];if(!e||e.length===0)return t;let n=P8(e);for(let s of N8){let r=s.matchAgainst(n.curls,n.directions);r>=vge&&t.push({name:s.name,confidence:r})}return t}var O8={thumb:[1,2,3,4],index:[5,6,7,8],middle:[9,10,11,12],ring:[13,14,15,16],pinky:[17,18,19,20],palm:[0]},la,ua,M8;async function ub(e,t){let n=await M8.estimateHands(e,t);if(!n)return[];let s=[];for(let r=0;rn[r].landmarks[d]);let o=n[r].landmarks,i=[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,0,0],l=[0,0,0,0];if(o&&o.length>0){for(let u of o)u[0]i[2]&&(i[2]=u[0]),u[1]>i[3]&&(i[3]=u[1]);i[2]-=i[0],i[3]-=i[1],l=[i[0]/(e.shape[2]||0),i[1]/(e.shape[1]||0),i[2]/(e.shape[2]||0),i[3]/(e.shape[1]||0)]}else i=n[r].box?[Math.trunc(Math.max(0,n[r].box.topLeft[0])),Math.trunc(Math.max(0,n[r].box.topLeft[1])),Math.trunc(Math.min(e.shape[2]||0,n[r].box.bottomRight[0])-Math.max(0,n[r].box.topLeft[0])),Math.trunc(Math.min(e.shape[1]||0,n[r].box.bottomRight[1])-Math.max(0,n[r].box.topLeft[1]))]:[0,0,0,0],l=[n[r].box.topLeft[0]/(e.shape[2]||0),n[r].box.topLeft[1]/(e.shape[1]||0),(n[r].box.bottomRight[0]-n[r].box.topLeft[0])/(e.shape[2]||0),(n[r].box.bottomRight[1]-n[r].box.topLeft[1])/(e.shape[1]||0)];let c=Qm(o);s.push({id:r,score:Math.round(100*n[r].confidence)/100,boxScore:Math.round(100*n[r].boxConfidence)/100,fingerScore:Math.round(100*n[r].fingerConfidence)/100,label:"hand",box:i,boxRaw:l,keypoints:o,annotations:a,landmarks:c})}return s}async function cb(e){var n,s,r,a,o,i;ye.initial&&(la=null,ua=null),!la||!ua?([la,ua]=await Promise.all([e.hand.enabled?st(at(e.modelBasePath,((n=e.hand.detector)==null?void 0:n.modelPath)||""),{fromTFHub:(((s=e.hand.detector)==null?void 0:s.modelPath)||"").includes("tfhub.dev")}):null,e.hand.landmarks?st(at(e.modelBasePath,((r=e.hand.skeleton)==null?void 0:r.modelPath)||""),{fromTFHub:(((a=e.hand.skeleton)==null?void 0:a.modelPath)||"").includes("tfhub.dev")}):null]),e.hand.enabled&&(!la||!la.modelUrl?ae("load model failed:",((o=e.hand.detector)==null?void 0:o.modelPath)||""):e.debug&&ae("load model:",la.modelUrl),!ua||!ua.modelUrl?ae("load model failed:",((i=e.hand.skeleton)==null?void 0:i.modelPath)||""):e.debug&&ae("load model:",ua.modelUrl))):(e.debug&&ae("cached model:",la.modelUrl),e.debug&&ae("cached model:",ua.modelUrl));let t=new ib(la);return M8=new lb(t,ua),[la,ua]}function Tl(e,t=[1,1]){let n=[e.map(i=>i[0]),e.map(i=>i[1])],s=[Math.min(...n[0]),Math.min(...n[1])],r=[Math.max(...n[0]),Math.max(...n[1])],a=[s[0],s[1],r[0]-s[0],r[1]-s[1]],o=[a[0]/t[0],a[1]/t[1],a[2]/t[0],a[3]/t[1]];return{box:a,boxRaw:o}}function z8(e,t=[1,1]){let n=[e.map(c=>c[0]),e.map(c=>c[1])],s=[Math.min(...n[0]),Math.min(...n[1])],r=[Math.max(...n[0]),Math.max(...n[1])],a=[(s[0]+r[0])/2,(s[1]+r[1])/2],o=Math.max(a[0]-s[0],a[1]-s[1],-a[0]+r[0],-a[1]+r[1]),i=[Math.trunc(a[0]-o),Math.trunc(a[1]-o),Math.trunc(2*o),Math.trunc(2*o)],l=[i[0]/t[0],i[1]/t[1],i[2]/t[0],i[3]/t[1]];return{box:i,boxRaw:l}}function e0(e,t){let n=[e[2]*t,e[3]*t];return[e[0]-(n[0]-e[2])/2,e[1]-(n[1]-e[3])/2,n[0],n[1]]}function db(e){return[Math.max(0,e[1]),Math.max(0,e[0]),Math.min(1,e[3]+e[1]),Math.min(1,e[2]+e[0])]}var Nt=[null,null],Sge=["StatefulPartitionedCall/Postprocessor/Slice","StatefulPartitionedCall/Postprocessor/ExpandDims_1"],qo=[[0,0],[0,0]],Cge=["hand","fist","pinch","point","face","tip","pinchtip"],L8=4,B8=1.6,Tge=512,Nge=1.4,t0=Number.MAX_SAFE_INTEGER,pb=0,ca=[0,0],Xt={boxes:[],hands:[]},W8={thumb:[1,2,3,4],index:[5,6,7,8],middle:[9,10,11,12],ring:[13,14,15,16],pinky:[17,18,19,20],palm:[0]};async function V8(e){var t,n;if(ye.initial&&(Nt[0]=null),Nt[0])e.debug&&ae("cached model:",Nt[0].modelUrl);else{dc(["tensorlistreserve","enter","tensorlistfromtensor","merge","loopcond","switch","exit","tensorliststack","nextiteration","tensorlistsetitem","tensorlistgetitem","reciprocal","shape","split","where"],e),Nt[0]=await st(at(e.modelBasePath,((t=e.hand.detector)==null?void 0:t.modelPath)||""));let s=Object.values(Nt[0].modelSignature.inputs);qo[0][0]=Array.isArray(s)?parseInt(s[0].tensorShape.dim[1].size):0,qo[0][1]=Array.isArray(s)?parseInt(s[0].tensorShape.dim[2].size):0,!Nt[0]||!Nt[0].modelUrl?ae("load model failed:",(n=e.hand.detector)==null?void 0:n.modelPath):e.debug&&ae("load model:",Nt[0].modelUrl)}return Nt[0]}async function U8(e){var t,n;if(ye.initial&&(Nt[1]=null),Nt[1])e.debug&&ae("cached model:",Nt[1].modelUrl);else{Nt[1]=await st(at(e.modelBasePath,((t=e.hand.skeleton)==null?void 0:t.modelPath)||""));let s=Object.values(Nt[1].modelSignature.inputs);qo[1][0]=Array.isArray(s)?parseInt(s[0].tensorShape.dim[1].size):0,qo[1][1]=Array.isArray(s)?parseInt(s[0].tensorShape.dim[2].size):0,!Nt[1]||!Nt[1].modelUrl?ae("load model failed:",(n=e.hand.skeleton)==null?void 0:n.modelPath):e.debug&&ae("load model:",Nt[1].modelUrl)}return Nt[1]}async function Ege(e,t){let n=[];if(!e||!Nt[0])return n;let s={},r=(e.shape[2]||1)/(e.shape[1]||1),a=Math.min(Math.round((e.shape[1]||0)/8)*8,Tge),o=Math.round(a*r/8)*8;s.resize=$e.resizeBilinear(e,[a,o]),s.cast=he(s.resize,"int32"),[s.rawScores,s.rawBoxes]=await Nt[0].executeAsync(s.cast,Sge),s.boxes=pt(s.rawBoxes,[0,2]),s.scores=pt(s.rawScores,[0]);let i=as(s.scores,1);Q(i[L8]),i.splice(L8,1),s.filtered=Pn(i,1),Q(i),s.max=rs(s.filtered,1),s.argmax=Hs(s.filtered,1);let l=0;s.nms=await $e.nonMaxSuppressionAsync(s.boxes,s.max,t.hand.maxDetected,t.hand.iouThreshold,t.hand.minConfidence);let c=await s.nms.data(),u=await s.max.data(),d=await s.argmax.data();for(let p of Array.from(c)){let h=_e(s.boxes,p,1),f=await h.data();Q(h);let m=[f[1],f[0],f[3]-f[1],f[2]-f[0]],g=e0(m,Nge),A=db(g),y=[Math.trunc(m[0]*ca[0]),Math.trunc(m[1]*ca[1]),Math.trunc(m[2]*ca[0]),Math.trunc(m[3]*ca[1])],x=u[p],b=Cge[d[p]],w={id:l++,score:x,box:y,boxRaw:g,boxCrop:A,label:b};n.push(w)}return Object.keys(s).forEach(p=>Q(s[p])),n.sort((p,h)=>h.score-p.score),n.length>(t.hand.maxDetected||1)&&(n.length=t.hand.maxDetected||1),n}async function hb(e,t,n){let s={id:t.id,score:Math.round(100*t.score)/100,boxScore:Math.round(100*t.score)/100,fingerScore:0,box:t.box,boxRaw:t.boxRaw,label:t.label,keypoints:[],landmarks:{},annotations:{}};if(e&&Nt[1]&&n.hand.landmarks&&t.score>(n.hand.minConfidence||0)){let r={};r.crop=$e.cropAndResize(e,[t.boxCrop],[0],[qo[1][0],qo[1][1]],"bilinear"),r.cast=he(r.crop,"float32"),r.div=fe(r.cast,255),[r.score,r.keypoints]=Nt[1].execute(r.div);let a=(await r.score.data())[0],o=(100-Math.trunc(100/(1+Math.exp(a))))/100;if(o>=(n.hand.minConfidence||0)){s.fingerScore=o,r.reshaped=G(r.keypoints,[-1,3]);let c=(await r.reshaped.array()).map(u=>[u[0]/qo[1][1],u[1]/qo[1][0],u[2]||0]).map(u=>[u[0]*t.boxRaw[2],u[1]*t.boxRaw[3],u[2]||0]);s.keypoints=c.map(u=>[ca[0]*(u[0]+t.boxRaw[0]),ca[1]*(u[1]+t.boxRaw[1]),u[2]||0]),s.landmarks=Qm(s.keypoints);for(let u of Object.keys(W8))s.annotations[u]=W8[u].map(d=>s.landmarks&&s.keypoints[d]?s.keypoints[d]:null)}Object.keys(r).forEach(i=>Q(r[i]))}return s}async function fb(e,t){var r,a;if(!Nt[0]||!Nt[1]||!((r=Nt[0])==null?void 0:r.inputs[0].shape)||!((a=Nt[1])==null?void 0:a.inputs[0].shape))return[];ca=[e.shape[2]||0,e.shape[1]||0],t0++;let n=(t.hand.skipTime||0)>pe()-pb,s=t0<(t.hand.skipFrames||0);return t.skipAllowed&&n&&s?Xt.hands:new Promise(async o=>{let i=3*(t.hand.skipTime||0)>pe()-pb,l=t0<3*(t.hand.skipFrames||0);t.skipAllowed&&Xt.hands.length===t.hand.maxDetected?Xt.hands=await Promise.all(Xt.boxes.map(u=>hb(e,u,t))):t.skipAllowed&&i&&l&&Xt.hands.length>0?Xt.hands=await Promise.all(Xt.boxes.map(u=>hb(e,u,t))):(Xt.boxes=await Ege(e,t),pb=pe(),Xt.hands=await Promise.all(Xt.boxes.map(u=>hb(e,u,t))),t0=0);let c=[...Xt.boxes];if(Xt.boxes.length=0,t.cacheSensitivity>0)for(let u=0;u.05&&d.box[3]/(e.shape[1]||1)>.05&&Xt.hands[u].fingerScore&&Xt.hands[u].fingerScore>(t.hand.minConfidence||0)){let p=e0(d.box,B8),h=e0(d.boxRaw,B8),f=db(h);Xt.boxes.push({...c[u],box:p,boxRaw:h,boxCrop:f})}}for(let u=0;us0,horizontal:()=>mb,kpt:()=>n0,relative:()=>Ab,vertical:()=>gb});var n0=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"],mb=[["leftEye","rightEye"],["leftEar","rightEar"],["leftShoulder","rightShoulder"],["leftElbow","rightElbow"],["leftWrist","rightWrist"],["leftHip","rightHip"],["leftKnee","rightKnee"],["leftAnkle","rightAnkle"]],gb=[["leftKnee","leftShoulder"],["rightKnee","rightShoulder"],["leftAnkle","leftKnee"],["rightAnkle","rightKnee"]],Ab=[[["leftHip","rightHip"],["leftShoulder","rightShoulder"]],[["leftElbow","rightElbow"],["leftShoulder","rightShoulder"]]],s0={leftLeg:["leftHip","leftKnee","leftAnkle"],rightLeg:["rightHip","rightKnee","rightAnkle"],torso:["leftShoulder","rightShoulder","rightHip","leftHip","leftShoulder"],leftArm:["leftShoulder","leftElbow","leftWrist"],rightArm:["rightShoulder","rightElbow","rightWrist"],head:[]};var G8=.005,vs={keypoints:[],padding:[[0,0],[0,0],[0,0],[0,0]]};function xb(e){for(let t of mb){let n=e.keypoints.findIndex(r=>r.part===t[0]),s=e.keypoints.findIndex(r=>r.part===t[1]);if(e.keypoints[n]&&e.keypoints[s]&&e.keypoints[n].position[0]r&&r.part===t[0]),s=e.keypoints.findIndex(r=>r&&r.part===t[1]);e.keypoints[n]&&e.keypoints[s]&&e.keypoints[n].position[1]c&&c.part===t[0]),r=e.keypoints.findIndex(c=>c&&c.part===t[1]),a=e.keypoints.findIndex(c=>c&&c.part===n[0]),o=e.keypoints.findIndex(c=>c&&c.part===n[1]);if(!e.keypoints[a]||!e.keypoints[o])continue;let i=e.keypoints[s]?[Math.abs(e.keypoints[a].position[0]-e.keypoints[s].position[0]),Math.abs(e.keypoints[o].position[0]-e.keypoints[s].position[0])]:[0,0],l=e.keypoints[r]?[Math.abs(e.keypoints[o].position[0]-e.keypoints[r].position[0]),Math.abs(e.keypoints[a].position[0]-e.keypoints[r].position[0])]:[0,0];if(i[0]>i[1]||l[0]>l[1]){let c=e.keypoints[s];e.keypoints[s]=e.keypoints[r],e.keypoints[r]=c}}}function H8(e){for(let t=0;te.shape[1]?Math.trunc((e.shape[2]-e.shape[1])/2):0,e.shape[2]>e.shape[1]?Math.trunc((e.shape[2]-e.shape[1])/2):0],[e.shape[1]>e.shape[2]?Math.trunc((e.shape[1]-e.shape[2])/2):0,e.shape[1]>e.shape[2]?Math.trunc((e.shape[1]-e.shape[2])/2):0],[0,0]],n.pad=qs(e,vs.padding),n.resize=$e.resizeBilinear(n.pad,[t,t]);let s=he(n.resize,"int32");return Object.keys(n).forEach(r=>Q(n[r])),s}function q8(e,t){e.keypoints=e.keypoints.filter(s=>s&&s.position);for(let s of e.keypoints)s.position=[s.position[0]*(t[0]+vs.padding[2][0]+vs.padding[2][1])/t[0]-vs.padding[2][0],s.position[1]*(t[1]+vs.padding[1][0]+vs.padding[1][1])/t[1]-vs.padding[1][0]],s.positionRaw=[s.position[0]/t[0],s.position[1]/t[1]];let n=Tl(e.keypoints.map(s=>s.position),t);return e.box=n.box,e.boxRaw=n.boxRaw,e}var Fn,r0=0,bb=Number.MAX_SAFE_INTEGER,Nl={boxes:[],bodies:[],last:0};async function X8(e){return ye.initial&&(Fn=null),Fn?e.debug&&ae("cached model:",Fn.modelUrl):(dc(["size"],e),Fn=await st(at(e.modelBasePath,e.body.modelPath||"")),!Fn||!Fn.modelUrl?ae("load model failed:",e.body.modelPath):e.debug&&ae("load model:",Fn.modelUrl)),r0=Fn.inputs[0].shape?Fn.inputs[0].shape[2]:0,r0===-1&&(r0=256),Fn}async function Rge(e,t,n,s){let r=e[0][0],a=[],o=0;for(let d=0;dt.body.minConfidence){let p=[(s[3]-s[1])*r[d][1]+s[1],(s[2]-s[0])*r[d][0]+s[0]];a.push({score:Math.round(100*o)/100,part:n0[d],positionRaw:p,position:[Math.round((n.shape[2]||0)*p[0]),Math.round((n.shape[1]||0)*p[1])]})}o=a.reduce((d,p)=>p.score>d?p.score:d,0);let i=[],l=Tl(a.map(d=>d.position),[n.shape[2],n.shape[1]]),c={};for(let[d,p]of Object.entries(s0)){let h=[];for(let f=0;fA.part===p[f]),g=a.find(A=>A.part===p[f+1]);m&&g&&m.score>(t.body.minConfidence||0)&&g.score>(t.body.minConfidence||0)&&h.push([m.position,g.position])}c[d]=h}let u={id:0,score:o,box:l.box,boxRaw:l.boxRaw,keypoints:a,annotations:c};return xb(u),i.push(u),i}async function $ge(e,t,n,s){let r=[];for(let a=0;at.body.minConfidence){let l=[];for(let p=0;p<17;p++){let h=o[3*p+2];if(h>t.body.minConfidence){let f=[(s[3]-s[1])*o[3*p+1]+s[1],(s[2]-s[0])*o[3*p+0]+s[0]];l.push({part:n0[p],score:Math.round(100*h)/100,positionRaw:f,position:[Math.round((n.shape[2]||0)*f[0]),Math.round((n.shape[1]||0)*f[1])]})}}let c=Tl(l.map(p=>p.position),[n.shape[2],n.shape[1]]),u={};for(let[p,h]of Object.entries(s0)){let f=[];for(let m=0;my.part===h[m]),A=l.find(y=>y.part===h[m+1]);g&&A&&g.score>(t.body.minConfidence||0)&&A.score>(t.body.minConfidence||0)&&f.push([g.position,A.position])}u[p]=f}let d={id:a,score:i,box:c.box,boxRaw:c.boxRaw,keypoints:[...l],annotations:u};xb(d),r.push(d)}}return r.sort((a,o)=>o.score-a.score),r.length>t.body.maxDetected&&(r.length=t.body.maxDetected),r}async function vb(e,t){if(!Fn||!(Fn==null?void 0:Fn.inputs[0].shape))return[];t.skipAllowed||(Nl.boxes.length=0),bb++;let n=(t.body.skipTime||0)>pe()-Nl.last,s=bb<(t.body.skipFrames||0);return t.skipAllowed&&n&&s?Nl.bodies:new Promise(async r=>{let a={};bb=0,a.input=j8(e,r0),a.res=await(Fn==null?void 0:Fn.predict(a.input)),Nl.last=pe();let o=await a.res.array();Nl.bodies=a.res.shape[2]===17?await Rge(o,t,e,[0,0,1,1]):await $ge(o,t,e,[0,0,1,1]);for(let i of Nl.bodies)q8(i,[e.shape[2]||1,e.shape[1]||1]),H8(i.keypoints);Object.keys(a).forEach(i=>Q(a[i])),r(Nl.bodies)})}var ws,a0=[],K8=0,wb=Number.MAX_SAFE_INTEGER,o0=2.5;async function Z8(e){if(!ws||ye.initial){ws=await st(at(e.modelBasePath,e.object.modelPath||""));let t=Object.values(ws.modelSignature.inputs);if(ws.inputSize=Array.isArray(t)?parseInt(t[0].tensorShape.dim[2].size):null,!ws.inputSize)throw new Error(`cannot determine model inputSize: ${e.object.modelPath}`);!ws||!ws.modelUrl?ae("load model failed:",e.object.modelPath):e.debug&&ae("load model:",ws.modelUrl)}else e.debug&&ae("cached model:",ws.modelUrl);return ws}async function Dge(e,t,n,s){let r=0,a=[];for(let c of[1,2,4])j(async()=>{var g,A;let u=c*13,d=(g=e.find(y=>y.shape[1]===u**2&&y.shape[2]===cc.length))==null?void 0:g.squeeze(),p=(A=e.find(y=>y.shape[1]===u**2&&y.shape[2]s.object.minConfidence&&x!==61){let w=(.5+Math.trunc(y%u))/u,k=(.5+Math.trunc(y/u))/u,S=f[y].map(U=>U*(u/c/t)),[E,$]=[w-o0/c*S[0],k-o0/c*S[1]],[F,R]=[w+o0/c*S[2]-E,k+o0/c*S[3]-$],P=[E,$,F,R];P=P.map(U=>Math.max(0,Math.min(U,1)));let T=[P[0]*n[0],P[1]*n[1],P[2]*n[0],P[3]*n[1]],M={id:r++,score:Math.round(100*b)/100,class:x+1,label:cc[x].label,box:T.map(U=>Math.trunc(U)),boxRaw:P};a.push(M)}}});e.forEach(c=>Q(c));let o=a.map(c=>[c.boxRaw[1],c.boxRaw[0],c.boxRaw[3],c.boxRaw[2]]),i=a.map(c=>c.score),l=[];if(o&&o.length>0){let c=await $e.nonMaxSuppressionAsync(o,i,s.object.maxDetected,s.object.iouThreshold,s.object.minConfidence);l=await c.data(),Q(c)}return a=a.filter((c,u)=>l.includes(u)).sort((c,u)=>u.score-c.score),a}async function kb(e,t){let n=(t.object.skipTime||0)>pe()-K8,s=wb<(t.object.skipFrames||0);return t.skipAllowed&&n&&s&&a0.length>0?(wb++,a0):(wb=0,!ye.kernels.includes("mod")||!ye.kernels.includes("sparsetodense")?a0:new Promise(async r=>{let a=[e.shape[2],e.shape[1]],o=$e.resizeBilinear(e,[ws.inputSize,ws.inputSize],!1),i=fe(o,255),l=i.transpose([0,3,1,2]);Q(i),Q(o);let c;t.object.enabled&&(c=await ws.predict(l)),K8=pe(),Q(l);let u=await Dge(c,ws.inputSize,a,t);a0=u,r(u)}))}var Ap=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"],_ge=Ap.length,yp=Ap.reduce((e,t,n)=>(e[t]=n,e),{}),Pge=[["leftHip","leftShoulder"],["leftElbow","leftShoulder"],["leftElbow","leftWrist"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["rightHip","rightShoulder"],["rightElbow","rightShoulder"],["rightElbow","rightWrist"],["rightHip","rightKnee"],["rightKnee","rightAnkle"],["leftShoulder","rightShoulder"],["leftHip","rightHip"]],hAe=Pge.map(([e,t])=>[yp[e],yp[t]]),Y8=[["nose","leftEye"],["leftEye","leftEar"],["nose","rightEye"],["rightEye","rightEar"],["nose","leftShoulder"],["leftShoulder","leftElbow"],["leftElbow","leftWrist"],["leftShoulder","leftHip"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["nose","rightShoulder"],["rightShoulder","rightElbow"],["rightElbow","rightWrist"],["rightShoulder","rightHip"],["rightHip","rightKnee"],["rightKnee","rightAnkle"]];function J8(e){let t=e.reduce(({maxX:n,maxY:s,minX:r,minY:a},{position:{x:o,y:i}})=>({maxX:Math.max(n,o),maxY:Math.max(s,i),minX:Math.min(r,o),minY:Math.min(a,i)}),{maxX:Number.NEGATIVE_INFINITY,maxY:Number.NEGATIVE_INFINITY,minX:Number.POSITIVE_INFINITY,minY:Number.POSITIVE_INFINITY});return[t.minX,t.minY,t.maxX-t.minX,t.maxY-t.minY]}function Q8(e,[t,n],[s,r]){let a=t/s,o=n/r,i=(c,u)=>({id:u,score:c.score,boxRaw:[c.box[0]/r,c.box[1]/s,c.box[2]/r,c.box[3]/s],box:[Math.trunc(c.box[0]*o),Math.trunc(c.box[1]*a),Math.trunc(c.box[2]*o),Math.trunc(c.box[3]*a)],keypoints:c.keypoints.map(({score:d,part:p,position:h})=>({score:d,part:p,position:[Math.trunc(h.x*o),Math.trunc(h.y*a)],positionRaw:[h.x/s,h.y/s]}))});return e.map((c,u)=>i(c,u))}var Ib=class{constructor(t,n){de(this,"priorityQueue");de(this,"numberOfElements");de(this,"getElementValue");this.priorityQueue=new Array(t),this.numberOfElements=-1,this.getElementValue=n}enqueue(t){this.priorityQueue[++this.numberOfElements]=t,this.swim(this.numberOfElements)}dequeue(){let t=this.priorityQueue[0];return this.exchange(0,this.numberOfElements--),this.sink(0),this.priorityQueue[this.numberOfElements+1]=null,t}empty(){return this.numberOfElements===-1}size(){return this.numberOfElements+1}all(){return this.priorityQueue.slice(0,this.numberOfElements+1)}max(){return this.priorityQueue[0]}swim(t){for(;t>0&&this.less(Math.floor(t/2),t);)this.exchange(t,Math.floor(t/2)),t=Math.floor(t/2)}sink(t){for(;2*t<=this.numberOfElements;){let n=2*t;if(nn?n:e}function eT(e,t,n,s){let r=n-e,a=s-t;return r*r+a*a}function Nb(e,t){return{x:e.x+t.x,y:e.y+t.y}}var ks,Fge=["MobilenetV1/offset_2/BiasAdd","MobilenetV1/heatmap_2/BiasAdd","MobilenetV1/displacement_fwd_2/BiasAdd","MobilenetV1/displacement_bwd_2/BiasAdd"],i0=1,fc=16,Oge=50**2;function tT(e,t,n,s,r,a,o=2){let i=A=>({y:a.get(A.y,A.x,e),x:a.get(A.y,A.x,a.shape[2]/2+e)}),l=(A,y,x)=>({y:Tb(Math.round(A.y/fc),0,y-1),x:Tb(Math.round(A.x/fc),0,x-1)}),[c,u]=s.shape,d=l(t.position,c,u),p=i(d),f=Nb(t.position,p);for(let A=0;A[yp[p],yp[h]]),o=a.map(([,p])=>p),i=a.map(([p])=>p),l=t.shape[2],c=o.length,u=new Array(l),d=Cb(e.part,fc,n);u[e.part.id]={score:e.score,part:Ap[e.part.id],position:d};for(let p=c-1;p>=0;--p){let h=o[p],f=i[p];u[h]&&!u[f]&&(u[f]=tT(p,u[h],f,t,n,r))}for(let p=0;pt){i=!1;break}if(!i)break}return i}function Lge(e,t){let[n,s,r]=t.shape,a=new Ib(n*s*r,({score:o})=>o);for(let o=0;o{var o;let a=(o=r[s])==null?void 0:o.position;return a?eT(n,t,a.y,a.x)<=Oge:!1})}function Bge(e,t){return t.reduce((s,{position:r,score:a},o)=>(nT(e,r,o)||(s+=a),s),0)/t.length}function Wge(e,t,n,s,r,a){let o=[],i=Lge(a,t);for(;o.lengthh.score>a);let d=Bge(o,u),p=J8(u);d>a&&o.push({keypoints:u,box:p,score:Math.round(100*d)/100})}return o}async function Eb(e,t){let n=j(()=>{if(!ks.inputs[0].shape)return[];let o=$e.resizeBilinear(e,[ks.inputs[0].shape[2],ks.inputs[0].shape[1]]),i=xe(fe(he(o,"float32"),127.5),1),c=ks.execute(i,Fge).map(u=>pt(u,[0]));return c[1]=c[1].sigmoid(),c}),s=await Promise.all(n.map(o=>o.buffer()));for(let o of n)Q(o);let r=await Wge(s[0],s[1],s[2],s[3],t.body.maxDetected,t.body.minConfidence);return ks.inputs[0].shape?Q8(r,[e.shape[1],e.shape[2]],[ks.inputs[0].shape[2],ks.inputs[0].shape[1]]):[]}async function sT(e){return!ks||ye.initial?(ks=await st(at(e.modelBasePath,e.body.modelPath||"")),!ks||!ks.modelUrl?ae("load model failed:",e.body.modelPath):e.debug&&ae("load model:",ks.modelUrl)):e.debug&&ae("cached model:",ks.modelUrl),ks}var zs,Rb=!1;async function $b(e){return!zs||ye.initial?(zs=await st(at(e.modelBasePath,e.segmentation.modelPath||"")),!zs||!zs.modelUrl?ae("load model failed:",e.segmentation.modelPath):e.debug&&ae("load model:",zs.modelUrl)):e.debug&&ae("cached model:",zs.modelUrl),zs}async function rT(e,t,n){var m,g;if(Rb)return{data:[],canvas:null,alpha:null};Rb=!0,zs||await $b(n);let s=uc(e,n),r=((m=s.canvas)==null?void 0:m.width)||0,a=((g=s.canvas)==null?void 0:g.height)||0;if(!s.tensor)return{data:[],canvas:null,alpha:null};let o={};o.resize=$e.resizeBilinear(s.tensor,[zs.inputs[0].shape?zs.inputs[0].shape[1]:0,zs.inputs[0].shape?zs.inputs[0].shape[2]:0],!1),Q(s.tensor),o.norm=fe(o.resize,255),o.res=zs.predict(o.norm),o.squeeze=pt(o.res,0),o.squeeze.shape[2]===2?(o.softmax=$u(o.squeeze),[o.bg,o.fg]=as(o.softmax,2),o.expand=Kt(o.fg,2),o.pad=Kt(o.expand,0),o.crop=$e.cropAndResize(o.pad,[[0,0,.5,.5]],[0],[r,a]),o.data=pt(o.crop,0)):o.data=$e.resizeBilinear(o.squeeze,[a,r]);let i=Array.from(await o.data.data());if(ye.node&&!ye.Canvas&&typeof ImageData=="undefined")return n.debug&&ae("canvas support missing"),Object.keys(o).forEach(A=>Q(o[A])),{data:i,canvas:null,alpha:null};let l=Kn(r,a);await Gs.toPixels(o.data,l);let c=l.getContext("2d");n.segmentation.blur&&n.segmentation.blur>0&&(c.filter=`blur(${n.segmentation.blur}px)`);let u=c.getImageData(0,0,r,a),d=Kn(r,a),p=d.getContext("2d");s.canvas&&p.drawImage(s.canvas,0,0),p.globalCompositeOperation="darken",n.segmentation.blur&&n.segmentation.blur>0&&(p.filter=`blur(${n.segmentation.blur}px)`),p.drawImage(l,0,0),p.globalCompositeOperation="source-over",p.filter="none";let h=p.getImageData(0,0,r,a);for(let A=0;AQ(o[A])),Rb=!1,{data:i,canvas:f||d,alpha:l}}var l0=class{constructor(){de(this,"age",null);de(this,"agegenderrace",null);de(this,"blazeposedetect",null);de(this,"blazepose",null);de(this,"centernet",null);de(this,"efficientpose",null);de(this,"embedding",null);de(this,"emotion",null);de(this,"facedetect",null);de(this,"faceiris",null);de(this,"facemesh",null);de(this,"faceres",null);de(this,"gender",null);de(this,"handpose",null);de(this,"handskeleton",null);de(this,"handtrack",null);de(this,"movenet",null);de(this,"nanodet",null);de(this,"posenet",null);de(this,"segmentation",null);de(this,"antispoof",null)}};function Db(e){for(let t of Object.keys(e.models))e.models[t]=null}async function aT(e){var t,n,s,r,a,o,i,l,c,u,d,p,h,f,m,g,A,y,x,b,w,k,S,E,$,F,R,P,T,M,U;ye.initial&&Db(e),e.config.hand.enabled&&(!e.models.handpose&&((n=(t=e.config.hand.detector)==null?void 0:t.modelPath)==null?void 0:n.includes("handdetect"))&&([e.models.handpose,e.models.handskeleton]=await cb(e.config)),!e.models.handskeleton&&e.config.hand.landmarks&&((r=(s=e.config.hand.detector)==null?void 0:s.modelPath)==null?void 0:r.includes("handdetect"))&&([e.models.handpose,e.models.handskeleton]=await cb(e.config))),e.config.face.enabled&&!e.models.facedetect&&(e.models.facedetect=H6(e.config)),e.config.face.enabled&&((a=e.config.face.mesh)==null?void 0:a.enabled)&&!e.models.facemesh&&(e.models.facemesh=p8(e.config)),e.config.face.enabled&&((o=e.config.face.iris)==null?void 0:o.enabled)&&!e.models.faceiris&&(e.models.faceiris=r8(e.config)),e.config.face.enabled&&((i=e.config.face.antispoof)==null?void 0:i.enabled)&&!e.models.antispoof&&(e.models.antispoof=F6(e.config)),e.config.hand.enabled&&!e.models.handtrack&&((c=(l=e.config.hand.detector)==null?void 0:l.modelPath)==null?void 0:c.includes("handtrack"))&&(e.models.handtrack=V8(e.config)),e.config.hand.enabled&&e.config.hand.landmarks&&!e.models.handskeleton&&((d=(u=e.config.hand.detector)==null?void 0:u.modelPath)==null?void 0:d.includes("handtrack"))&&(e.models.handskeleton=U8(e.config)),e.config.body.enabled&&!e.models.posenet&&((h=(p=e.config.body)==null?void 0:p.modelPath)==null?void 0:h.includes("posenet"))&&(e.models.posenet=sT(e.config)),e.config.body.enabled&&!e.models.efficientpose&&((m=(f=e.config.body)==null?void 0:f.modelPath)==null?void 0:m.includes("efficientpose"))&&(e.models.efficientpose=Xx(e.config)),e.config.body.enabled&&!e.models.blazepose&&((A=(g=e.config.body)==null?void 0:g.modelPath)==null?void 0:A.includes("blazepose"))&&(e.models.blazepose=Z6(e.config)),e.config.body.enabled&&!e.models.blazeposedetect&&((y=e.config.body.detector)==null?void 0:y.modelPath)&&((b=(x=e.config.body)==null?void 0:x.modelPath)==null?void 0:b.includes("blazepose"))&&(e.models.blazeposedetect=K6(e.config)),e.config.body.enabled&&!e.models.efficientpose&&((k=(w=e.config.body)==null?void 0:w.modelPath)==null?void 0:k.includes("efficientpose"))&&(e.models.efficientpose=Xx(e.config)),e.config.body.enabled&&!e.models.movenet&&((E=(S=e.config.body)==null?void 0:S.modelPath)==null?void 0:E.includes("movenet"))&&(e.models.movenet=X8(e.config)),e.config.object.enabled&&!e.models.nanodet&&((F=($=e.config.object)==null?void 0:$.modelPath)==null?void 0:F.includes("nanodet"))&&(e.models.nanodet=Z8(e.config)),e.config.object.enabled&&!e.models.centernet&&((P=(R=e.config.object)==null?void 0:R.modelPath)==null?void 0:P.includes("centernet"))&&(e.models.centernet=Q6(e.config)),e.config.face.enabled&&((T=e.config.face.emotion)==null?void 0:T.enabled)&&!e.models.emotion&&(e.models.emotion=s8(e.config)),e.config.face.enabled&&((M=e.config.face.description)==null?void 0:M.enabled)&&!e.models.faceres&&(e.models.faceres=A8(e.config)),e.config.segmentation.enabled&&!e.models.segmentation&&(e.models.segmentation=$b(e.config)),e.config.face.enabled&&((U=e.config.face.agegenderrace)==null?void 0:U.enabled)&&!e.models.agegenderrace&&(e.models.agegenderrace=D6(e.config));for await(let H of Object.keys(e.models))e.models[H]&&typeof e.models[H]!="undefined"&&(e.models[H]=await e.models[H])}async function oT(e){let t=["const","placeholder","noop","pad","squeeze","add","sub","mul","div"];for(let n of Object.keys(e.models))if(e.models[n]){let s=[];Array.isArray(e.models[n])?s=e.models[n].filter(r=>r!==null).map(r=>r&&r.executor?r:r.model):s=[e.models[n]];for(let r of s){if(!r){e.config.debug&&ae("model marked as loaded but not defined:",n);continue}let a=[],o=r==null?void 0:r.executor;if(o&&o.graph.nodes)for(let l of Object.values(o.graph.nodes)){let c=l.op.toLowerCase();a.includes(c)||a.push(c)}else!o&&e.config.debug&&ae("model signature not determined:",n);let i=[];for(let l of a)!t.includes(l)&&!e.env.kernels.includes(l)&&!e.env.kernels.includes(l.replace("_",""))&&!e.env.kernels.includes(l.replace("native",""))&&!e.env.kernels.includes(l.replace("v2",""))&&i.push(l);i.length>0&&e.config.debug&&ae("model validation:",n,i)}}}var zt={name:"humangl",priority:999,canvas:null,gl:null,extensions:[],webGLattr:{alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!1,desynchronized:!0}};function Vge(){let e=zt.gl;!e||(zt.extensions=e.getSupportedExtensions())}async function iT(e){var t;if(e.config.backend==="humangl"&&(zt.name in ss().registry&&(!zt.gl||!zt.gl.getParameter(zt.gl.VERSION))&&(ae("error: humangl backend invalid context"),Db(e)),!S2(zt.name))){try{zt.canvas=await Kn(100,100)}catch(s){ae("error: cannot create canvas:",s);return}try{zt.gl=(t=zt.canvas)==null?void 0:t.getContext("webgl2",zt.webGLattr),zt.canvas&&(zt.canvas.addEventListener("webglcontextlost",async s=>{throw ae("error: humangl:",s.type),ae("possible browser memory leak using webgl or conflict with multiple backend registrations"),e.emit("error"),new Error("browser webgl error")}),zt.canvas.addEventListener("webglcontextrestored",s=>{ae("error: humangl context restored:",s)}),zt.canvas.addEventListener("webglcontextcreationerror",s=>{ae("error: humangl context create:",s)}))}catch(s){ae("error: cannot get WebGL context:",s);return}try{pm(2,zt.gl)}catch(s){ae("error: cannot set WebGL context:",s);return}try{let s=new vm(zt.gl);Ki(zt.name,()=>new Kd(s),zt.priority)}catch(s){ae("error: cannot register WebGL backend:",s);return}try{Xr("webgl").forEach(r=>{let a={...r,backendName:zt.name};Kr(a)})}catch(s){ae("error: cannot update WebGL backend registration:",s);return}let n=Tr().getGPGPUContext?Tr().getGPGPUContext().gl:null;if(n)ae(`humangl webgl version:${n.getParameter(n.VERSION)} renderer:${n.getParameter(n.RENDERER)}`);else{ae("error: no current gl context:",n,zt.gl);return}try{Ir.set("WEBGL_VERSION",2)}catch(s){ae("error: cannot set WebGL backend flags:",s);return}Vge(),ae("backend registered:",zt.name)}}async function u0(e,t=!1){if(e.state="backend",t||ye.initial||e.config.backend&&e.config.backend.length>0&&ir()!==e.config.backend){let n=pe();if(e.config.backend&&e.config.backend.length>0){if(typeof window=="undefined"&&typeof WorkerGlobalScope!="undefined"&&e.config.debug&&e.config.debug&&ae("running inside web worker"),ye.browser&&e.config.backend==="tensorflow"&&(e.config.debug&&ae("override: backend set to tensorflow while running in browser"),e.config.backend="humangl"),ye.node&&(e.config.backend==="webgl"||e.config.backend==="humangl")&&(e.config.debug&&ae(`override: backend set to ${e.config.backend} while running in nodejs`),e.config.backend="tensorflow"),ye.browser&&e.config.backend==="webgpu")if(typeof navigator=="undefined"||typeof navigator.gpu=="undefined")ae("override: backend set to webgpu but browser does not support webgpu"),e.config.backend="humangl";else{let r=await navigator.gpu.requestAdapter();e.config.debug&&ae("enumerated webgpu adapter:",r)}e.config.backend==="humangl"&&await iT(e);let s=Object.keys(ss().registryFactory);if(e.config.debug&&ae("available backends:",s),s.includes(e.config.backend)||(ae(`error: backend ${e.config.backend} not found in registry`),e.config.backend=ye.node?"tensorflow":"webgl",e.config.debug&&ae(`override: setting backend ${e.config.backend}`)),e.config.debug&&ae("setting backend:",e.config.backend),e.config.backend==="wasm"){if(e.config.debug&&ae("wasm path:",e.config.wasmPath),typeof(wl==null?void 0:wl.setWasmPaths)!="undefined")await b6(e.config.wasmPath);else throw new Error("wasm backend is not loaded");let r=await K().getAsync("WASM_HAS_SIMD_SUPPORT"),a=await K().getAsync("WASM_HAS_MULTITHREAD_SUPPORT");e.config.debug&&ae(`wasm execution: ${r?"SIMD":"no SIMD"} ${a?"multithreaded":"singlethreaded"}`),e.config.debug&&!r&&ae("warning: wasm simd support is not enabled")}try{await g3(e.config.backend),await Wh()}catch(r){return ae("error: cannot set backend:",e.config.backend,r),!1}}if(ir()==="humangl"&&(Ir.set("CHECK_COMPUTATION_FOR_ERRORS",!1),Ir.set("WEBGL_CPU_FORWARD",!0),Ir.set("WEBGL_USE_SHAPES_UNIFORMS",!0),Ir.set("CPU_HANDOFF_SIZE_THRESHOLD",256),typeof e.config.deallocate!="undefined"&&e.config.deallocate&&(ae("changing webgl: WEBGL_DELETE_TEXTURE_THRESHOLD:",!0),Ir.set("WEBGL_DELETE_TEXTURE_THRESHOLD",0)),Tr().getGPGPUContext)){let s=await Tr().getGPGPUContext().gl;e.config.debug&&ae(`gl version:${s.getParameter(s.VERSION)} renderer:${s.getParameter(s.RENDERER)}`)}ir()==="webgpu",m3(),await Wh(),e.performance.backend=Math.trunc(pe()-n),e.config.backend=ir(),ye.updateBackend()}return!0}function dc(e,t){for(let n of e){let s={kernelName:n,backendName:t.backend,kernelFunc:()=>{t.debug&&ae("kernelFunc",n,t.backend)}};Kr(s)}ye.kernels=Xr(ir()).map(n=>n.kernelName.toLowerCase())}var da={color:"rgba(173, 216, 230, 0.6)",labelColor:"rgba(173, 216, 230, 1)",shadowColor:"black",font:'small-caps 14px "Segoe UI"',lineHeight:18,lineWidth:4,pointSize:2,roundRect:8,drawPoints:!1,drawLabels:!0,drawBoxes:!0,drawGestures:!0,drawPolygons:!0,drawGaze:!0,fillPolygons:!1,useDepth:!0,useCurves:!1,bufferedOutput:!0},El=e=>{if(e&&e.getContext)return e.getContext("2d");throw new Error("invalid canvas")},mc=e=>Math.round(e*180/Math.PI);function _b(e,t,n,s=0,r){e.fillStyle=r.useDepth&&s?`rgba(${127.5+2*s}, ${127.5-2*s}, 255, 0.3)`:r.color,e.beginPath(),e.arc(t,n,r.pointSize,0,2*Math.PI),e.fill()}function xp(e,t,n,s,r,a){if(e.beginPath(),a.useCurves){let o=(t+t+s)/2,i=(n+n+r)/2;e.ellipse(o,i,s/2,r/2,0,0,2*Math.PI)}else e.lineWidth=a.lineWidth,e.moveTo(t+a.roundRect,n),e.lineTo(t+s-a.roundRect,n),e.quadraticCurveTo(t+s,n,t+s,n+a.roundRect),e.lineTo(t+s,n+r-a.roundRect),e.quadraticCurveTo(t+s,n+r,t+s-a.roundRect,n+r),e.lineTo(t+a.roundRect,n+r),e.quadraticCurveTo(t,n+r,t,n+r-a.roundRect),e.lineTo(t,n+a.roundRect),e.quadraticCurveTo(t,n,t+a.roundRect,n),e.closePath();e.stroke()}function lT(e,t=[],n){if(!(t===void 0||t.length===0)){e.beginPath(),e.moveTo(t[0][0],t[0][1]);for(let s of t){let r=s[2]||0;e.strokeStyle=n.useDepth&&r?`rgba(${127.5+2*r}, ${127.5-2*r}, 255, 0.3)`:n.color,e.fillStyle=n.useDepth&&r?`rgba(${127.5+2*r}, ${127.5-2*r}, 255, 0.3)`:n.color,e.lineTo(s[0],Math.round(s[1]))}e.stroke(),n.fillPolygons&&(e.closePath(),e.fill())}}function Uge(e,t=[],n){if(!(t===void 0||t.length===0)){if(!n.useCurves||t.length<=2){lT(e,t,n);return}e.moveTo(t[0][0],t[0][1]);for(let s=0;s1&&l[1].length>0){let c=i[1]>0?`#${i[1]}`:"",u=`${i[0]} ${c}: ${l[1]}`;s.shadowColor&&s.shadowColor!==""&&(r.fillStyle=s.shadowColor,r.fillText(u,8,2+a*s.lineHeight)),r.fillStyle=s.labelColor,r.fillText(u,6,0+a*s.lineHeight),a+=1}}}}async function Fb(e,t,n){var a,o,i,l,c;let s=$n(da,n);if(!t||!e)return;let r=El(e);for(let u of t){if(r.font=s.font,r.strokeStyle=s.color,r.fillStyle=s.color,s.drawBoxes&&xp(r,u.box[0],u.box[1],u.box[2],u.box[3],s),s.drawLabels){let d=[];if(d.push(`face: ${Math.trunc(100*u.score)}%`),u.genderScore&&d.push(`${u.gender||""} ${Math.trunc(100*u.genderScore)}%`),u.age&&d.push(`age: ${u.age||""}`),u.iris&&d.push(`distance: ${u.iris}`),u.real&&d.push(`real: ${Math.trunc(100*u.real)}%`),u.emotion&&u.emotion.length>0){let p=u.emotion.map(h=>`${Math.trunc(100*h.score)}% ${h.emotion}`);p.length>3&&(p.length=3),d.push(p.join(" "))}u.rotation&&u.rotation.angle&&u.rotation.gaze&&(u.rotation.angle.roll&&d.push(`roll: ${mc(u.rotation.angle.roll)}\xB0 yaw:${mc(u.rotation.angle.yaw)}\xB0 pitch:${mc(u.rotation.angle.pitch)}\xB0`),u.rotation.gaze.bearing&&d.push(`gaze: ${mc(u.rotation.gaze.bearing)}\xB0`)),d.length===0&&d.push("face"),r.fillStyle=s.color;for(let p=d.length-1;p>=0;p--){let h=Math.max(u.box[0],0),f=p*s.lineHeight+u.box[1];s.shadowColor&&s.shadowColor!==""&&(r.fillStyle=s.shadowColor,r.fillText(d[p],h+5,f+16)),r.fillStyle=s.labelColor,r.fillText(d[p],h+4,f+15)}}if(r.lineWidth=1,u.mesh&&u.mesh.length>0){if(s.drawPoints)for(let d of u.mesh)_b(r,d[0],d[1],d[2],s);if(s.drawPolygons){if(r.lineWidth=1,u.mesh.length>450)for(let d=0;du.mesh[h]);lT(r,p,s)}if(u.annotations&&u.annotations.leftEyeIris&&u.annotations.leftEyeIris[0]){r.strokeStyle=s.useDepth?"rgba(255, 200, 255, 0.3)":s.color,r.beginPath();let d=Math.abs(u.annotations.leftEyeIris[3][0]-u.annotations.leftEyeIris[1][0])/2,p=Math.abs(u.annotations.leftEyeIris[4][1]-u.annotations.leftEyeIris[2][1])/2;r.ellipse(u.annotations.leftEyeIris[0][0],u.annotations.leftEyeIris[0][1],d,p,0,0,2*Math.PI),r.stroke(),s.fillPolygons&&(r.fillStyle=s.useDepth?"rgba(255, 255, 200, 0.3)":s.color,r.fill())}if(u.annotations&&u.annotations.rightEyeIris&&u.annotations.rightEyeIris[0]){r.strokeStyle=s.useDepth?"rgba(255, 200, 255, 0.3)":s.color,r.beginPath();let d=Math.abs(u.annotations.rightEyeIris[3][0]-u.annotations.rightEyeIris[1][0])/2,p=Math.abs(u.annotations.rightEyeIris[4][1]-u.annotations.rightEyeIris[2][1])/2;r.ellipse(u.annotations.rightEyeIris[0][0],u.annotations.rightEyeIris[0][1],d,p,0,0,2*Math.PI),r.stroke(),s.fillPolygons&&(r.fillStyle=s.useDepth?"rgba(255, 255, 200, 0.3)":s.color,r.fill())}if(s.drawGaze&&((a=u.rotation)==null?void 0:a.angle)){r.strokeStyle="pink";let d=u.box[0]+u.box[2]/2-u.box[3]*mc(u.rotation.angle.yaw)/90,p=u.box[1]+u.box[3]/2+u.box[2]*mc(u.rotation.angle.pitch)/90,h=new Path2D(` M ${u.box[0]+u.box[2]/2} ${u.box[1]} C ${d} ${u.box[1]}, @@ -7090,7 +7090,7 @@ return a / b;`,lre=` ${u.box[0]} ${p}, ${u.box[0]+u.box[2]} ${p}, ${u.box[0]+u.box[2]} ${u.box[1]+u.box[3]/2} - `);r.stroke(f),r.stroke(h)}if(s.drawGaze&&((i=(o=u.rotation)==null?void 0:o.gaze)==null?void 0:i.strength)&&((c=(l=u.rotation)==null?void 0:l.gaze)==null?void 0:c.bearing)&&u.annotations.leftEyeIris&&u.annotations.rightEyeIris&&u.annotations.leftEyeIris[0]&&u.annotations.rightEyeIris[0]){r.strokeStyle="pink",r.fillStyle="pink";let d=[u.annotations.leftEyeIris[0][0]+Math.sin(u.rotation.gaze.bearing)*u.rotation.gaze.strength*u.box[3],u.annotations.leftEyeIris[0][1]+Math.cos(u.rotation.gaze.bearing)*u.rotation.gaze.strength*u.box[2]];uT(r,[u.annotations.leftEyeIris[0][0],u.annotations.leftEyeIris[0][1]],[d[0],d[1]],4);let p=[u.annotations.rightEyeIris[0][0]+Math.sin(u.rotation.gaze.bearing)*u.rotation.gaze.strength*u.box[3],u.annotations.rightEyeIris[0][1]+Math.cos(u.rotation.gaze.bearing)*u.rotation.gaze.strength*u.box[2]];uT(r,[u.annotations.rightEyeIris[0][0],u.annotations.rightEyeIris[0][1]],[p[0],p[1]],4)}}}}}async function Ob(e,t,n){var a;let s=$n(da,n);if(!t||!e)return;let r=El(e);r.lineJoin="round";for(let o=0;o0)for(let o of a.keypoints)r.fillStyle=s.useDepth?`rgba(${127.5+2*(o[2]||0)}, ${127.5-2*(o[2]||0)}, 255, 0.5)`:s.color,_b(r,o[0],o[1],0,s);if(s.drawLabels&&a.annotations){let o=(i,l)=>{!i||i.length===0||!i[0]||(r.fillStyle=s.useDepth?`rgba(${127.5+2*i[i.length-1][2]}, ${127.5-2*i[i.length-1][2]}, 255, 0.5)`:s.color,r.fillText(l,i[i.length-1][0]+4,i[i.length-1][1]+4))};r.font=s.font,o(a.annotations.index,"index"),o(a.annotations.middle,"middle"),o(a.annotations.ring,"ring"),o(a.annotations.pinky,"pinky"),o(a.annotations.thumb,"thumb"),o(a.annotations.palm,"palm")}if(s.drawPolygons&&a.annotations){let o=i=>{if(!(!i||i.length===0||!i[0]))for(let l=0;l0?l-1:0][0],i[l>0?l-1:0][1]),r.lineTo(i[l][0],i[l][1]),r.stroke()};r.lineWidth=s.lineWidth,o(a.annotations.index),o(a.annotations.middle),o(a.annotations.ring),o(a.annotations.pinky),o(a.annotations.thumb)}}}async function zb(e,t,n){let s=$n(da,n);if(!t||!e)return;let r=El(e);r.lineJoin="round",r.font=s.font;for(let a of t)if(s.drawBoxes){if(r.strokeStyle=s.color,r.fillStyle=s.color,xp(r,a.box[0],a.box[1],a.box[2],a.box[3],s),s.drawLabels){let o=`${a.label} ${Math.round(100*a.score)}%`;s.shadowColor&&s.shadowColor!==""&&(r.fillStyle=s.shadowColor,r.fillText(o,a.box[0]+3,1+a.box[1]+s.lineHeight,a.box[2])),r.fillStyle=s.labelColor,r.fillText(o,a.box[0]+2,0+a.box[1]+s.lineHeight,a.box[2])}r.stroke()}}async function cT(e,t,n){let s=$n(da,n);if(!t||!e)return;let r=El(e);r.lineJoin="round",r.font=s.font;for(let a=0;a{let t=(d,p)=>Math.atan2(d[1]-p[1],d[0]-p[0]);if(!e.annotations.rightEyeIris||!e.annotations.leftEyeIris)return{bearing:0,strength:0};let n=[0,-.1],s=1,r=e.mesh[33][2]>e.mesh[263][2],a=r?e.mesh[473]:e.mesh[468],o=r?[(e.mesh[133][0]+e.mesh[33][0])/2,(e.mesh[133][1]+e.mesh[33][1])/2]:[(e.mesh[263][0]+e.mesh[362][0])/2,(e.mesh[263][1]+e.mesh[362][1])/2],i=r?[e.mesh[133][0]-e.mesh[33][0],e.mesh[23][1]-e.mesh[27][1]]:[e.mesh[263][0]-e.mesh[362][0],e.mesh[253][1]-e.mesh[257][1]],l=[(o[0]-a[0])/i[0]-n[0],s*(a[1]-o[1])/i[1]-n[1]],c=Math.sqrt(l[0]**2+l[1]**2);return c=Math.min(c,e.boxRaw[2]/2,e.boxRaw[3]/2),{bearing:(t([0,0],l)+Math.PI/2)%Math.PI,strength:c}},hT=(e,t)=>{let n=g=>{let A=Math.sqrt(g[0]*g[0]+g[1]*g[1]+g[2]*g[2]);return g[0]/=A,g[1]/=A,g[2]/=A,g},s=(g,A)=>{let y=g[0]-A[0],x=g[1]-A[1],b=g[2]-A[2];return[y,x,b]},r=(g,A)=>{let y=g[1]*A[2]-g[2]*A[1],x=g[2]*A[0]-g[0]*A[2],b=g[0]*A[1]-g[1]*A[0];return[y,x,b]},a=g=>{let[A,y,x,b,w,k,S,E,P]=g,F,R,_;return b<1?b>-1?(_=Math.asin(b),R=Math.atan2(-S,A),F=Math.atan2(-k,w)):(_=-Math.PI/2,R=-Math.atan2(E,P),F=0):(_=Math.PI/2,R=Math.atan2(E,P),F=0),isNaN(F)&&(F=0),isNaN(R)&&(R=0),isNaN(_)&&(_=0),{pitch:2*-F,yaw:2*-R,roll:2*-_}},o=g=>{let A=(x,b,w,k)=>Math.atan2(k-b,w-x);return{pitch:A(g[10][1],g[10][2],g[152][1],g[152][2]),yaw:A(g[33][0],g[33][2],g[263][0],g[263][2]),roll:A(g[33][0],g[33][1],g[263][0],g[263][1])}},i=e.meshRaw;if(!i||i.length<300)return{angle:{pitch:0,yaw:0,roll:0},matrix:[1,0,0,0,1,0,0,0,1],gaze:{bearing:0,strength:0}};let l=Math.max(e.boxRaw[2]*t[0],e.boxRaw[3]*t[1])/1.5,c=[i[10],i[152],i[234],i[454]].map(g=>[g[0]*t[0]/l,g[1]*t[1]/l,g[2]]),u=n(s(c[1],c[0])),d=n(s(c[3],c[2])),p=n(r(d,u));d=r(u,p);let h=[d[0],d[1],d[2],u[0],u[1],u[2],p[0],p[1],p[2]],f=a(h),m=i.length===478?Gge(e):{bearing:0,strength:0};return{angle:f,matrix:h,gaze:m}};var Lb=async(e,t)=>{var p,h,f,m;let n,s,r,a,o,i,l,c,u=[];e.state="run:face",n=Ae();let d=await d8(t,e.config);if(e.performance.face=Math.trunc(Ae()-n),!t.shape||t.shape.length!==4)return[];if(!d)return[];for(let g=0;g0&&d[g].annotations.rightEyeIris.length>0&&d[g].annotations.leftEyeIris[0]!==null&&d[g].annotations.rightEyeIris[0]!==null?Math.max(Math.abs(d[g].annotations.leftEyeIris[3][0]-d[g].annotations.leftEyeIris[1][0]),Math.abs(d[g].annotations.rightEyeIris[4][1]-d[g].annotations.rightEyeIris[2][1]))/t.shape[2]:0,x=e.config.face.detector.return?pt(d[g].tensor):null;Q(d[g].tensor),d[g].tensor&&delete d[g].tensor,u.push({...d[g],id:g,age:c==null?void 0:c.age,gender:c==null?void 0:c.gender,genderScore:c==null?void 0:c.genderScore,embedding:c==null?void 0:c.descriptor,emotion:o,real:l,iris:y!==0?Math.trunc(500/y/11.7)/100:0,rotation:A,tensor:x}),e.analyze("End Face")}return e.analyze("End FaceMesh:"),e.config.async&&(e.performance.face&&delete e.performance.face,e.performance.age&&delete e.performance.age,e.performance.gender&&delete e.performance.gender,e.performance.emotion&&delete e.performance.emotion),u};var fT=e=>{if(!e)return[];let t=[];for(let n=0;nl.part==="leftWrist"),r=e[n].keypoints.find(l=>l.part==="rightWrist"),a=e[n].keypoints.find(l=>l.part==="nose");a&&s&&r&&s.position[1]l.part==="leftShoulder"),i=e[n].keypoints.find(l=>l.part==="rightShoulder");o&&i&&t.push({body:n,gesture:`leaning ${o.position[1]>i.position[1]?"left":"right"}`})}return t},mT=e=>{if(!e)return[];let t=[];for(let n=0;n450){let s=e[n].mesh[33][2]-e[n].mesh[263][2];Math.abs(s)<10?t.push({face:n,gesture:"facing center"}):t.push({face:n,gesture:`facing ${s<0?"left":"right"}`}),Math.abs(e[n].mesh[374][1]-e[n].mesh[386][1])/Math.abs(e[n].mesh[443][1]-e[n].mesh[450][1])<.2&&t.push({face:n,gesture:"blink left eye"}),Math.abs(e[n].mesh[145][1]-e[n].mesh[159][1])/Math.abs(e[n].mesh[223][1]-e[n].mesh[230][1])<.2&&t.push({face:n,gesture:"blink right eye"});let o=Math.min(100,500*Math.abs(e[n].mesh[13][1]-e[n].mesh[14][1])/Math.abs(e[n].mesh[10][1]-e[n].mesh[152][1]));o>10&&t.push({face:n,gesture:`mouth ${Math.trunc(o)}% open`});let i=e[n].mesh[152][2];Math.abs(i)>10&&t.push({face:n,gesture:`head ${i<0?"up":"down"}`})}return t},gT=e=>{if(!e)return[];let t=[];for(let n=0;n.06||d>.06)&&(c=!1),p>.06&&t.push({iris:n,gesture:"looking right"}),d>.06&&t.push({iris:n,gesture:"looking left"});let h=Math.abs(e[n].mesh[145][1]-e[n].annotations.rightEyeIris[0][1])/e[n].box[3],f=Math.abs(e[n].mesh[374][1]-e[n].annotations.leftEyeIris[0][1])/e[n].box[3];(f<.01||h<.01||f>.022||h>.022)&&(c=!1),(f<.01||h<.01)&&t.push({iris:n,gesture:"looking down"}),(f>.022||h>.022)&&t.push({iris:n,gesture:"looking up"}),c&&t.push({iris:n,gesture:"looking center"})}return t},AT=e=>{if(!e)return[];let t=[];for(let n=0;n0){let r=s.reduce((o,i)=>o.position[2]o.position[1]((r-1)*Pe.body[z].box[te]+J)/r),ee=e.body[z].boxRaw.map((J,te)=>((r-1)*Pe.body[z].boxRaw[te]+J)/r),Y=e.body[z].keypoints.map((J,te)=>({score:J.score,part:J.part,position:[Pe.body[z].keypoints[te]?((r-1)*Pe.body[z].keypoints[te].position[0]+J.position[0])/r:J.position[0],Pe.body[z].keypoints[te]?((r-1)*Pe.body[z].keypoints[te].position[1]+J.position[1])/r:J.position[1]],positionRaw:[Pe.body[z].keypoints[te]?((r-1)*Pe.body[z].keypoints[te].positionRaw[0]+J.positionRaw[0])/r:J.position[0],Pe.body[z].keypoints[te]?((r-1)*Pe.body[z].keypoints[te].positionRaw[1]+J.positionRaw[1])/r:J.position[1]]})),se={},ne={connected:{}};((i=(o=t.body)==null?void 0:o.modelPath)==null?void 0:i.includes("efficientpose"))?ne=jx:((c=(l=t.body)==null?void 0:l.modelPath)==null?void 0:c.includes("blazepose"))?ne=zx:((d=(u=t.body)==null?void 0:u.modelPath)==null?void 0:d.includes("movenet"))&&(ne=yb);for(let[J,te]of Object.entries(ne.connected)){let ue=[];for(let ce=0;ceCe.part===te[ce]),we=Y.find(Ce=>Ce.part===te[ce+1]);xe&&we&&xe.score>(t.body.minConfidence||0)&&we.score>(t.body.minConfidence||0)&&ue.push([xe.position,we.position])}se[J]=ue}Pe.body[z]={...e.body[z],box:X,boxRaw:ee,keypoints:Y,annotations:se}}if(!Pe.hand||e.hand.length!==Pe.hand.length)Pe.hand=JSON.parse(JSON.stringify(e.hand));else for(let z=0;z((r-1)*Pe.hand[z].box[J]+ne)/r),ee=e.hand[z].boxRaw.map((ne,J)=>((r-1)*Pe.hand[z].boxRaw[J]+ne)/r);Pe.hand[z].keypoints.length!==e.hand[z].keypoints.length&&(Pe.hand[z].keypoints=e.hand[z].keypoints);let Y=e.hand[z].keypoints&&e.hand[z].keypoints.length>0?e.hand[z].keypoints.map((ne,J)=>ne.map((te,ue)=>((r-1)*(Pe.hand[z].keypoints[J][ue]||1)+(te||0))/r)):[],se={};if(Object.keys(Pe.hand[z].annotations).length!==Object.keys(e.hand[z].annotations).length)Pe.hand[z].annotations=e.hand[z].annotations,se=Pe.hand[z].annotations;else if(e.hand[z].annotations)for(let ne of Object.keys(e.hand[z].annotations))se[ne]=e.hand[z].annotations[ne]&&e.hand[z].annotations[ne][0]?e.hand[z].annotations[ne].map((J,te)=>J.map((ue,ce)=>((r-1)*Pe.hand[z].annotations[ne][te][ce]+ue)/r)):null;Pe.hand[z]={...e.hand[z],box:X,boxRaw:ee,keypoints:Y,annotations:se}}if(!Pe.face||e.face.length!==Pe.face.length)Pe.face=JSON.parse(JSON.stringify(e.face));else for(let z=0;z((r-1)*Pe.face[z].box[ne]+se)/r),ee=e.face[z].boxRaw.map((se,ne)=>((r-1)*Pe.face[z].boxRaw[ne]+se)/r),Y={matrix:[0,0,0,0,0,0,0,0,0],angle:{roll:0,yaw:0,pitch:0},gaze:{bearing:0,strength:0}};Y.matrix=(p=e.face[z].rotation)==null?void 0:p.matrix,Y.angle={roll:((r-1)*(((f=(h=Pe.face[z].rotation)==null?void 0:h.angle)==null?void 0:f.roll)||0)+(((g=(m=e.face[z].rotation)==null?void 0:m.angle)==null?void 0:g.roll)||0))/r,yaw:((r-1)*(((y=(A=Pe.face[z].rotation)==null?void 0:A.angle)==null?void 0:y.yaw)||0)+(((b=(x=e.face[z].rotation)==null?void 0:x.angle)==null?void 0:b.yaw)||0))/r,pitch:((r-1)*(((k=(w=Pe.face[z].rotation)==null?void 0:w.angle)==null?void 0:k.pitch)||0)+(((E=(S=e.face[z].rotation)==null?void 0:S.angle)==null?void 0:E.pitch)||0))/r},Y.gaze={bearing:((r-1)*(((F=(P=Pe.face[z].rotation)==null?void 0:P.gaze)==null?void 0:F.bearing)||0)+(((_=(R=e.face[z].rotation)==null?void 0:R.gaze)==null?void 0:_.bearing)||0))/r,strength:((r-1)*(((M=(T=Pe.face[z].rotation)==null?void 0:T.gaze)==null?void 0:M.strength)||0)+(((H=(U=e.face[z].rotation)==null?void 0:U.gaze)==null?void 0:H.strength)||0))/r},Pe.face[z]={...e.face[z],rotation:Y,box:X,boxRaw:ee}}if(!Pe.object||e.object.length!==Pe.object.length)Pe.object=JSON.parse(JSON.stringify(e.object));else for(let z=0;z((r-1)*Pe.object[z].box[se]+Y)/r),ee=e.object[z].boxRaw.map((Y,se)=>((r-1)*Pe.object[z].boxRaw[se]+Y)/r);Pe.object[z]={...e.object[z],box:X,boxRaw:ee}}if(e.persons){let z=e.persons;if(!Pe.persons||z.length!==Pe.persons.length)Pe.persons=JSON.parse(JSON.stringify(z));else for(let X=0;X((r-1)*Pe.persons[X].box[Y]+ee)/r)}e.gesture&&(Pe.gesture=e.gesture);let a=Ae();return e.performance&&(Pe.performance={...e.performance,interpolate:Math.round(a-n)}),Pe}function c0(e,t,n={order:2}){let s=0;for(let r=0;rM.box[0]&&S.box[0]M.box[1]&&S.box[1]+S.box[3]E.body.box[0]&&M.box[0]+M.box[2]E.body.box[1]&&M.box[1]+M.box[3]E.body.box[0]&&M.box[1]+M.box[3]>E.body.box[1]&&M.box[1]+M.box[3]{M&&M.length===4&&(P.push(M[0],M[0]+M[2]),F.push(M[1],M[1]+M[3]))};R((A=E.face)==null?void 0:A.box),R((y=E.body)==null?void 0:y.box),R((b=(x=E.hands)==null?void 0:x.left)==null?void 0:b.box),R((k=(w=E.hands)==null?void 0:w.right)==null?void 0:k.box);let _=Math.min(...P),T=Math.min(...F);E.box=[_,T,Math.max(...P)-_,Math.max(...F)-T],r&&r[1]&&r[2]&&(E.boxRaw=[E.box[0]/r[2],E.box[1]/r[1],E.box[2]/r[2],E.box[3]/r[1]]),o.push(E)}return o}var d0=` + `);r.stroke(f),r.stroke(h)}if(s.drawGaze&&((i=(o=u.rotation)==null?void 0:o.gaze)==null?void 0:i.strength)&&((c=(l=u.rotation)==null?void 0:l.gaze)==null?void 0:c.bearing)&&u.annotations.leftEyeIris&&u.annotations.rightEyeIris&&u.annotations.leftEyeIris[0]&&u.annotations.rightEyeIris[0]){r.strokeStyle="pink",r.fillStyle="pink";let d=[u.annotations.leftEyeIris[0][0]+Math.sin(u.rotation.gaze.bearing)*u.rotation.gaze.strength*u.box[3],u.annotations.leftEyeIris[0][1]+Math.cos(u.rotation.gaze.bearing)*u.rotation.gaze.strength*u.box[2]];uT(r,[u.annotations.leftEyeIris[0][0],u.annotations.leftEyeIris[0][1]],[d[0],d[1]],4);let p=[u.annotations.rightEyeIris[0][0]+Math.sin(u.rotation.gaze.bearing)*u.rotation.gaze.strength*u.box[3],u.annotations.rightEyeIris[0][1]+Math.cos(u.rotation.gaze.bearing)*u.rotation.gaze.strength*u.box[2]];uT(r,[u.annotations.rightEyeIris[0][0],u.annotations.rightEyeIris[0][1]],[p[0],p[1]],4)}}}}}async function Ob(e,t,n){var a;let s=$n(da,n);if(!t||!e)return;let r=El(e);r.lineJoin="round";for(let o=0;o0)for(let o of a.keypoints)r.fillStyle=s.useDepth?`rgba(${127.5+2*(o[2]||0)}, ${127.5-2*(o[2]||0)}, 255, 0.5)`:s.color,_b(r,o[0],o[1],0,s);if(s.drawLabels&&a.annotations){let o=(i,l)=>{!i||i.length===0||!i[0]||(r.fillStyle=s.useDepth?`rgba(${127.5+2*i[i.length-1][2]}, ${127.5-2*i[i.length-1][2]}, 255, 0.5)`:s.color,r.fillText(l,i[i.length-1][0]+4,i[i.length-1][1]+4))};r.font=s.font,o(a.annotations.index,"index"),o(a.annotations.middle,"middle"),o(a.annotations.ring,"ring"),o(a.annotations.pinky,"pinky"),o(a.annotations.thumb,"thumb"),o(a.annotations.palm,"palm")}if(s.drawPolygons&&a.annotations){let o=i=>{if(!(!i||i.length===0||!i[0]))for(let l=0;l0?l-1:0][0],i[l>0?l-1:0][1]),r.lineTo(i[l][0],i[l][1]),r.stroke()};r.lineWidth=s.lineWidth,o(a.annotations.index),o(a.annotations.middle),o(a.annotations.ring),o(a.annotations.pinky),o(a.annotations.thumb)}}}async function zb(e,t,n){let s=$n(da,n);if(!t||!e)return;let r=El(e);r.lineJoin="round",r.font=s.font;for(let a of t)if(s.drawBoxes){if(r.strokeStyle=s.color,r.fillStyle=s.color,xp(r,a.box[0],a.box[1],a.box[2],a.box[3],s),s.drawLabels){let o=`${a.label} ${Math.round(100*a.score)}%`;s.shadowColor&&s.shadowColor!==""&&(r.fillStyle=s.shadowColor,r.fillText(o,a.box[0]+3,1+a.box[1]+s.lineHeight,a.box[2])),r.fillStyle=s.labelColor,r.fillText(o,a.box[0]+2,0+a.box[1]+s.lineHeight,a.box[2])}r.stroke()}}async function cT(e,t,n){let s=$n(da,n);if(!t||!e)return;let r=El(e);r.lineJoin="round",r.font=s.font;for(let a=0;a{let t=(d,p)=>Math.atan2(d[1]-p[1],d[0]-p[0]);if(!e.annotations.rightEyeIris||!e.annotations.leftEyeIris)return{bearing:0,strength:0};let n=[0,-.1],s=1,r=e.mesh[33][2]>e.mesh[263][2],a=r?e.mesh[473]:e.mesh[468],o=r?[(e.mesh[133][0]+e.mesh[33][0])/2,(e.mesh[133][1]+e.mesh[33][1])/2]:[(e.mesh[263][0]+e.mesh[362][0])/2,(e.mesh[263][1]+e.mesh[362][1])/2],i=r?[e.mesh[133][0]-e.mesh[33][0],e.mesh[23][1]-e.mesh[27][1]]:[e.mesh[263][0]-e.mesh[362][0],e.mesh[253][1]-e.mesh[257][1]],l=[(o[0]-a[0])/i[0]-n[0],s*(a[1]-o[1])/i[1]-n[1]],c=Math.sqrt(l[0]**2+l[1]**2);return c=Math.min(c,e.boxRaw[2]/2,e.boxRaw[3]/2),{bearing:(t([0,0],l)+Math.PI/2)%Math.PI,strength:c}},hT=(e,t)=>{let n=g=>{let A=Math.sqrt(g[0]*g[0]+g[1]*g[1]+g[2]*g[2]);return g[0]/=A,g[1]/=A,g[2]/=A,g},s=(g,A)=>{let y=g[0]-A[0],x=g[1]-A[1],b=g[2]-A[2];return[y,x,b]},r=(g,A)=>{let y=g[1]*A[2]-g[2]*A[1],x=g[2]*A[0]-g[0]*A[2],b=g[0]*A[1]-g[1]*A[0];return[y,x,b]},a=g=>{let[A,y,x,b,w,k,S,E,$]=g,F,R,P;return b<1?b>-1?(P=Math.asin(b),R=Math.atan2(-S,A),F=Math.atan2(-k,w)):(P=-Math.PI/2,R=-Math.atan2(E,$),F=0):(P=Math.PI/2,R=Math.atan2(E,$),F=0),isNaN(F)&&(F=0),isNaN(R)&&(R=0),isNaN(P)&&(P=0),{pitch:2*-F,yaw:2*-R,roll:2*-P}},o=g=>{let A=(x,b,w,k)=>Math.atan2(k-b,w-x);return{pitch:A(g[10][1],g[10][2],g[152][1],g[152][2]),yaw:A(g[33][0],g[33][2],g[263][0],g[263][2]),roll:A(g[33][0],g[33][1],g[263][0],g[263][1])}},i=e.meshRaw;if(!i||i.length<300)return{angle:{pitch:0,yaw:0,roll:0},matrix:[1,0,0,0,1,0,0,0,1],gaze:{bearing:0,strength:0}};let l=Math.max(e.boxRaw[2]*t[0],e.boxRaw[3]*t[1])/1.5,c=[i[10],i[152],i[234],i[454]].map(g=>[g[0]*t[0]/l,g[1]*t[1]/l,g[2]]),u=n(s(c[1],c[0])),d=n(s(c[3],c[2])),p=n(r(d,u));d=r(u,p);let h=[d[0],d[1],d[2],u[0],u[1],u[2],p[0],p[1],p[2]],f=a(h),m=i.length===478?Gge(e):{bearing:0,strength:0};return{angle:f,matrix:h,gaze:m}};var Lb=async(e,t)=>{var p,h,f,m;let n,s,r,a,o,i,l,c,u=[];e.state="run:face",n=pe();let d=await d8(t,e.config);if(e.performance.face=ye.perfadd?(e.performance.face||0)+Math.trunc(pe()-n):Math.trunc(pe()-n),!t.shape||t.shape.length!==4)return[];if(!d)return[];for(let g=0;g0&&d[g].annotations.rightEyeIris.length>0&&d[g].annotations.leftEyeIris[0]!==null&&d[g].annotations.rightEyeIris[0]!==null?Math.max(Math.abs(d[g].annotations.leftEyeIris[3][0]-d[g].annotations.leftEyeIris[1][0]),Math.abs(d[g].annotations.rightEyeIris[4][1]-d[g].annotations.rightEyeIris[2][1]))/t.shape[2]:0,x=e.config.face.detector.return?pt(d[g].tensor):null;Q(d[g].tensor),d[g].tensor&&delete d[g].tensor,u.push({...d[g],id:g,age:c==null?void 0:c.age,gender:c==null?void 0:c.gender,genderScore:c==null?void 0:c.genderScore,embedding:c==null?void 0:c.descriptor,emotion:o,real:l,iris:y!==0?Math.trunc(500/y/11.7)/100:0,rotation:A,tensor:x}),e.analyze("End Face")}return e.analyze("End FaceMesh:"),e.config.async&&(e.performance.face&&delete e.performance.face,e.performance.age&&delete e.performance.age,e.performance.gender&&delete e.performance.gender,e.performance.emotion&&delete e.performance.emotion),u};var fT=e=>{if(!e)return[];let t=[];for(let n=0;nl.part==="leftWrist"),r=e[n].keypoints.find(l=>l.part==="rightWrist"),a=e[n].keypoints.find(l=>l.part==="nose");a&&s&&r&&s.position[1]l.part==="leftShoulder"),i=e[n].keypoints.find(l=>l.part==="rightShoulder");o&&i&&t.push({body:n,gesture:`leaning ${o.position[1]>i.position[1]?"left":"right"}`})}return t},mT=e=>{if(!e)return[];let t=[];for(let n=0;n450){let s=e[n].mesh[33][2]-e[n].mesh[263][2];Math.abs(s)<10?t.push({face:n,gesture:"facing center"}):t.push({face:n,gesture:`facing ${s<0?"left":"right"}`}),Math.abs(e[n].mesh[374][1]-e[n].mesh[386][1])/Math.abs(e[n].mesh[443][1]-e[n].mesh[450][1])<.2&&t.push({face:n,gesture:"blink left eye"}),Math.abs(e[n].mesh[145][1]-e[n].mesh[159][1])/Math.abs(e[n].mesh[223][1]-e[n].mesh[230][1])<.2&&t.push({face:n,gesture:"blink right eye"});let o=Math.min(100,500*Math.abs(e[n].mesh[13][1]-e[n].mesh[14][1])/Math.abs(e[n].mesh[10][1]-e[n].mesh[152][1]));o>10&&t.push({face:n,gesture:`mouth ${Math.trunc(o)}% open`});let i=e[n].mesh[152][2];Math.abs(i)>10&&t.push({face:n,gesture:`head ${i<0?"up":"down"}`})}return t},gT=e=>{if(!e)return[];let t=[];for(let n=0;n.06||d>.06)&&(c=!1),p>.06&&t.push({iris:n,gesture:"looking right"}),d>.06&&t.push({iris:n,gesture:"looking left"});let h=Math.abs(e[n].mesh[145][1]-e[n].annotations.rightEyeIris[0][1])/e[n].box[3],f=Math.abs(e[n].mesh[374][1]-e[n].annotations.leftEyeIris[0][1])/e[n].box[3];(f<.01||h<.01||f>.022||h>.022)&&(c=!1),(f<.01||h<.01)&&t.push({iris:n,gesture:"looking down"}),(f>.022||h>.022)&&t.push({iris:n,gesture:"looking up"}),c&&t.push({iris:n,gesture:"looking center"})}return t},AT=e=>{if(!e)return[];let t=[];for(let n=0;n0){let r=s.reduce((o,i)=>o.position[2]o.position[1]((r-1)*Pe.body[z].box[te]+J)/r),ee=e.body[z].boxRaw.map((J,te)=>((r-1)*Pe.body[z].boxRaw[te]+J)/r),Y=e.body[z].keypoints.map((J,te)=>({score:J.score,part:J.part,position:[Pe.body[z].keypoints[te]?((r-1)*Pe.body[z].keypoints[te].position[0]+J.position[0])/r:J.position[0],Pe.body[z].keypoints[te]?((r-1)*Pe.body[z].keypoints[te].position[1]+J.position[1])/r:J.position[1]],positionRaw:[Pe.body[z].keypoints[te]?((r-1)*Pe.body[z].keypoints[te].positionRaw[0]+J.positionRaw[0])/r:J.position[0],Pe.body[z].keypoints[te]?((r-1)*Pe.body[z].keypoints[te].positionRaw[1]+J.positionRaw[1])/r:J.position[1]]})),ne={},se={connected:{}};((i=(o=t.body)==null?void 0:o.modelPath)==null?void 0:i.includes("efficientpose"))?se=jx:((c=(l=t.body)==null?void 0:l.modelPath)==null?void 0:c.includes("blazepose"))?se=zx:((d=(u=t.body)==null?void 0:u.modelPath)==null?void 0:d.includes("movenet"))&&(se=yb);for(let[J,te]of Object.entries(se.connected)){let ue=[];for(let ce=0;ceCe.part===te[ce]),we=Y.find(Ce=>Ce.part===te[ce+1]);be&&we&&be.score>(t.body.minConfidence||0)&&we.score>(t.body.minConfidence||0)&&ue.push([be.position,we.position])}ne[J]=ue}Pe.body[z]={...e.body[z],box:X,boxRaw:ee,keypoints:Y,annotations:ne}}if(!Pe.hand||e.hand.length!==Pe.hand.length)Pe.hand=JSON.parse(JSON.stringify(e.hand));else for(let z=0;z((r-1)*Pe.hand[z].box[J]+se)/r),ee=e.hand[z].boxRaw.map((se,J)=>((r-1)*Pe.hand[z].boxRaw[J]+se)/r);Pe.hand[z].keypoints.length!==e.hand[z].keypoints.length&&(Pe.hand[z].keypoints=e.hand[z].keypoints);let Y=e.hand[z].keypoints&&e.hand[z].keypoints.length>0?e.hand[z].keypoints.map((se,J)=>se.map((te,ue)=>((r-1)*(Pe.hand[z].keypoints[J][ue]||1)+(te||0))/r)):[],ne={};if(Object.keys(Pe.hand[z].annotations).length!==Object.keys(e.hand[z].annotations).length)Pe.hand[z].annotations=e.hand[z].annotations,ne=Pe.hand[z].annotations;else if(e.hand[z].annotations)for(let se of Object.keys(e.hand[z].annotations))ne[se]=e.hand[z].annotations[se]&&e.hand[z].annotations[se][0]?e.hand[z].annotations[se].map((J,te)=>J.map((ue,ce)=>((r-1)*Pe.hand[z].annotations[se][te][ce]+ue)/r)):null;Pe.hand[z]={...e.hand[z],box:X,boxRaw:ee,keypoints:Y,annotations:ne}}if(!Pe.face||e.face.length!==Pe.face.length)Pe.face=JSON.parse(JSON.stringify(e.face));else for(let z=0;z((r-1)*Pe.face[z].box[se]+ne)/r),ee=e.face[z].boxRaw.map((ne,se)=>((r-1)*Pe.face[z].boxRaw[se]+ne)/r),Y={matrix:[0,0,0,0,0,0,0,0,0],angle:{roll:0,yaw:0,pitch:0},gaze:{bearing:0,strength:0}};Y.matrix=(p=e.face[z].rotation)==null?void 0:p.matrix,Y.angle={roll:((r-1)*(((f=(h=Pe.face[z].rotation)==null?void 0:h.angle)==null?void 0:f.roll)||0)+(((g=(m=e.face[z].rotation)==null?void 0:m.angle)==null?void 0:g.roll)||0))/r,yaw:((r-1)*(((y=(A=Pe.face[z].rotation)==null?void 0:A.angle)==null?void 0:y.yaw)||0)+(((b=(x=e.face[z].rotation)==null?void 0:x.angle)==null?void 0:b.yaw)||0))/r,pitch:((r-1)*(((k=(w=Pe.face[z].rotation)==null?void 0:w.angle)==null?void 0:k.pitch)||0)+(((E=(S=e.face[z].rotation)==null?void 0:S.angle)==null?void 0:E.pitch)||0))/r},Y.gaze={bearing:((r-1)*(((F=($=Pe.face[z].rotation)==null?void 0:$.gaze)==null?void 0:F.bearing)||0)+(((P=(R=e.face[z].rotation)==null?void 0:R.gaze)==null?void 0:P.bearing)||0))/r,strength:((r-1)*(((M=(T=Pe.face[z].rotation)==null?void 0:T.gaze)==null?void 0:M.strength)||0)+(((H=(U=e.face[z].rotation)==null?void 0:U.gaze)==null?void 0:H.strength)||0))/r},Pe.face[z]={...e.face[z],rotation:Y,box:X,boxRaw:ee}}if(!Pe.object||e.object.length!==Pe.object.length)Pe.object=JSON.parse(JSON.stringify(e.object));else for(let z=0;z((r-1)*Pe.object[z].box[ne]+Y)/r),ee=e.object[z].boxRaw.map((Y,ne)=>((r-1)*Pe.object[z].boxRaw[ne]+Y)/r);Pe.object[z]={...e.object[z],box:X,boxRaw:ee}}if(e.persons){let z=e.persons;if(!Pe.persons||z.length!==Pe.persons.length)Pe.persons=JSON.parse(JSON.stringify(z));else for(let X=0;X((r-1)*Pe.persons[X].box[Y]+ee)/r)}e.gesture&&(Pe.gesture=e.gesture);let a=pe();return e.performance&&(Pe.performance={...e.performance,interpolate:Math.round(a-n)}),Pe}function c0(e,t,n={order:2}){let s=0;for(let r=0;rM.box[0]&&S.box[0]M.box[1]&&S.box[1]+S.box[3]E.body.box[0]&&M.box[0]+M.box[2]E.body.box[1]&&M.box[1]+M.box[3]E.body.box[0]&&M.box[1]+M.box[3]>E.body.box[1]&&M.box[1]+M.box[3]{M&&M.length===4&&($.push(M[0],M[0]+M[2]),F.push(M[1],M[1]+M[3]))};R((A=E.face)==null?void 0:A.box),R((y=E.body)==null?void 0:y.box),R((b=(x=E.hands)==null?void 0:x.left)==null?void 0:b.box),R((k=(w=E.hands)==null?void 0:w.right)==null?void 0:k.box);let P=Math.min(...$),T=Math.min(...F);E.box=[P,T,Math.max(...$)-P,Math.max(...F)-T],r&&r[1]&&r[2]&&(E.boxRaw=[E.box[0]/r[2],E.box[1]/r[1],E.box[2]/r[2],E.box[3]/r[1]]),o.push(E)}return o}var d0=` /9j/4AAQSkZJRgABAQEAYABgAAD/4QBoRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUA AAABAAAARgEoAAMAAAABAAIAAAExAAIAAAARAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQu bmV0IDQuMi4xMwAA/9sAQwAGBAUGBQQGBgUGBwcGCAoQCgoJCQoUDg8MEBcUGBgXFBYWGh0lHxob @@ -7809,7 +7809,7 @@ AAAAAAJAAAAAAAAAAAAAABAJEAAAAAAAAAAAAAAAIEoBKAAAAAAAAAAAAAAABAlAAAAAAAIAAAAA BAkBAkBAkBAlACEgMZjdjbFW8bWrEx8YWANb6Fp+bfwab+vLDKMFK9qxH5L0bAr8OPRPKz2AY7J2 SbAjYZAI2E7AIEgIEgIEgMdkSy2NgY7MdlmyNoBXsxmFuyNgVTVjNV3KjlBRNTlXTVHKCrlIqt5T lBhEMohlFerLlBjEMohMVTEARDKCITsAk2AEgAAAkAAAAAAAAAAAAAAAAAAAAAAAASAAAAAAAAD/ -2Q==`;async function Hge(e){let t=(r,a="application/octet-stream")=>fetch(`data:${a};base64,${r}`).then(o=>o.blob()),n,s;switch(e.config.warmup){case"face":n=await t(d0);break;case"body":case"full":n=await t(p0);break;default:n=null}if(n){let r=await createImageBitmap(n);s=await e.detect(r,e.config),r.close()}return s}async function jge(e){return new Promise(t=>{let n;switch(e.config.warmup){case"face":n="data:image/jpeg;base64,"+d0;break;case"full":case"body":n="data:image/jpeg;base64,"+p0;break;default:n=null}let s;typeof Image!="undefined"?s=new Image:be.Image&&(s=new be.Image),s.onload=async()=>{let r=Kn(s.naturalWidth,s.naturalHeight);if(!r)ae("Warmup: Canvas not found"),t({});else{let a=r.getContext("2d");a&&a.drawImage(s,0,0);let o=await e.image(r),i=await e.detect(o.tensor,e.config);t(i)}},n?s.src=n:t(null)})}async function qge(e){let t=r=>Buffer.from(r,"base64"),n;if(e.config.warmup==="face"&&(n=t(d0)),(e.config.warmup==="body"||e.config.warmup==="full")&&(n=t(p0)),!n)return null;let s;if(typeof void 0!="undefined"){let r=(void 0).decodeJpeg(n),a=r.expandDims(0);e.tf.dispose(r),s=await e.detect(a,e.config),e.tf.dispose(a)}else e.config.debug&&ae("Warmup tfjs-node not loaded");return s}async function wT(e,t){let n=Ae();if(e.state="warmup",t&&(e.config=$n(e.config,t)),!e.config.warmup||e.config.warmup==="none")return{error:"null"};let s;return new Promise(async r=>{typeof createImageBitmap=="function"?s=await Hge(e):typeof Image!="undefined"||be.Canvas!==void 0?s=await jge(e):s=await qge(e);let a=Ae();e.config.debug&&ae("Warmup",e.config.warmup,Math.round(a-n),"ms"),e.emit("warmup"),r(s)})}var gc,bp,vp,h0,Xge=class{constructor(t){pe(this,"version");pe(this,"config");pe(this,"result");pe(this,"state");pe(this,"process");pe(this,"tf");pe(this,"env");pe(this,"draw");pe(this,"models");pe(this,"events");pe(this,"faceTriangulation");pe(this,"faceUVMap");pe(this,"performance");Rc(this,gc,void 0);Rc(this,bp,void 0);Rc(this,vp,void 0);pe(this,"gl");pe(this,"analyze",(...t)=>{if(!Ec(this,bp))return;let n=this.tf.engine().state.numTensors,s=Ec(this,gc);$c(this,gc,n);let r=n-s;r!==0&&ae(...t,r)});Rc(this,h0,t=>{if(!Ec(this,vp))return null;if(!t)return"input is not defined";if(this.env.node&&!(t instanceof Ye))return"input must be a tensor";try{this.tf.getBackend()}catch(n){return"backend not loaded"}return null});pe(this,"similarity",xT);pe(this,"distance",c0);pe(this,"match",bT);pe(this,"emit",t=>{var n;this.events&&this.events.dispatchEvent&&((n=this.events)==null||n.dispatchEvent(new Event(t)))});this.env=be,Jo.wasmPath=up.includes("-")?"https://vladmandic.github.io/tfjs/dist/":`https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-backend-wasm@${up}/dist/`,Jo.modelBasePath=be.browser?"../models/":"file://models/",Jo.backend=be.browser?"humangl":"tensorflow",this.version=Cx,Object.defineProperty(this,"version",{value:Cx}),this.config=JSON.parse(JSON.stringify(Jo)),Object.seal(this.config),t&&(this.config=$n(this.config,t)),this.tf=wl,this.state="idle",$c(this,gc,0),$c(this,bp,!1),$c(this,vp,!1),this.performance={backend:0,load:0,image:0,frames:0,cached:0,changed:0,total:0,draw:0},this.events=typeof EventTarget!="undefined"?new EventTarget:void 0,this.models=new l0,this.draw={options:da,canvas:(n,s)=>dT(n,s),face:(n,s,r)=>Fb(n,s,r),body:(n,s,r)=>Ob(n,s,r),hand:(n,s,r)=>Mb(n,s,r),gesture:(n,s,r)=>Pb(n,s,r),object:(n,s,r)=>zb(n,s,r),person:(n,s,r)=>cT(n,s,r),all:(n,s,r)=>pT(n,s,r)},this.result={face:[],body:[],hand:[],gesture:[],object:[],performance:{},timestamp:0,persons:[]},this.process={tensor:null,canvas:null},this.faceTriangulation=h8,this.faceUVMap=f8,this.gl=zt,this.emit("create")}reset(){let t=this.config.backend;this.config=JSON.parse(JSON.stringify(Jo)),this.config.backend=t}validate(t){return Mg(Jo,t||this.config)}now(){return Ae()}image(t,n=!0){return uc(t,this.config,n)}async segmentation(t,n){return rT(t,n,this.config)}enhance(t){return sb(t)}async init(){await u0(this,!0),await this.tf.ready()}async load(t){this.state="load";let n=Ae(),s=Object.values(this.models).filter(o=>o).length;t&&(this.config=$n(this.config,t)),be.initial&&(this.config.debug&&ae(`version: ${this.version}`),this.config.debug&&ae(`tfjs version: ${this.tf.version_core}`),await u0(this)||ae("error: backend check failed"),await Wh(),this.env.browser&&(this.config.debug&&ae("configuration:",this.config),this.config.debug&&ae("tf flags:",this.tf.ENV.flags))),await aT(this),be.initial&&this.config.debug&&ae("tf engine state:",this.tf.engine().state.numBytes,"bytes",this.tf.engine().state.numTensors,"tensors"),be.initial=!1,Object.values(this.models).filter(o=>o).length!==s&&(await oT(this),this.emit("load"));let a=Math.trunc(Ae()-n);a>(this.performance.load||0)&&(this.performance.load=a)}next(t=this.result){return yT(t,this.config)}async warmup(t){return wT(this,t)}async detect(t,n){return this.state="detect",new Promise(async s=>{var A,y,x,b,w,k,S,E,P,F,R,_,T,M,U,H,z,X,ee,Y,se,ne;this.state="config";let r,a;this.config=$n(this.config,n),this.state="check";let o=Ec(this,h0).call(this,t);o&&(ae(o,t),s({error:o}));let i=Ae();await u0(this),await this.load(),r=Ae(),this.state="image";let l=uc(t,this.config);if(this.process=l,this.performance.image=Math.trunc(Ae()-r),this.analyze("Get Image:"),!l.tensor){this.config.debug&&ae("could not convert input to tensor"),s({error:"could not convert input to tensor"});return}this.emit("image"),r=Ae(),this.config.skipFrame=await $6(this.config,l.tensor),this.performance.frames||(this.performance.frames=0),this.performance.cached||(this.performance.cached=0),this.performance.frames++,this.config.skipFrame&&this.performance.cached++,this.performance.changed=Math.trunc(Ae()-r),this.analyze("Check Changed:");let c=[],u=[],d=[],p=[];this.state="detect:face",this.config.async?(c=this.config.face.enabled?Lb(this,l.tensor):[],this.performance.face&&delete this.performance.face):(r=Ae(),c=this.config.face.enabled?await Lb(this,l.tensor):[],a=Math.trunc(Ae()-r),a>0&&(this.performance.face=a)),this.config.async&&(this.config.body.maxDetected===-1||this.config.hand.maxDetected===-1)&&(c=await c),this.analyze("Start Body:"),this.state="detect:body";let h=this.config.body.maxDetected===-1?$n(this.config,{body:{maxDetected:this.config.face.enabled?1*c.length:1}}):this.config;this.config.async?(((A=this.config.body.modelPath)==null?void 0:A.includes("posenet"))?u=this.config.body.enabled?Eb(l.tensor,h):[]:((y=this.config.body.modelPath)==null?void 0:y.includes("blazepose"))?u=this.config.body.enabled?Wx(l.tensor,h):[]:((x=this.config.body.modelPath)==null?void 0:x.includes("efficientpose"))?u=this.config.body.enabled?Kx(l.tensor,h):[]:((b=this.config.body.modelPath)==null?void 0:b.includes("movenet"))&&(u=this.config.body.enabled?vb(l.tensor,h):[]),this.performance.body&&delete this.performance.body):(r=Ae(),((w=this.config.body.modelPath)==null?void 0:w.includes("posenet"))?u=this.config.body.enabled?await Eb(l.tensor,h):[]:((k=this.config.body.modelPath)==null?void 0:k.includes("blazepose"))?u=this.config.body.enabled?await Wx(l.tensor,h):[]:((S=this.config.body.modelPath)==null?void 0:S.includes("efficientpose"))?u=this.config.body.enabled?await Kx(l.tensor,h):[]:((E=this.config.body.modelPath)==null?void 0:E.includes("movenet"))&&(u=this.config.body.enabled?await vb(l.tensor,h):[]),a=Math.trunc(Ae()-r),a>0&&(this.performance.body=a)),this.analyze("End Body:"),this.analyze("Start Hand:"),this.state="detect:hand";let f=this.config.hand.maxDetected===-1?$n(this.config,{hand:{maxDetected:this.config.face.enabled?2*c.length:1}}):this.config;this.config.async?(((F=(P=this.config.hand.detector)==null?void 0:P.modelPath)==null?void 0:F.includes("handdetect"))?d=this.config.hand.enabled?ub(l.tensor,f):[]:((_=(R=this.config.hand.detector)==null?void 0:R.modelPath)==null?void 0:_.includes("handtrack"))&&(d=this.config.hand.enabled?fb(l.tensor,f):[]),this.performance.hand&&delete this.performance.hand):(r=Ae(),((M=(T=this.config.hand.detector)==null?void 0:T.modelPath)==null?void 0:M.includes("handdetect"))?d=this.config.hand.enabled?await ub(l.tensor,f):[]:((H=(U=this.config.hand.detector)==null?void 0:U.modelPath)==null?void 0:H.includes("handtrack"))&&(d=this.config.hand.enabled?await fb(l.tensor,f):[]),a=Math.trunc(Ae()-r),a>0&&(this.performance.hand=a)),this.analyze("End Hand:"),this.analyze("Start Object:"),this.state="detect:object",this.config.async?(((z=this.config.object.modelPath)==null?void 0:z.includes("nanodet"))?p=this.config.object.enabled?kb(l.tensor,this.config):[]:((X=this.config.object.modelPath)==null?void 0:X.includes("centernet"))&&(p=this.config.object.enabled?Ux(l.tensor,this.config):[]),this.performance.object&&delete this.performance.object):(r=Ae(),((ee=this.config.object.modelPath)==null?void 0:ee.includes("nanodet"))?p=this.config.object.enabled?await kb(l.tensor,this.config):[]:((Y=this.config.object.modelPath)==null?void 0:Y.includes("centernet"))&&(p=this.config.object.enabled?await Ux(l.tensor,this.config):[]),a=Math.trunc(Ae()-r),a>0&&(this.performance.object=a)),this.analyze("End Object:"),this.state="detect:await",this.config.async&&([c,u,d,p]=await Promise.all([c,u,d,p])),this.state="detect:gesture";let m=[];this.config.gesture.enabled&&(r=Ae(),m=[...mT(c),...fT(u),...AT(d),...gT(c)],this.config.async?this.performance.gesture&&delete this.performance.gesture:this.performance.gesture=Math.trunc(Ae()-r)),this.performance.total=Math.trunc(Ae()-i);let g=((ne=(se=this.process)==null?void 0:se.tensor)==null?void 0:ne.shape)||[];this.result={face:c,body:u,hand:d,gesture:m,object:p,performance:this.performance,canvas:this.process.canvas,timestamp:Date.now(),get persons(){return vT(c,u,d,m,g)}},Q(l.tensor),this.emit("detect"),this.state="idle",s(this.result)})}};gc=new WeakMap,bp=new WeakMap,vp=new WeakMap,h0=new WeakMap;export{Sx as Env,Xge as Human,l0 as Models,Xge as default,Jo as defaults,be as env}; +2Q==`;async function Hge(e){let t=(r,a="application/octet-stream")=>fetch(`data:${a};base64,${r}`).then(o=>o.blob()),n,s;switch(e.config.warmup){case"face":n=await t(d0);break;case"body":case"full":n=await t(p0);break;default:n=null}if(n){let r=await createImageBitmap(n);s=await e.detect(r,e.config),r.close()}return s}async function jge(e){return new Promise(t=>{let n;switch(e.config.warmup){case"face":n="data:image/jpeg;base64,"+d0;break;case"full":case"body":n="data:image/jpeg;base64,"+p0;break;default:n=null}let s;typeof Image!="undefined"?s=new Image:ye.Image&&(s=new ye.Image),s.onload=async()=>{let r=Kn(s.naturalWidth,s.naturalHeight);if(!r)ae("Warmup: Canvas not found"),t({});else{let a=r.getContext("2d");a&&a.drawImage(s,0,0);let o=await e.image(r),i=await e.detect(o.tensor,e.config);t(i)}},n?s.src=n:t(null)})}async function qge(e){let t=r=>Buffer.from(r,"base64"),n;if(e.config.warmup==="face"&&(n=t(d0)),(e.config.warmup==="body"||e.config.warmup==="full")&&(n=t(p0)),!n)return null;let s;if(typeof void 0!="undefined"){let r=(void 0).decodeJpeg(n),a=r.expandDims(0);e.tf.dispose(r),s=await e.detect(a,e.config),e.tf.dispose(a)}else e.config.debug&&ae("Warmup tfjs-node not loaded");return s}async function wT(e,t){let n=pe();if(e.state="warmup",t&&(e.config=$n(e.config,t)),!e.config.warmup||e.config.warmup==="none")return{error:"null"};let s;return new Promise(async r=>{typeof createImageBitmap=="function"?s=await Hge(e):typeof Image!="undefined"||ye.Canvas!==void 0?s=await jge(e):s=await qge(e);let a=pe();e.config.debug&&ae("Warmup",e.config.warmup,Math.round(a-n),"ms"),e.emit("warmup"),r(s)})}var gc,bp,vp,h0,Xge=class{constructor(t){de(this,"version");de(this,"config");de(this,"result");de(this,"state");de(this,"process");de(this,"tf");de(this,"env");de(this,"draw");de(this,"models");de(this,"events");de(this,"faceTriangulation");de(this,"faceUVMap");de(this,"performance");Rc(this,gc,void 0);Rc(this,bp,void 0);Rc(this,vp,void 0);de(this,"gl");de(this,"analyze",(...t)=>{if(!Ec(this,bp))return;let n=this.tf.engine().state.numTensors,s=Ec(this,gc);$c(this,gc,n);let r=n-s;r!==0&&ae(...t,r)});Rc(this,h0,t=>{if(!Ec(this,vp))return null;if(!t)return"input is not defined";if(this.env.node&&!(t instanceof Ye))return"input must be a tensor";try{this.tf.getBackend()}catch(n){return"backend not loaded"}return null});de(this,"similarity",xT);de(this,"distance",c0);de(this,"match",bT);de(this,"emit",t=>{var n;this.events&&this.events.dispatchEvent&&((n=this.events)==null||n.dispatchEvent(new Event(t)))});this.env=ye,Jo.wasmPath=up.includes("-")?"https://vladmandic.github.io/tfjs/dist/":`https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-backend-wasm@${up}/dist/`,Jo.modelBasePath=ye.browser?"../models/":"file://models/",Jo.backend=ye.browser?"humangl":"tensorflow",this.version=Cx,Object.defineProperty(this,"version",{value:Cx}),this.config=JSON.parse(JSON.stringify(Jo)),Object.seal(this.config),t&&(this.config=$n(this.config,t)),this.tf=wl,this.state="idle",$c(this,gc,0),$c(this,bp,!1),$c(this,vp,!1),this.performance={backend:0,load:0,image:0,frames:0,cached:0,changed:0,total:0,draw:0},this.events=typeof EventTarget!="undefined"?new EventTarget:void 0,this.models=new l0,this.draw={options:da,canvas:(n,s)=>dT(n,s),face:(n,s,r)=>Fb(n,s,r),body:(n,s,r)=>Ob(n,s,r),hand:(n,s,r)=>Mb(n,s,r),gesture:(n,s,r)=>Pb(n,s,r),object:(n,s,r)=>zb(n,s,r),person:(n,s,r)=>cT(n,s,r),all:(n,s,r)=>pT(n,s,r)},this.result={face:[],body:[],hand:[],gesture:[],object:[],performance:{},timestamp:0,persons:[]},this.process={tensor:null,canvas:null},this.faceTriangulation=h8,this.faceUVMap=f8,this.gl=zt,this.emit("create")}reset(){let t=this.config.backend;this.config=JSON.parse(JSON.stringify(Jo)),this.config.backend=t}validate(t){return Mg(Jo,t||this.config)}now(){return pe()}image(t,n=!0){return uc(t,this.config,n)}async segmentation(t,n){return rT(t,n,this.config)}enhance(t){return sb(t)}async init(){await u0(this,!0),await this.tf.ready()}async load(t){this.state="load";let n=pe(),s=Object.values(this.models).filter(o=>o).length;t&&(this.config=$n(this.config,t)),this.env.initial&&(this.config.debug&&ae(`version: ${this.version}`),this.config.debug&&ae(`tfjs version: ${this.tf.version_core}`),await u0(this)||ae("error: backend check failed"),await Wh(),this.env.browser&&(this.config.debug&&ae("configuration:",this.config),this.config.debug&&ae("tf flags:",this.tf.ENV.flags))),await aT(this),this.env.initial&&this.config.debug&&ae("tf engine state:",this.tf.engine().state.numBytes,"bytes",this.tf.engine().state.numTensors,"tensors"),this.env.initial=!1,Object.values(this.models).filter(o=>o).length!==s&&(await oT(this),this.emit("load"));let a=Math.trunc(pe()-n);a>(this.performance.load||0)&&(this.performance.load=this.env.perfadd?(this.performance.load||0)+a:a)}next(t=this.result){return yT(t,this.config)}async warmup(t){return wT(this,t)}async detect(t,n){return this.state="detect",new Promise(async s=>{var g,A,y,x,b,w,k,S,E,$,F,R,P,T,M,U,H,z,X,ee,Y,ne;this.state="config";let r;this.config=$n(this.config,n),this.state="check";let a=Ec(this,h0).call(this,t);a&&(ae(a,t),s({error:a}));let o=pe();await u0(this),await this.load(),r=pe(),this.state="image";let i=uc(t,this.config);if(this.process=i,this.performance.image=this.env.perfadd?(this.performance.image||0)+Math.trunc(pe()-r):Math.trunc(pe()-r),this.analyze("Get Image:"),!i.tensor){this.config.debug&&ae("could not convert input to tensor"),s({error:"could not convert input to tensor"});return}this.emit("image"),r=pe(),this.config.skipAllowed=await $6(this.config,i.tensor),this.performance.frames||(this.performance.frames=0),this.performance.cached||(this.performance.cached=0),this.performance.frames++,this.config.skipAllowed&&this.performance.cached++,this.performance.changed=this.env.perfadd?(this.performance.changed||0)+Math.trunc(pe()-r):Math.trunc(pe()-r),this.analyze("Check Changed:");let l=[],c=[],u=[],d=[];this.state="detect:face",this.config.async?(l=this.config.face.enabled?Lb(this,i.tensor):[],this.performance.face&&delete this.performance.face):(r=pe(),l=this.config.face.enabled?await Lb(this,i.tensor):[],this.performance.face=this.env.perfadd?(this.performance.face||0)+Math.trunc(pe()-r):Math.trunc(pe()-r)),this.config.async&&(this.config.body.maxDetected===-1||this.config.hand.maxDetected===-1)&&(l=await l),this.analyze("Start Body:"),this.state="detect:body";let p=this.config.body.maxDetected===-1?$n(this.config,{body:{maxDetected:this.config.face.enabled?1*l.length:1}}):this.config;this.config.async?(((g=this.config.body.modelPath)==null?void 0:g.includes("posenet"))?c=this.config.body.enabled?Eb(i.tensor,p):[]:((A=this.config.body.modelPath)==null?void 0:A.includes("blazepose"))?c=this.config.body.enabled?Wx(i.tensor,p):[]:((y=this.config.body.modelPath)==null?void 0:y.includes("efficientpose"))?c=this.config.body.enabled?Kx(i.tensor,p):[]:((x=this.config.body.modelPath)==null?void 0:x.includes("movenet"))&&(c=this.config.body.enabled?vb(i.tensor,p):[]),this.performance.body&&delete this.performance.body):(r=pe(),((b=this.config.body.modelPath)==null?void 0:b.includes("posenet"))?c=this.config.body.enabled?await Eb(i.tensor,p):[]:((w=this.config.body.modelPath)==null?void 0:w.includes("blazepose"))?c=this.config.body.enabled?await Wx(i.tensor,p):[]:((k=this.config.body.modelPath)==null?void 0:k.includes("efficientpose"))?c=this.config.body.enabled?await Kx(i.tensor,p):[]:((S=this.config.body.modelPath)==null?void 0:S.includes("movenet"))&&(c=this.config.body.enabled?await vb(i.tensor,p):[]),this.performance.body=this.env.perfadd?(this.performance.body||0)+Math.trunc(pe()-r):Math.trunc(pe()-r)),this.analyze("End Body:"),this.analyze("Start Hand:"),this.state="detect:hand";let h=this.config.hand.maxDetected===-1?$n(this.config,{hand:{maxDetected:this.config.face.enabled?2*l.length:1}}):this.config;this.config.async?((($=(E=this.config.hand.detector)==null?void 0:E.modelPath)==null?void 0:$.includes("handdetect"))?u=this.config.hand.enabled?ub(i.tensor,h):[]:((R=(F=this.config.hand.detector)==null?void 0:F.modelPath)==null?void 0:R.includes("handtrack"))&&(u=this.config.hand.enabled?fb(i.tensor,h):[]),this.performance.hand&&delete this.performance.hand):(r=pe(),((T=(P=this.config.hand.detector)==null?void 0:P.modelPath)==null?void 0:T.includes("handdetect"))?u=this.config.hand.enabled?await ub(i.tensor,h):[]:((U=(M=this.config.hand.detector)==null?void 0:M.modelPath)==null?void 0:U.includes("handtrack"))&&(u=this.config.hand.enabled?await fb(i.tensor,h):[]),this.performance.hand=this.env.perfadd?(this.performance.hand||0)+Math.trunc(pe()-r):Math.trunc(pe()-r)),this.analyze("End Hand:"),this.analyze("Start Object:"),this.state="detect:object",this.config.async?(((H=this.config.object.modelPath)==null?void 0:H.includes("nanodet"))?d=this.config.object.enabled?kb(i.tensor,this.config):[]:((z=this.config.object.modelPath)==null?void 0:z.includes("centernet"))&&(d=this.config.object.enabled?Ux(i.tensor,this.config):[]),this.performance.object&&delete this.performance.object):(r=pe(),((X=this.config.object.modelPath)==null?void 0:X.includes("nanodet"))?d=this.config.object.enabled?await kb(i.tensor,this.config):[]:((ee=this.config.object.modelPath)==null?void 0:ee.includes("centernet"))&&(d=this.config.object.enabled?await Ux(i.tensor,this.config):[]),this.performance.object=this.env.perfadd?(this.performance.object||0)+Math.trunc(pe()-r):Math.trunc(pe()-r)),this.analyze("End Object:"),this.state="detect:await",this.config.async&&([l,c,u,d]=await Promise.all([l,c,u,d])),this.state="detect:gesture";let f=[];this.config.gesture.enabled&&(r=pe(),f=[...mT(l),...fT(c),...AT(u),...gT(l)],this.config.async?this.performance.gesture&&delete this.performance.gesture:this.performance.gesture=this.env.perfadd?(this.performance.gesture||0)+Math.trunc(pe()-r):Math.trunc(pe()-r)),this.performance.total=Math.trunc(pe()-o);let m=((ne=(Y=this.process)==null?void 0:Y.tensor)==null?void 0:ne.shape)||[];this.result={face:l,body:c,hand:u,gesture:f,object:d,performance:this.performance,canvas:this.process.canvas,timestamp:Date.now(),get persons(){return vT(l,c,u,f,m)}},Q(i.tensor),this.emit("detect"),this.state="idle",s(this.result)})}};gc=new WeakMap,bp=new WeakMap,vp=new WeakMap,h0=new WeakMap;export{Sx as Env,Xge as Human,l0 as Models,Xge as default,Jo as defaults,ye as env}; /** * @license * Copyright 2017 Google LLC. All Rights Reserved. diff --git a/dist/human.custom.esm.js.map b/dist/human.custom.esm.js.map index df5a401d..5612654e 100644 --- a/dist/human.custom.esm.js.map +++ b/dist/human.custom.esm.js.map @@ -1,7 +1,7 @@ { "version": 3, "sources": ["../src/util/util.ts", "../src/config.ts", "../../tfjs/node_modules/.pnpm/long@4.0.0/node_modules/long/src/long.js", "../../tfjs/dist/(disabled):node-fetch", "../../tfjs/dist/(disabled):util", "../../tfjs/node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/alea.js", "../../tfjs/node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor128.js", "../../tfjs/node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorwow.js", "../../tfjs/node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorshift7.js", "../../tfjs/node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor4096.js", "../../tfjs/node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/tychei.js", "../../tfjs/dist/(disabled):crypto", "../../tfjs/node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/seedrandom.js", "../../tfjs/node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/index.js", "../../tfjs/src/node_modules/string_decoder/index.js", "../../tfjs/src/tfjs-backend-wasm/wasm-out/tfjs-backend-wasm-threaded-simd.js", "../../tfjs/src/tfjs-backend-wasm/wasm-out/tfjs-backend-wasm.js", "../../tfjs/src/tfjs-core/src/backends/backend.ts", "../../tfjs/src/tfjs-core/src/util_base.ts", "../../tfjs/src/tfjs-core/src/log.ts", "../../tfjs/src/tfjs-core/src/environment.ts", "../../tfjs/src/tfjs-core/src/global_util.ts", "../../tfjs/src/tfjs-core/src/kernel_names.ts", "../../tfjs/src/tfjs-core/src/kernel_registry.ts", "../../tfjs/src/tfjs-core/src/util.ts", "../../tfjs/src/tfjs-core/src/hash_util.ts", "../../tfjs/src/tfjs-core/src/profiler.ts", "../../tfjs/src/tfjs-core/src/tape.ts", "../../tfjs/src/tfjs-core/src/tensor_format.ts", "../../tfjs/src/tfjs-core/src/tensor.ts", "../../tfjs/src/tfjs-core/src/tensor_util.ts", "../../tfjs/src/tfjs-core/src/types.ts", "../../tfjs/src/tfjs-core/src/engine.ts", "../../tfjs/src/tfjs-core/src/device_util.ts", "../../tfjs/src/tfjs-core/src/flags.ts", "../../tfjs/src/tfjs-core/src/tensor_util_env.ts", "../../tfjs/src/tfjs-core/src/ops/operation.ts", "../../tfjs/src/tfjs-core/src/ops/complex.ts", "../../tfjs/src/tfjs-core/src/ops/tensor_ops_util.ts", "../../tfjs/src/tfjs-core/src/ops/tensor.ts", "../../tfjs/src/tfjs-core/src/io/types.ts", "../../tfjs/src/tfjs-core/src/io/io_utils.ts", "../../tfjs/src/tfjs-core/src/io/router_registry.ts", "../../tfjs/src/tfjs-core/src/io/indexed_db.ts", "../../tfjs/src/tfjs-core/src/io/local_storage.ts", "../../tfjs/src/tfjs-core/src/io/model_management.ts", "../../tfjs/src/tfjs-core/src/platforms/platform_browser.ts", "../../tfjs/src/tfjs-core/src/platforms/platform_node.ts", "../../tfjs/src/tfjs-core/src/ops/buffer.ts", "../../tfjs/src/tfjs-core/src/ops/cast.ts", "../../tfjs/src/tfjs-core/src/ops/clone.ts", "../../tfjs/src/tfjs-core/src/ops/print.ts", "../../tfjs/src/tfjs-core/src/base_side_effects.ts", "../../tfjs/src/tfjs-core/src/io/io.ts", "../../tfjs/src/tfjs-core/src/io/browser_files.ts", "../../tfjs/src/tfjs-core/src/io/progress.ts", "../../tfjs/src/tfjs-core/src/io/weights_loader.ts", "../../tfjs/src/tfjs-core/src/io/http.ts", "../../tfjs/src/tfjs-core/src/io/passthrough.ts", "../../tfjs/src/tfjs-core/src/math.ts", "../../tfjs/src/tfjs-core/src/ops/mat_mul.ts", "../../tfjs/src/tfjs-core/src/ops/one_hot.ts", "../../tfjs/src/tfjs-core/src/ops/transpose.ts", "../../tfjs/src/tfjs-core/src/ops/confusion_matrix.ts", "../../tfjs/src/tfjs-core/src/ops/browser.ts", "../../tfjs/src/tfjs-core/src/ops/tensor3d.ts", "../../tfjs/src/tfjs-core/src/ops/gather_nd_util.ts", "../../tfjs/src/tfjs-core/src/ops/scatter_nd_util.ts", "../../tfjs/src/tfjs-core/src/ops/slice_util.ts", "../../tfjs/src/tfjs-core/src/serialization.ts", "../../tfjs/src/tfjs-core/src/test_util.ts", "../../tfjs/src/tfjs-core/src/version.ts", "../../tfjs/src/tfjs-core/src/model_types.ts", "../../tfjs/src/tfjs-core/src/globals.ts", "../../tfjs/src/tfjs-core/src/ops/add.ts", "../../tfjs/src/tfjs-core/src/ops/floorDiv.ts", "../../tfjs/src/tfjs-core/src/ops/div.ts", "../../tfjs/src/tfjs-core/src/ops/mul.ts", "../../tfjs/src/tfjs-core/src/ops/abs.ts", "../../tfjs/src/tfjs-core/src/ops/acos.ts", "../../tfjs/src/tfjs-core/src/ops/acosh.ts", "../../tfjs/src/tfjs-core/src/ops/add_n.ts", "../../tfjs/src/tfjs-core/src/ops/all.ts", "../../tfjs/src/tfjs-core/src/ops/any.ts", "../../tfjs/src/tfjs-core/src/ops/arg_max.ts", "../../tfjs/src/tfjs-core/src/ops/arg_min.ts", "../../tfjs/src/tfjs-core/src/ops/asin.ts", "../../tfjs/src/tfjs-core/src/ops/asinh.ts", "../../tfjs/src/tfjs-core/src/ops/atan.ts", "../../tfjs/src/tfjs-core/src/ops/atan2.ts", "../../tfjs/src/tfjs-core/src/ops/atanh.ts", "../../tfjs/src/tfjs-core/src/ops/conv_util.ts", "../../tfjs/src/tfjs-core/src/ops/reshape.ts", "../../tfjs/src/tfjs-core/src/ops/avg_pool.ts", "../../tfjs/src/tfjs-core/src/ops/avg_pool_3d.ts", "../../tfjs/src/tfjs-core/src/ops/concat.ts", "../../tfjs/src/tfjs-core/src/ops/sigmoid.ts", "../../tfjs/src/tfjs-core/src/ops/slice.ts", "../../tfjs/src/tfjs-core/src/ops/tanh.ts", "../../tfjs/src/tfjs-core/src/ops/basic_lstm_cell.ts", "../../tfjs/src/tfjs-core/src/ops/batch_to_space_nd.ts", "../../tfjs/src/tfjs-core/src/ops/batchnorm_util.ts", "../../tfjs/src/tfjs-core/src/ops/batchnorm.ts", "../../tfjs/src/tfjs-core/src/ops/batchnorm2d.ts", "../../tfjs/src/tfjs-core/src/ops/batchnorm3d.ts", "../../tfjs/src/tfjs-core/src/ops/batchnorm4d.ts", "../../tfjs/src/tfjs-core/src/ops/bincount.ts", "../../tfjs/src/tfjs-core/src/ops/broadcast_args.ts", "../../tfjs/src/tfjs-core/src/ops/broadcast_to.ts", "../../tfjs/src/tfjs-core/src/ops/ceil.ts", "../../tfjs/src/tfjs-core/src/ops/clip_by_value.ts", "../../tfjs/src/tfjs-core/src/ops/concat_1d.ts", "../../tfjs/src/tfjs-core/src/ops/concat_2d.ts", "../../tfjs/src/tfjs-core/src/ops/concat_3d.ts", "../../tfjs/src/tfjs-core/src/ops/concat_4d.ts", "../../tfjs/src/tfjs-core/src/ops/conv2d.ts", "../../tfjs/src/tfjs-core/src/ops/conv1d.ts", "../../tfjs/src/tfjs-core/src/ops/conv2d_backprop_input.ts", "../../tfjs/src/tfjs-core/src/ops/conv2d_transpose.ts", "../../tfjs/src/tfjs-core/src/ops/conv3d.ts", "../../tfjs/src/tfjs-core/src/ops/conv3d_backprop_input.ts", "../../tfjs/src/tfjs-core/src/ops/conv3d_transpose.ts", "../../tfjs/src/tfjs-core/src/ops/cos.ts", "../../tfjs/src/tfjs-core/src/ops/cosh.ts", "../../tfjs/src/tfjs-core/src/ops/cumsum.ts", "../../tfjs/src/tfjs-core/src/ops/dense_bincount.ts", "../../tfjs/src/tfjs-core/src/ops/depth_to_space.ts", "../../tfjs/src/tfjs-core/src/ops/depthwise_conv2d.ts", "../../tfjs/src/tfjs-core/src/ops/diag.ts", "../../tfjs/src/tfjs-core/src/ops/dilation2d.ts", "../../tfjs/src/tfjs-core/src/ops/broadcast_util.ts", "../../tfjs/src/tfjs-core/src/ops/equal.ts", "../../tfjs/src/tfjs-core/src/ops/where.ts", "../../tfjs/src/tfjs-core/src/ops/zeros_like.ts", "../../tfjs/src/tfjs-core/src/ops/div_no_nan.ts", "../../tfjs/src/tfjs-core/src/ops/dot.ts", "../../tfjs/src/tfjs-core/src/ops/einsum.ts", "../../tfjs/src/tfjs-core/src/ops/elu.ts", "../../tfjs/src/tfjs-core/src/ops/erf.ts", "../../tfjs/src/tfjs-core/src/ops/exp.ts", "../../tfjs/src/tfjs-core/src/ops/expand_dims.ts", "../../tfjs/src/tfjs-core/src/ops/expm1.ts", "../../tfjs/src/tfjs-core/src/ops/tile.ts", "../../tfjs/src/tfjs-core/src/ops/eye.ts", "../../tfjs/src/tfjs-core/src/ops/fill.ts", "../../tfjs/src/tfjs-core/src/ops/floor.ts", "../../tfjs/src/tfjs-core/src/ops/gather.ts", "../../tfjs/src/tfjs-core/src/ops/greater.ts", "../../tfjs/src/tfjs-core/src/ops/greater_equal.ts", "../../tfjs/src/tfjs-core/src/ops/imag.ts", "../../tfjs/src/tfjs-core/src/ops/is_finite.ts", "../../tfjs/src/tfjs-core/src/ops/is_inf.ts", "../../tfjs/src/tfjs-core/src/ops/is_nan.ts", "../../tfjs/src/tfjs-core/src/ops/leaky_relu.ts", "../../tfjs/src/tfjs-core/src/ops/less.ts", "../../tfjs/src/tfjs-core/src/ops/less_equal.ts", "../../tfjs/src/tfjs-core/src/ops/linspace.ts", "../../tfjs/src/tfjs-core/src/ops/local_response_normalization.ts", "../../tfjs/src/tfjs-core/src/ops/log.ts", "../../tfjs/src/tfjs-core/src/ops/log1p.ts", "../../tfjs/src/tfjs-core/src/gradients.ts", "../../tfjs/src/tfjs-core/src/ops/neg.ts", "../../tfjs/src/tfjs-core/src/ops/softplus.ts", "../../tfjs/src/tfjs-core/src/ops/log_sigmoid.ts", "../../tfjs/src/tfjs-core/src/ops/max.ts", "../../tfjs/src/tfjs-core/src/ops/sub.ts", "../../tfjs/src/tfjs-core/src/ops/sum.ts", "../../tfjs/src/tfjs-core/src/ops/log_softmax.ts", "../../tfjs/src/tfjs-core/src/ops/axis_util.ts", "../../tfjs/src/tfjs-core/src/ops/log_sum_exp.ts", "../../tfjs/src/tfjs-core/src/ops/logical_and.ts", "../../tfjs/src/tfjs-core/src/ops/logical_not.ts", "../../tfjs/src/tfjs-core/src/ops/logical_or.ts", "../../tfjs/src/tfjs-core/src/ops/logical_xor.ts", "../../tfjs/src/tfjs-core/src/ops/max_pool.ts", "../../tfjs/src/tfjs-core/src/ops/max_pool_3d.ts", "../../tfjs/src/tfjs-core/src/ops/max_pool_with_argmax.ts", "../../tfjs/src/tfjs-core/src/ops/maximum.ts", "../../tfjs/src/tfjs-core/src/ops/mean.ts", "../../tfjs/src/tfjs-core/src/ops/zeros.ts", "../../tfjs/src/tfjs-core/src/ops/ones.ts", "../../tfjs/src/tfjs-core/src/ops/meshgrid.ts", "../../tfjs/src/tfjs-core/src/ops/min.ts", "../../tfjs/src/tfjs-core/src/ops/minimum.ts", "../../tfjs/src/tfjs-core/src/ops/mirror_pad.ts", "../../tfjs/src/tfjs-core/src/ops/mod.ts", "../../tfjs/src/tfjs-core/src/ops/square.ts", "../../tfjs/src/tfjs-core/src/ops/moments.ts", "../../tfjs/src/tfjs-core/src/ops/multi_rnn_cell.ts", "../../tfjs/src/tfjs-core/src/ops/multinomial.ts", "../../tfjs/src/tfjs-core/src/ops/not_equal.ts", "../../tfjs/src/tfjs-core/src/ops/ones_like.ts", "../../tfjs/src/tfjs-core/src/ops/outer_product.ts", "../../tfjs/src/tfjs-core/src/ops/pad.ts", "../../tfjs/src/tfjs-core/src/ops/pad1d.ts", "../../tfjs/src/tfjs-core/src/ops/pad2d.ts", "../../tfjs/src/tfjs-core/src/ops/pad3d.ts", "../../tfjs/src/tfjs-core/src/ops/pad4d.ts", "../../tfjs/src/tfjs-core/src/ops/space_to_batch_nd.ts", "../../tfjs/src/tfjs-core/src/ops/pool.ts", "../../tfjs/src/tfjs-core/src/ops/pow.ts", "../../tfjs/src/tfjs-core/src/ops/prelu.ts", "../../tfjs/src/tfjs-core/src/ops/prod.ts", "../../tfjs/src/tfjs-core/src/ops/rand.ts", "../../tfjs/src/tfjs-core/src/ops/rand_util.ts", "../../tfjs/src/tfjs-core/src/ops/random_gamma.ts", "../../tfjs/src/tfjs-core/src/ops/random_normal.ts", "../../tfjs/src/tfjs-core/src/ops/random_uniform.ts", "../../tfjs/src/tfjs-core/src/ops/range.ts", "../../tfjs/src/tfjs-core/src/ops/real.ts", "../../tfjs/src/tfjs-core/src/ops/reciprocal.ts", "../../tfjs/src/tfjs-core/src/ops/relu.ts", "../../tfjs/src/tfjs-core/src/ops/relu6.ts", "../../tfjs/src/tfjs-core/src/ops/reverse.ts", "../../tfjs/src/tfjs-core/src/ops/reverse_1d.ts", "../../tfjs/src/tfjs-core/src/ops/reverse_2d.ts", "../../tfjs/src/tfjs-core/src/ops/reverse_3d.ts", "../../tfjs/src/tfjs-core/src/ops/reverse_4d.ts", "../../tfjs/src/tfjs-core/src/ops/round.ts", "../../tfjs/src/tfjs-core/src/ops/rsqrt.ts", "../../tfjs/src/tfjs-core/src/ops/scalar.ts", "../../tfjs/src/tfjs-core/src/ops/selu.ts", "../../tfjs/src/tfjs-core/src/ops/separable_conv2d.ts", "../../tfjs/src/tfjs-core/src/ops/setdiff1d_async.ts", "../../tfjs/src/tfjs-core/src/ops/sign.ts", "../../tfjs/src/tfjs-core/src/ops/sin.ts", "../../tfjs/src/tfjs-core/src/ops/sinh.ts", "../../tfjs/src/tfjs-core/src/ops/slice1d.ts", "../../tfjs/src/tfjs-core/src/ops/slice2d.ts", "../../tfjs/src/tfjs-core/src/ops/slice3d.ts", "../../tfjs/src/tfjs-core/src/ops/slice4d.ts", "../../tfjs/src/tfjs-core/src/ops/softmax.ts", "../../tfjs/src/tfjs-core/src/ops/spectral/fft.ts", "../../tfjs/src/tfjs-core/src/ops/spectral/ifft.ts", "../../tfjs/src/tfjs-core/src/ops/spectral/irfft.ts", "../../tfjs/src/tfjs-core/src/ops/split.ts", "../../tfjs/src/tfjs-core/src/ops/spectral/rfft.ts", "../../tfjs/src/tfjs-core/src/ops/sqrt.ts", "../../tfjs/src/tfjs-core/src/ops/squared_difference.ts", "../../tfjs/src/tfjs-core/src/ops/squeeze.ts", "../../tfjs/src/tfjs-core/src/ops/stack.ts", "../../tfjs/src/tfjs-core/src/ops/step.ts", "../../tfjs/src/tfjs-core/src/ops/strided_slice.ts", "../../tfjs/src/tfjs-core/src/ops/tan.ts", "../../tfjs/src/tfjs-core/src/ops/tensor1d.ts", "../../tfjs/src/tfjs-core/src/ops/tensor2d.ts", "../../tfjs/src/tfjs-core/src/ops/tensor4d.ts", "../../tfjs/src/tfjs-core/src/ops/tensor5d.ts", "../../tfjs/src/tfjs-core/src/ops/tensor6d.ts", "../../tfjs/src/tfjs-core/src/ops/topk.ts", "../../tfjs/src/tfjs-core/src/ops/truncated_normal.ts", "../../tfjs/src/tfjs-core/src/ops/unique.ts", "../../tfjs/src/tfjs-core/src/ops/unsorted_segment_sum.ts", "../../tfjs/src/tfjs-core/src/ops/unstack.ts", "../../tfjs/src/tfjs-core/src/ops/variable.ts", "../../tfjs/src/tfjs-core/src/backends/where_impl.ts", "../../tfjs/src/tfjs-core/src/ops/where_async.ts", "../../tfjs/src/tfjs-core/src/ops/boolean_mask.ts", "../../tfjs/src/tfjs-core/src/ops/norm.ts", "../../tfjs/src/tfjs-core/src/ops/moving_average.ts", "../../tfjs/src/tfjs-core/src/ops/scatter_nd.ts", "../../tfjs/src/tfjs-core/src/ops/sparse_to_dense_util.ts", "../../tfjs/src/tfjs-core/src/ops/sparse_to_dense.ts", "../../tfjs/src/tfjs-core/src/ops/gather_nd.ts", "../../tfjs/src/tfjs-core/src/ops/dropout_util.ts", "../../tfjs/src/tfjs-core/src/ops/dropout.ts", "../../tfjs/src/tfjs-core/src/ops/signal_ops_util.ts", "../../tfjs/src/tfjs-core/src/ops/in_top_k.ts", "../../tfjs/src/tfjs-core/src/ops/fused_ops.ts", "../../tfjs/src/tfjs-core/src/ops/conv2d_backprop_filter.ts", "../../tfjs/src/tfjs-core/src/ops/fused_util.ts", "../../tfjs/src/tfjs-core/src/ops/fused/conv2d.ts", "../../tfjs/src/tfjs-core/src/ops/depthwise_conv2d_native_backprop_filter.ts", "../../tfjs/src/tfjs-core/src/ops/depthwise_conv2d_native_backprop_input.ts", "../../tfjs/src/tfjs-core/src/ops/fused/depthwise_conv2d.ts", "../../tfjs/src/tfjs-core/src/ops/fused/mat_mul.ts", "../../tfjs/src/tfjs-core/src/ops/fused_types.ts", "../../tfjs/src/tfjs-core/src/ops/signal/hamming_window.ts", "../../tfjs/src/tfjs-core/src/ops/signal/hann_window.ts", "../../tfjs/src/tfjs-core/src/ops/signal/frame.ts", "../../tfjs/src/tfjs-core/src/ops/signal/stft.ts", "../../tfjs/src/tfjs-core/src/ops/image/crop_and_resize.ts", "../../tfjs/src/tfjs-core/src/ops/image/flip_left_right.ts", "../../tfjs/src/tfjs-core/src/ops/image/grayscale_to_rgb.ts", "../../tfjs/src/tfjs-core/src/ops/image/rotate_with_offset.ts", "../../tfjs/src/tfjs-core/src/ops/nonmax_util.ts", "../../tfjs/src/tfjs-core/src/ops/image/non_max_suppression.ts", "../../tfjs/src/tfjs-core/src/backends/non_max_suppression_util.ts", "../../tfjs/src/tfjs-core/src/backends/non_max_suppression_impl.ts", "../../tfjs/src/tfjs-core/src/ops/image/non_max_suppression_async.ts", "../../tfjs/src/tfjs-core/src/ops/image/non_max_suppression_with_score.ts", "../../tfjs/src/tfjs-core/src/ops/image/non_max_suppression_with_score_async.ts", "../../tfjs/src/tfjs-core/src/ops/image/non_max_suppression_padded.ts", "../../tfjs/src/tfjs-core/src/ops/image/non_max_suppression_padded_async.ts", "../../tfjs/src/tfjs-core/src/ops/image/resize_bilinear.ts", "../../tfjs/src/tfjs-core/src/ops/image/resize_nearest_neighbor.ts", "../../tfjs/src/tfjs-core/src/ops/image/threshold.ts", "../../tfjs/src/tfjs-core/src/ops/image/transform.ts", "../../tfjs/src/tfjs-core/src/ops/linalg/band_part.ts", "../../tfjs/src/tfjs-core/src/ops/linalg/gram_schmidt.ts", "../../tfjs/src/tfjs-core/src/ops/linalg/qr.ts", "../../tfjs/src/tfjs-core/src/ops/loss_ops_utils.ts", "../../tfjs/src/tfjs-core/src/ops/losses/compute_weighted_loss.ts", "../../tfjs/src/tfjs-core/src/ops/losses/absolute_difference.ts", "../../tfjs/src/tfjs-core/src/ops/losses/cosine_distance.ts", "../../tfjs/src/tfjs-core/src/ops/losses/hinge_loss.ts", "../../tfjs/src/tfjs-core/src/ops/losses/huber_loss.ts", "../../tfjs/src/tfjs-core/src/ops/losses/log_loss.ts", "../../tfjs/src/tfjs-core/src/ops/losses/mean_squared_error.ts", "../../tfjs/src/tfjs-core/src/ops/losses/sigmoid_cross_entropy.ts", "../../tfjs/src/tfjs-core/src/ops/losses/softmax_cross_entropy.ts", "../../tfjs/src/tfjs-core/src/ops/sparse/sparse_fill_empty_rows.ts", "../../tfjs/src/tfjs-core/src/ops/sparse/sparse_reshape.ts", "../../tfjs/src/tfjs-core/src/ops/sparse/sparse_segment_mean.ts", "../../tfjs/src/tfjs-core/src/ops/sparse/sparse_segment_sum.ts", "../../tfjs/src/tfjs-core/src/ops/string/string_n_grams.ts", "../../tfjs/src/tfjs-core/src/ops/string/string_split.ts", "../../tfjs/src/tfjs-core/src/ops/string/string_to_hash_bucket_fast.ts", "../../tfjs/src/tfjs-core/src/ops/ops.ts", "../../tfjs/src/tfjs-core/src/optimizers/optimizer.ts", "../../tfjs/src/tfjs-core/src/optimizers/adadelta_optimizer.ts", "../../tfjs/src/tfjs-core/src/optimizers/adagrad_optimizer.ts", "../../tfjs/src/tfjs-core/src/optimizers/adam_optimizer.ts", "../../tfjs/src/tfjs-core/src/optimizers/adamax_optimizer.ts", "../../tfjs/src/tfjs-core/src/optimizers/sgd_optimizer.ts", "../../tfjs/src/tfjs-core/src/optimizers/momentum_optimizer.ts", "../../tfjs/src/tfjs-core/src/optimizers/rmsprop_optimizer.ts", "../../tfjs/src/tfjs-core/src/tensor_types.ts", "../../tfjs/src/tfjs-core/src/optimizers/optimizer_constructors.ts", "../../tfjs/src/tfjs-core/src/train.ts", "../../tfjs/src/tfjs-core/src/platforms/platform.ts", "../../tfjs/src/tfjs-core/src/browser_util.ts", "../../tfjs/src/tfjs-core/src/backends/backend_util.ts", "../../tfjs/src/tfjs-core/src/ops/concat_util.ts", "../../tfjs/src/tfjs-core/src/ops/reduce_util.ts", "../../tfjs/src/tfjs-core/src/ops/rotate_util.ts", "../../tfjs/src/tfjs-core/src/ops/array_ops_util.ts", "../../tfjs/src/tfjs-core/src/ops/selu_util.ts", "../../tfjs/src/tfjs-core/src/ops/erf_util.ts", "../../tfjs/src/tfjs-core/src/backends/complex_util.ts", "../../tfjs/src/tfjs-core/src/backends/einsum_util.ts", "../../tfjs/src/tfjs-core/src/ops/split_util.ts", "../../tfjs/src/tfjs-core/src/ops/segment_util.ts", "../../tfjs/src/tfjs-core/src/backends/kernel_impls.ts", "../../tfjs/src/tfjs-core/src/base.ts", "../../tfjs/src/tfjs-core/src/index.ts", "../../tfjs/src/tfjs-core/src/gradients/Abs_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Acos_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Acosh_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Add_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/AddN_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/ArgMax_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/ArgMin_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Asin_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Asinh_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Atan2_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Atan_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Atanh_grad.ts", "../../tfjs/src/tfjs-core/src/ops/avg_pool_3d_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/AvgPool3D_grad.ts", "../../tfjs/src/tfjs-core/src/ops/avg_pool_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/AvgPool_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/BatchMatMul_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/BatchToSpaceND_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/BroadcastTo_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Cast_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Ceil_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/ClipByValue_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/ComplexAbs_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Concat_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Conv2D_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Conv2DBackpropInput_grad.ts", "../../tfjs/src/tfjs-core/src/ops/conv3d_backprop_filter.ts", "../../tfjs/src/tfjs-core/src/gradients/Conv3D_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Cos_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Cosh_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Cumsum_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/DepthwiseConv2dNative_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Dilation2D_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Elu_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Erf_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Exp_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/ExpandDims_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Expm1_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Floor_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/FloorDiv_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/FusedBatchNorm_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/GatherV2_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/GreaterEqual_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Identity_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/IsFinite_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/IsInf_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/IsNan_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/LeakyRelu_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Log1p_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Log_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/LogSoftmax_grad.ts", "../../tfjs/src/tfjs-core/src/ops/local_response_normalization_backprop.ts", "../../tfjs/src/tfjs-core/src/gradients/LRN_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/min_max_grad_util.ts", "../../tfjs/src/tfjs-core/src/gradients/Max_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Maximum_grad.ts", "../../tfjs/src/tfjs-core/src/ops/max_pool_3d_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/MaxPool3D_grad.ts", "../../tfjs/src/tfjs-core/src/ops/max_pool_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/MaxPool_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Mean_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Min_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Minimum_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/MirrorPad_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Mod_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Multiply_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Neg_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/OneHot_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/OnesLike_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Pack_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/PadV2_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Pow_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Prelu_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/RealDiv_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Reciprocal_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Relu6_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Relu_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Reshape_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/ResizeBilinear_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/ResizeNearestNeighbor_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Reverse_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Round_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Rsqrt_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Select_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Selu_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Sigmoid_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Sign_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Sin_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Sinh_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Slice_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Softmax_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Softplus_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/SpaceToBatchND_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/SplitV_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Sqrt_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Square_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/SquaredDifference_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Step_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Sub_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Sum_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Tan_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Tanh_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Tile_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Transpose_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/Unpack_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/UnsortedSegmentSum_grad.ts", "../../tfjs/src/tfjs-core/src/gradients/ZerosLike_grad.ts", "../../tfjs/src/tfjs-core/src/register_all_gradients.ts", "../../tfjs/src/tfjs-layers/src/exports_constraints.ts", "../../tfjs/src/tfjs-layers/src/backend/common.ts", "../../tfjs/src/tfjs-layers/src/errors.ts", "../../tfjs/src/tfjs-layers/src/utils/generic_utils.ts", "../../tfjs/src/tfjs-layers/src/constraints.ts", "../../tfjs/src/tfjs-layers/src/exports_initializers.ts", "../../tfjs/src/tfjs-layers/src/keras_format/common.ts", "../../tfjs/src/tfjs-layers/src/common.ts", "../../tfjs/src/tfjs-layers/src/utils/math_utils.ts", "../../tfjs/src/tfjs-layers/src/backend/tfjs_backend.ts", "../../tfjs/src/tfjs-layers/src/keras_format/initializer_config.ts", "../../tfjs/src/tfjs-layers/src/initializers.ts", "../../tfjs/src/tfjs-layers/src/exports_layers.ts", "../../tfjs/src/tfjs-layers/src/backend/state.ts", "../../tfjs/src/tfjs-layers/src/utils/types_utils.ts", "../../tfjs/src/tfjs-layers/src/utils/variable_utils.ts", "../../tfjs/src/tfjs-layers/src/variables.ts", "../../tfjs/src/tfjs-layers/src/engine/topology.ts", "../../tfjs/src/tfjs-layers/src/engine/input_layer.ts", "../../tfjs/src/tfjs-layers/src/logs.ts", "../../tfjs/src/tfjs-layers/src/base_callbacks.ts", "../../tfjs/src/tfjs-layers/src/layers/serialization.ts", "../../tfjs/src/tfjs-layers/src/losses.ts", "../../tfjs/src/tfjs-layers/src/metrics.ts", "../../tfjs/src/tfjs-layers/src/optimizers.ts", "../../tfjs/src/tfjs-layers/src/user_defined_metadata.ts", "../../tfjs/src/tfjs-layers/src/utils/layer_utils.ts", "../../tfjs/src/tfjs-layers/src/utils/serialization_utils.ts", "../../tfjs/src/tfjs-layers/src/version.ts", "../../tfjs/src/tfjs-layers/src/engine/executor.ts", "../../tfjs/src/tfjs-layers/src/engine/container.ts", "../../tfjs/src/tfjs-layers/src/engine/training_utils.ts", "../../tfjs/src/tfjs-layers/src/engine/training_dataset.ts", "../../tfjs/src/tfjs-layers/src/engine/training_tensors.ts", "../../tfjs/src/tfjs-layers/src/engine/training.ts", "../../tfjs/src/tfjs-layers/src/models.ts", "../../tfjs/src/tfjs-layers/src/exports.ts", "../../tfjs/src/tfjs-layers/src/activations.ts", "../../tfjs/src/tfjs-layers/src/regularizers.ts", "../../tfjs/src/tfjs-layers/src/layers/advanced_activations.ts", "../../tfjs/src/tfjs-layers/src/utils/conv_utils.ts", "../../tfjs/src/tfjs-layers/src/layers/convolutional.ts", "../../tfjs/src/tfjs-layers/src/layers/convolutional_depthwise.ts", "../../tfjs/src/tfjs-layers/src/layers/recurrent.ts", "../../tfjs/src/tfjs-layers/src/layers/convolutional_recurrent.ts", "../../tfjs/src/tfjs-layers/src/layers/core.ts", "../../tfjs/src/tfjs-layers/src/layers/embeddings.ts", "../../tfjs/src/tfjs-layers/src/layers/merge.ts", "../../tfjs/src/tfjs-layers/src/layers/noise.ts", "../../tfjs/src/tfjs-layers/src/layers/normalization.ts", "../../tfjs/src/tfjs-layers/src/layers/padding.ts", "../../tfjs/src/tfjs-layers/src/layers/pooling.ts", "../../tfjs/src/tfjs-layers/src/layers/wrappers.ts", "../../tfjs/src/tfjs-layers/src/exports_metrics.ts", "../../tfjs/src/tfjs-layers/src/exports_models.ts", "../../tfjs/src/tfjs-layers/src/exports_regularizers.ts", "../../tfjs/src/tfjs-layers/src/callbacks.ts", "../../tfjs/src/tfjs-layers/src/index.ts", "../../tfjs/src/tfjs-converter/src/data/compiled_api.ts", "../../tfjs/src/tfjs-converter/src/operations/custom_op/register.ts", "../../tfjs/src/tfjs-converter/src/operations/executors/utils.ts", "../../tfjs/src/tfjs-converter/src/operations/op_list/arithmetic.js", "../../tfjs/src/tfjs-converter/src/operations/op_list/basic_math.js", "../../tfjs/src/tfjs-converter/src/operations/op_list/control.js", "../../tfjs/src/tfjs-converter/src/operations/op_list/convolution.js", "../../tfjs/src/tfjs-converter/src/operations/op_list/creation.js", "../../tfjs/src/tfjs-converter/src/operations/op_list/dynamic.js", "../../tfjs/src/tfjs-converter/src/operations/op_list/evaluation.js", "../../tfjs/src/tfjs-converter/src/operations/op_list/graph.js", "../../tfjs/src/tfjs-converter/src/operations/op_list/hash_table.js", "../../tfjs/src/tfjs-converter/src/operations/op_list/image.js", "../../tfjs/src/tfjs-converter/src/operations/op_list/logical.js", "../../tfjs/src/tfjs-converter/src/operations/op_list/matrices.js", "../../tfjs/src/tfjs-converter/src/operations/op_list/normalization.js", "../../tfjs/src/tfjs-converter/src/operations/op_list/reduction.js", "../../tfjs/src/tfjs-converter/src/operations/op_list/slice_join.js", "../../tfjs/src/tfjs-converter/src/operations/op_list/sparse.js", "../../tfjs/src/tfjs-converter/src/operations/op_list/spectral.js", "../../tfjs/src/tfjs-converter/src/operations/op_list/string.js", "../../tfjs/src/tfjs-converter/src/operations/op_list/transformation.js", "../../tfjs/src/tfjs-converter/src/operations/operation_mapper.ts", "../../tfjs/src/tfjs-converter/src/operations/custom_op/node_value_impl.ts", "../../tfjs/src/tfjs-core/src/ops/ops_for_converter.ts", "../../tfjs/src/tfjs-converter/src/operations/executors/arithmetic_executor.ts", "../../tfjs/src/tfjs-converter/src/operations/executors/basic_math_executor.ts", "../../tfjs/src/tfjs-converter/src/executor/tensor_utils.ts", "../../tfjs/src/tfjs-converter/src/executor/tensor_array.ts", "../../tfjs/src/tfjs-converter/src/executor/tensor_list.ts", "../../tfjs/src/tfjs-converter/src/operations/executors/control_executor.ts", "../../tfjs/src/tfjs-converter/src/operations/executors/convolution_executor.ts", "../../tfjs/src/tfjs-converter/src/operations/executors/creation_executor.ts", "../../tfjs/src/tfjs-converter/src/operations/executors/dynamic_executor.ts", "../../tfjs/src/tfjs-converter/src/operations/executors/evaluation_executor.ts", "../../tfjs/src/tfjs-converter/src/operations/executors/graph_executor.ts", "../../tfjs/src/tfjs-converter/src/executor/hash_table.ts", "../../tfjs/src/tfjs-converter/src/operations/executors/hash_table_executor.ts", "../../tfjs/src/tfjs-converter/src/operations/executors/image_executor.ts", "../../tfjs/src/tfjs-converter/src/operations/executors/logical_executor.ts", "../../tfjs/src/tfjs-converter/src/operations/executors/matrices_executor.ts", "../../tfjs/src/tfjs-converter/src/operations/executors/normalization_executor.ts", "../../tfjs/src/tfjs-converter/src/operations/executors/reduction_executor.ts", "../../tfjs/src/tfjs-converter/src/operations/executors/slice_join_executor.ts", "../../tfjs/src/tfjs-converter/src/operations/executors/sparse_executor.ts", "../../tfjs/src/tfjs-converter/src/operations/executors/spectral_executor.ts", "../../tfjs/src/tfjs-converter/src/operations/executors/string_executor.ts", "../../tfjs/src/tfjs-converter/src/operations/executors/transformation_executor.ts", "../../tfjs/src/tfjs-converter/src/operations/operation_executor.ts", "../../tfjs/src/tfjs-converter/src/executor/execution_context.ts", "../../tfjs/src/tfjs-converter/src/executor/model_analysis.ts", "../../tfjs/src/tfjs-converter/src/executor/graph_executor.ts", "../../tfjs/src/tfjs-converter/src/executor/resource_manager.ts", "../../tfjs/src/tfjs-converter/src/executor/graph_model.ts", "../../tfjs/src/tfjs-converter/src/operations/types.ts", "../../tfjs/src/tfjs-converter/src/version.ts", "../../tfjs/src/tfjs-converter/src/index.ts", "../../tfjs/src/tfjs-data/src/index.ts", "../../tfjs/src/tfjs-data/src/util/deep_map.ts", "../../tfjs/src/tfjs-data/src/util/deep_clone.ts", "../../tfjs/src/tfjs-data/src/util/ring_buffer.ts", "../../tfjs/src/tfjs-data/src/util/growing_ring_buffer.ts", "../../tfjs/src/tfjs-data/src/iterators/lazy_iterator.ts", "../../tfjs/src/tfjs-data/src/dataset.ts", "../../tfjs/src/tfjs-data/src/datasets/text_line_dataset.ts", "../../tfjs/src/tfjs-data/src/datasets/csv_dataset.ts", "../../tfjs/src/tfjs-data/src/iterators/microphone_iterator.ts", "../../tfjs/src/tfjs-data/src/iterators/webcam_iterator.ts", "../../tfjs/src/tfjs-data/src/datasource.ts", "../../tfjs/src/tfjs-data/src/iterators/string_iterator.ts", "../../tfjs/src/tfjs-data/src/iterators/byte_chunk_iterator.ts", "../../tfjs/src/tfjs-data/src/iterators/file_chunk_iterator.ts", "../../tfjs/src/tfjs-data/src/iterators/url_chunk_iterator.ts", "../../tfjs/src/tfjs-data/src/util/source_util.ts", "../../tfjs/src/tfjs-data/src/sources/file_data_source.ts", "../../tfjs/src/tfjs-data/src/sources/url_data_source.ts", "../../tfjs/src/tfjs-data/src/readers.ts", "../../tfjs/src/tfjs-data/src/types.ts", "../../tfjs/src/tfjs-data/src/version.ts", "../../tfjs/src/tfjs-backend-cpu/src/cpu_util.ts", "../../tfjs/src/tfjs-backend-cpu/src/backend_cpu.ts", "../../tfjs/src/tfjs-backend-cpu/src/shared.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Abs.ts", "../../tfjs/src/tfjs-backend-cpu/src/utils/binary_impl.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Complex.ts", "../../tfjs/src/tfjs-backend-cpu/src/utils/zeros_impl.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Identity.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Real.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Cast.ts", "../../tfjs/src/tfjs-backend-cpu/src/utils/binary_utils.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Add.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Bincount_impl.ts", "../../tfjs/src/tfjs-backend-cpu/src/utils/unary_impl.ts", "../../tfjs/src/tfjs-backend-cpu/src/utils/unary_utils.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Ceil.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Concat_impl.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Equal.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Exp.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Expm1.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Floor.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/GatherNd_Impl.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/GatherV2_impl.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Greater.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/GreaterEqual.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Less.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/LessEqual.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/LinSpace_impl.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Log.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Max_impl.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Maximum.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Minimum.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Multiply.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Neg.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/NotEqual.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Transpose_impl.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Transpose.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Prod.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Range_impl.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Rsqrt.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Sigmoid.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Slice.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/SparseFillEmptyRows_impl.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/SparseReshape_impl.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/SparseSegmentReduction_impl.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Sqrt.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/SquaredDifference.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/StridedSlice_impl.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/StringNGrams_impl.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/StringSplit_impl.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/StringToHashBucketFast_impl.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Sub.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Tile_impl.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/TopK_impl.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Unique_impl.ts", "../../tfjs/src/tfjs-backend-cpu/src/utils/binary_types.ts", "../../tfjs/src/tfjs-backend-cpu/src/version.ts", "../../tfjs/src/tfjs-backend-cpu/src/base.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Elu.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/LeakyRelu.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Prelu.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Relu.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Relu6.ts", "../../tfjs/src/tfjs-backend-cpu/src/utils/fused_utils.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Reshape.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/BatchMatMul.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/_FusedMatMul.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Acos.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Acosh.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/AddN.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/All.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Any.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/ArgMax.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/ArgMin.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Asin.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Asinh.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Atan.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Atan2.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Atanh.ts", "../../tfjs/src/tfjs-backend-cpu/src/utils/pool_utils.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/AvgPool.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/AvgPool3D.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/AvgPool3DGrad.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/AvgPoolGrad.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/BatchNorm.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/BatchToSpaceND.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Bincount.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/BroadcastArgs.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Clip.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/ComplexAbs.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Imag.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Concat.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Conv2D.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Conv2DBackpropFilter.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Conv2DBackpropInput.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Conv3D.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Conv3DBackpropFilterV2.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Conv3DBackpropInputV2.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Cos.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Cosh.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/CropAndResize.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Cumsum.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/DenseBincount.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/DepthToSpace.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/DepthwiseConv2dNative.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/DepthwiseConv2dNativeBackpropFilter.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/DepthwiseConv2dNativeBackpropInput.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Diag.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Dilation2D.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Dilation2DBackpropFilter.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Dilation2DBackpropInput.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Sum.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Einsum.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/EluGrad.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Erf.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/ExpandDims.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/RealDiv.ts", "../../tfjs/src/tfjs-backend-cpu/src/utils/fft_utils.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/FFT.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Fill.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/FlipLeftRight.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/FloorDiv.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/FusedConv2D.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/FusedDepthwiseConv2D.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/GatherNd.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/GatherV2.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/IFFT.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/IsFinite.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/IsInf.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/IsNaN.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/LinSpace.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Log1p.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/LogicalAnd.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/LogicalNot.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/LogicalOr.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/LRN.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/LRNGrad.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Max.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/MaxPool.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/MaxPool3D.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/MaxPool3DGrad.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/MaxPoolGrad.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/MaxPoolWithArgmax_impl.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/MaxPoolWithArgmax.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Mean.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Min.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/MirrorPad.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Mod.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Softmax.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Multinomial.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/NonMaxSuppressionV3.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/NonMaxSuppressionV4.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/NonMaxSuppressionV5.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/OneHot.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/ZerosLike.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/OnesLike.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Pack.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/PadV2.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Pow.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Range.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Reciprocal.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/ResizeBilinear.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/ResizeBilinearGrad.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/ResizeNearestNeighbor.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/ResizeNearestNeighborGrad.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Reverse.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/RotateWithOffset.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Round.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Scatter_impl.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/ScatterNd.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Select.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Selu.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Sign.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Sin.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Sinh.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Softplus.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/SpaceToBatchND.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/SparseFillEmptyRows.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/SparseReshape.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/SparseSegmentMean.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/SparseSegmentSum.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/SparseToDense.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/SplitV.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Square.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Step.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/StridedSlice.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/StringNGrams.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/StringSplit.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/StringToHashBucketFast.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Tan.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Tanh.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Tile.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/TopK.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Transform.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Unique.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/Unpack.ts", "../../tfjs/src/tfjs-backend-cpu/src/kernels/UnsortedSegmentSum.ts", "../../tfjs/src/tfjs-backend-cpu/src/register_all_kernels.ts", "../../tfjs/src/tfjs-backend-cpu/src/index.ts", "../../tfjs/src/tfjs-backend-webgl/src/webgl_util.ts", "../../tfjs/src/tfjs-backend-webgl/src/canvas_util.ts", "../../tfjs/src/tfjs-backend-webgl/src/tex_util.ts", "../../tfjs/src/tfjs-backend-webgl/src/flags_webgl.ts", "../../tfjs/src/tfjs-backend-webgl/src/glsl_version.ts", "../../tfjs/src/tfjs-backend-webgl/src/shader_compiler_util.ts", "../../tfjs/src/tfjs-backend-webgl/src/shader_compiler.ts", "../../tfjs/src/tfjs-backend-webgl/src/gpgpu_math.ts", "../../tfjs/src/tfjs-backend-webgl/src/decode_matrix_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/decode_matrix_packed_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/encode_float_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/encode_float_packed_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/encode_matrix_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/encode_matrix_packed_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/gpgpu_util.ts", "../../tfjs/src/tfjs-backend-webgl/src/gpgpu_context.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernel_utils/shared.ts", "../../tfjs/src/tfjs-backend-webgl/src/packing_util.ts", "../../tfjs/src/tfjs-backend-webgl/src/pack_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/reshape_packed_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/texture_manager.ts", "../../tfjs/src/tfjs-backend-webgl/src/unaryop_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/unaryop_packed_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/unpack_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/backend_webgl.ts", "../../tfjs/src/tfjs-backend-webgl/src/version.ts", "../../tfjs/src/tfjs-backend-webgl/src/webgl.ts", "../../tfjs/src/tfjs-backend-webgl/src/base.ts", "../../tfjs/src/tfjs-backend-webgl/src/binaryop_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/binaryop_packed_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Identity.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Complex.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/LeakyRelu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Prelu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernel_utils/kernel_funcs_utils.ts", "../../tfjs/src/tfjs-backend-webgl/src/mulmat_packed_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/binaryop_complex_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Multiply.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernel_utils/reshape.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Reshape.ts", "../../tfjs/src/tfjs-backend-webgl/src/mean_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/reduce_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernel_utils/reduce.ts", "../../tfjs/src/tfjs-backend-webgl/src/transpose_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/transpose_packed_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Transpose_impl.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Sum_impl.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Sum.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Transpose.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/BatchMatMul_impl.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/_FusedMatMul.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Abs.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Acos.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Acosh.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Add.ts", "../../tfjs/src/tfjs-backend-webgl/src/addn_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/addn_packed_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/AddN.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/All.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Any.ts", "../../tfjs/src/tfjs-backend-webgl/src/argminmax_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/argminmax_packed_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernel_utils/arg_min_max.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/ArgMax.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/ArgMin.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Asin.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Asinh.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Atan.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Atan2.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Atanh.ts", "../../tfjs/src/tfjs-backend-webgl/src/pool_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/AvgPool.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/AvgPool3D.ts", "../../tfjs/src/tfjs-backend-webgl/src/avg_pool_backprop_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/AvgPool3DGrad.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/AvgPoolGrad.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/BatchMatMul.ts", "../../tfjs/src/tfjs-backend-webgl/src/batchnorm_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/batchnorm_packed_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/BatchNorm.ts", "../../tfjs/src/tfjs-backend-webgl/src/slice_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/slice_packed_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Slice.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/BatchToSpaceND.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Bincount.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/BroadcastArgs.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/NotEqual.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Real.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernel_utils/int.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Cast.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Ceil.ts", "../../tfjs/src/tfjs-backend-webgl/src/clip_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/clip_packed_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/ClipByValue.ts", "../../tfjs/src/tfjs-backend-webgl/src/complex_abs_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/ComplexAbs.ts", "../../tfjs/src/tfjs-backend-webgl/src/concat_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/concat_packed_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Imag.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Concat_impl.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Concat.ts", "../../tfjs/src/tfjs-backend-webgl/src/conv_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/im2col_packed_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Conv2D_impl.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Conv2D.ts", "../../tfjs/src/tfjs-backend-webgl/src/conv_backprop_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Conv2DBackpropFilter.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Conv2DBackpropInput.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Conv3D.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Conv3DBackpropFilterV2.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Conv3DBackpropInputV2.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Cos.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Cosh.ts", "../../tfjs/src/tfjs-backend-webgl/src/crop_and_resize_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/CropAndResize.ts", "../../tfjs/src/tfjs-backend-webgl/src/cumsum_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Cumsum.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/DenseBincount.ts", "../../tfjs/src/tfjs-backend-webgl/src/depth_to_space_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/DepthToSpace.ts", "../../tfjs/src/tfjs-backend-webgl/src/conv_gpu_depthwise.ts", "../../tfjs/src/tfjs-backend-webgl/src/conv_packed_gpu_depthwise.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/DepthwiseConv2dNative.ts", "../../tfjs/src/tfjs-backend-webgl/src/conv_backprop_gpu_depthwise.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/DepthwiseConv2dNativeBackpropFilter.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/DepthwiseConv2dNativeBackpropInput.ts", "../../tfjs/src/tfjs-backend-webgl/src/diag_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Diag.ts", "../../tfjs/src/tfjs-backend-webgl/src/dilation_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Dilation2D.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Einsum.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Elu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/EluGrad.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Equal.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Erf.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Exp.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/ExpandDims.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Expm1.ts", "../../tfjs/src/tfjs-backend-webgl/src/fft_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/FFT_impl.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/FFT.ts", "../../tfjs/src/tfjs-backend-webgl/src/fill_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Fill.ts", "../../tfjs/src/tfjs-backend-webgl/src/flip_left_right_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/FlipLeftRight.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Floor.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/FloorDiv.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/FromPixels_utils/from_pixels_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/FromPixels_utils/from_pixels_packed_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/FromPixels.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/FusedConv2D.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/FusedDepthwiseConv2D.ts", "../../tfjs/src/tfjs-backend-webgl/src/gather_nd_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/GatherNd.ts", "../../tfjs/src/tfjs-backend-webgl/src/gather_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/GatherV2.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Greater.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/GreaterEqual.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/IFFT.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/IsFinite.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/IsInf.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/IsNaN.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Less.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/LessEqual.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/LinSpace.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Log.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Log1p.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/LogicalAnd.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/LogicalNot.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/LogicalOr.ts", "../../tfjs/src/tfjs-backend-webgl/src/lrn_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/lrn_packed_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/LRN.ts", "../../tfjs/src/tfjs-backend-webgl/src/lrn_grad_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/LRNGrad.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Max_impl.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Max.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Maximum.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/MaxPool.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/MaxPool3D.ts", "../../tfjs/src/tfjs-backend-webgl/src/max_pool_backprop_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/MaxPool3DGrad.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/MaxPoolGrad.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/MaxPoolWithArgmax_impl.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/MaxPoolWithArgmax.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Mean_impl.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Mean.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Min.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Minimum.ts", "../../tfjs/src/tfjs-backend-webgl/src/mirror_pad_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/mirror_pad_packed_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/MirrorPad.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Mod.ts", "../../tfjs/src/tfjs-backend-webgl/src/multinomial_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/RealDiv.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Sub.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Softmax.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Multinomial.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Neg.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/NonMaxSuppressionV3.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/NonMaxSuppressionV4.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/NonMaxSuppressionV5.ts", "../../tfjs/src/tfjs-backend-webgl/src/onehot_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/OneHot.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/ZerosLike.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/OnesLike.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Pack.ts", "../../tfjs/src/tfjs-backend-webgl/src/pad_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/pad_packed_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/PadV2.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Pow.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Prod.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Range.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Reciprocal.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Relu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Relu6.ts", "../../tfjs/src/tfjs-backend-webgl/src/resize_bilinear_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/resize_bilinear_packed_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/ResizeBilinear.ts", "../../tfjs/src/tfjs-backend-webgl/src/resize_bilinear_backprop_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/ResizeBilinearGrad.ts", "../../tfjs/src/tfjs-backend-webgl/src/resize_nearest_neighbor_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/resize_nearest_neighbor_packed_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/ResizeNearestNeighbor.ts", "../../tfjs/src/tfjs-backend-webgl/src/resize_nearest_neighbor_backprop_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/ResizeNearestNeighborGrad.ts", "../../tfjs/src/tfjs-backend-webgl/src/reverse_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/reverse_packed_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Reverse.ts", "../../tfjs/src/tfjs-backend-webgl/src/rotate_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/RotateWithOffset.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Round.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Rsqrt.ts", "../../tfjs/src/tfjs-backend-webgl/src/scatter_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/ScatterNd.ts", "../../tfjs/src/tfjs-backend-webgl/src/select_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Select.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Selu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Sigmoid.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Sign.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Sin.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Sinh.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Softplus.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/SpaceToBatchND.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/SparseFillEmptyRows.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/SparseReshape.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/SparseSegmentMean.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/SparseSegmentSum.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/SparseToDense.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/SplitV.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Sqrt.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Square.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/SquaredDifference.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Step.ts", "../../tfjs/src/tfjs-backend-webgl/src/strided_slice_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/StridedSlice.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/StringNGrams.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/StringSplit.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/StringToHashBucketFast.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Tan.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Tanh.ts", "../../tfjs/src/tfjs-backend-webgl/src/tile_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Tile.ts", "../../tfjs/src/tfjs-backend-webgl/src/top_k_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/TopK.ts", "../../tfjs/src/tfjs-backend-webgl/src/transform_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Transform.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Unique.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/Unpack.ts", "../../tfjs/src/tfjs-backend-webgl/src/segment_gpu.ts", "../../tfjs/src/tfjs-backend-webgl/src/kernels/UnsortedSegmentSum.ts", "../../tfjs/src/tfjs-backend-webgl/src/register_all_kernels.ts", "../../tfjs/src/tfjs-backend-webgl/src/index.ts", "../../tfjs/src/tfjs-backend-webgpu/src/flags_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/shader_util.ts", "../../tfjs/src/tfjs-backend-webgpu/src/shader_preprocessor.ts", "../../tfjs/src/tfjs-backend-webgpu/src/webgpu_util.ts", "../../tfjs/src/tfjs-backend-webgpu/src/constants.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/binary_op_util.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/unary_op_util.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/activation_util.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/matmul_packed_vec4_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/matmul_packed_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/matmul_small_output_size_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Reshape.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/BatchMatMul_impl.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/_FusedMatMul.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/binary_op_complex_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/binary_op_shared_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/binary_op_vec4_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/binary_op_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/binary_ops.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Identity.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Complex.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/unary_op_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernel_utils/kernel_funcs_utils.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernel_utils/shared.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Abs.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Add.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/addn_packed_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/AddN.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/argminmax_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/transpose_shared_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/transpose_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Transpose.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/ArgMax.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/ArgMin.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/pool2d_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/pool_filtersizeone_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/AvgPool.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/BatchMatMul.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/slice_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Slice.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/BatchToSpaceND.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/NotEqual.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Real.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernel_utils/int.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Cast.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Ceil.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/clip_vec4_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/clip_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/ClipByValue.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/concat_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Imag.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Concat_impl.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Concat.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/im2col_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Conv2D_impl.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/conv2d_mm_vec4_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/conv2d_mm_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/conv2d_naive_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Conv2D.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/conv_backprop_mm_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/conv_backprop_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Conv2DBackpropInput.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Cos.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Cosh.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/crop_and_resize_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/CropAndResize.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/depth_to_space_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/DepthToSpace.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/depthwise_conv2d_3x3_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/depthwise_conv2d_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/DepthwiseConv2dNative.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Multiply.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/reduce_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernel_utils/reduce.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Sum.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Einsum.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Elu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Equal.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Exp.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/ExpandDims.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Expm1.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/fill_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Fill.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/flip_left_right_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/FlipLeftRight.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Floor.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/FloorDiv.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/webgpu_program.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/FromPixelsExternalImage.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/FromPixels.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/batchnorm_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/FusedBatchNorm.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/FusedConv2D.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/FusedDepthwiseConv2D.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/gather_nd_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/GatherNd.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/gather_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/GatherV2.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Greater.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/GreaterEqual.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Less.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/LessEqual.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Log.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/LogicalAnd.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/LogicalNot.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Max.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Maximum.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/MaxPool.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Mean.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Min.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Minimum.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/mirror_pad_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/MirrorPad.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Neg.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/NonMaxSuppressionV3.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/NonMaxSuppressionV5.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/ZerosLike.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/OnesLike.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Pack.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/pad_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/PadV2.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Pow.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Prelu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Prod.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Range.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/RealDiv.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Relu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Relu6.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/resize_bilinear_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/ResizeBilinear.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/resize_nearest_neighbor_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/ResizeNearestNeighbor.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/rotate_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/RotateWithOffset.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Rsqrt.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/scatter_optimized_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/ScatterNd.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/select_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Select.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Sigmoid.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Sin.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Sinh.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Sub.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Softmax.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/SpaceToBatchND.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/scatter_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/SparseToDense.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/SplitV.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Sqrt.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Square.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/SquaredDifference.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/strided_slice_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/StridedSlice.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/StringNGrams.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Tanh.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/tile_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Tile.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/top_k_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/TopK.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/transform_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Transform.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/Unpack.ts", "../../tfjs/src/tfjs-backend-webgpu/src/register_all_kernels.ts", "../../tfjs/src/tfjs-backend-webgpu/src/buffer_manager.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/FromPixels_utils/from_pixels_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/kernels/FromPixels_utils/from_pixels_import_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/backend_webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/webgpu.ts", "../../tfjs/src/tfjs-backend-webgpu/src/index.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/types.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/_FusedMatMul.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/unary_kernel.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Abs.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/binary_kernel.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Add.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/AddN.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Identity.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Transpose.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/kernel_utils.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/All.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Any.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/ArgMax.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/AvgPool.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Reshape.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/BatchMatMul.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernel_utils/shared.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Slice.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/BatchToSpaceND.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Cast.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Ceil.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/ClipByValue.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Concat.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Conv2D.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Conv2DBackpropInput.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Cos.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Cosh.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/CropAndResize.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Cumsum.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/DepthToSpace.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/DepthwiseConv2dNative.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Elu.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Equal.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Exp.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/ExpandDims.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Fill.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/FlipLeftRight.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Floor.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/FloorDiv.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/FusedBatchNorm.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/FusedConv2D.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/FusedDepthwiseConv2D.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/GatherNd.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/GatherV2.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Greater.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/GreaterEqual.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/LeakyRelu.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Less.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/LessEqual.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Log.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/LogicalAnd.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Max.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Maximum.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/MaxPool.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Mean.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Min.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Minimum.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/MirrorPad.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Multiply.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Neg.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/NonMaxSuppression_util.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/NonMaxSuppressionV3.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/NonMaxSuppressionV4.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/NonMaxSuppressionV5.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/NotEqual.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/OneHot.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/OnesLike.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Pack.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/PadV2.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Pow.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Prelu.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Prod.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Range.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/RealDiv.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Relu.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Relu6.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/ResizeBilinear.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Reverse.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/RotateWithOffset.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Round.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Rsqrt.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/ScatterNd.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Select.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Sigmoid.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Sin.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Softmax.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/SpaceToBatchND.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/SplitV.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Sqrt.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Square.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/SquaredDifference.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Step.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/StridedSlice.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Sub.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Sum.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Tan.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Tanh.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Tile.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/TopK.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Transform.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/Unpack.ts", "../../tfjs/src/tfjs-backend-wasm/src/kernels/ZerosLike.ts", "../../tfjs/src/tfjs-backend-wasm/src/register_all_kernels.ts", "../../tfjs/src/tfjs-backend-wasm/src/flags_wasm.ts", "../../tfjs/src/tfjs-backend-wasm/wasm-out/tfjs-backend-wasm-threaded-simd.worker.js", "../../tfjs/src/tfjs-backend-wasm/src/backend_wasm.ts", "../../tfjs/src/tfjs-backend-wasm/src/version.ts", "../../tfjs/src/tfjs-backend-wasm/src/base.ts", "../../tfjs/src/tfjs-backend-wasm/src/index.ts", "../../tfjs/.tfjs-browser.ts", "../tfjs/tf-custom.ts", "../src/image/imagefxshaders.ts", "../src/image/imagefx.ts", "../src/image/image.ts", "../src/util/env.ts", "../src/gear/gear-agegenderrace.ts", "../src/face/antispoof.ts", "../src/face/facemeshcoords.ts", "../src/face/facemeshutil.ts", "../src/face/blazeface.ts", "../src/body/blazeposecoords.ts", "../src/body/blazepose.ts", "../src/object/labels.ts", "../src/object/centernet.ts", "../src/body/efficientposecoords.ts", "../src/body/efficientpose.ts", "../src/gear/emotion.ts", "../src/face/iris.ts", "../src/face/facemesh.ts", "../src/face/faceres.ts", "../src/hand/handposeutil.ts", "../src/hand/handposeanchors.ts", "../src/hand/handposedetector.ts", "../src/hand/handposepipeline.ts", "../src/hand/fingerdef.ts", "../src/hand/fingergesture.ts", "../src/hand/fingerpose.ts", "../src/hand/handpose.ts", "../src/util/box.ts", "../src/hand/handtrack.ts", "../src/body/movenetcoords.ts", "../src/body/movenetfix.ts", "../src/body/movenet.ts", "../src/object/nanodet.ts", "../src/body/posenetutils.ts", "../src/body/posenet.ts", "../src/segmentation/segmentation.ts", "../src/models.ts", "../src/tfjs/humangl.ts", "../src/tfjs/backend.ts", "../src/util/draw.ts", "../src/face/angles.ts", "../src/face/face.ts", "../src/gesture/gesture.ts", "../src/util/interpolate.ts", "../src/face/match.ts", "../src/util/persons.ts", "../src/sample.ts", "../src/warmup.ts", "../src/human.ts"], - "sourcesContent": ["/**\n * Simple helper functions used accross codebase\n */\n\n// helper function: join two paths\nexport function join(folder: string, file: string): string {\n const separator = folder.endsWith('/') ? '' : '/';\n const skipJoin = file.startsWith('.') || file.startsWith('/') || file.startsWith('http:') || file.startsWith('https:') || file.startsWith('file:');\n const path = skipJoin ? `${file}` : `${folder}${separator}${file}`;\n if (!path.toLocaleLowerCase().includes('.json')) throw new Error(`modelpath error: ${path} expecting json file`);\n return path;\n}\n\n// helper function: wrapper around console output\nexport function log(...msg): void {\n const dt = new Date();\n const ts = `${dt.getHours().toString().padStart(2, '0')}:${dt.getMinutes().toString().padStart(2, '0')}:${dt.getSeconds().toString().padStart(2, '0')}.${dt.getMilliseconds().toString().padStart(3, '0')}`;\n // eslint-disable-next-line no-console\n if (msg) console.log(ts, 'Human:', ...msg);\n}\n\n// helper function: gets elapsed time on both browser and nodejs\nexport const now = () => {\n if (typeof performance !== 'undefined') return performance.now();\n return parseInt((Number(process.hrtime.bigint()) / 1000 / 1000).toString());\n};\n\n// helper function: checks current config validity\nexport function validate(defaults, config, parent = 'config', msgs: Array<{ reason: string, where: string, expected?: string }> = []) {\n for (const key of Object.keys(config)) {\n if (typeof config[key] === 'object') {\n validate(defaults[key], config[key], key, msgs);\n } else {\n const defined = defaults && (typeof defaults[key] !== 'undefined');\n if (!defined) msgs.push({ reason: 'unknown property', where: `${parent}.${key} = ${config[key]}` });\n const same = defaults && typeof defaults[key] === typeof config[key];\n if (defined && !same) msgs.push({ reason: 'property type mismatch', where: `${parent}.${key} = ${config[key]}`, expected: typeof defaults[key] });\n }\n // ok = ok && defined && same;\n }\n if (config.debug && parent === 'config' && msgs.length > 0) log('invalid configuration', msgs);\n return msgs;\n}\n\n// helper function: perform deep merge of multiple objects so it allows full inheriance with overrides\nexport function mergeDeep(...objects) {\n const isObject = (obj) => obj && typeof obj === 'object';\n return objects.reduce((prev, obj) => {\n Object.keys(obj || {}).forEach((key) => {\n const pVal = prev[key];\n const oVal = obj[key];\n if (Array.isArray(pVal) && Array.isArray(oVal)) prev[key] = pVal.concat(...oVal);\n else if (isObject(pVal) && isObject(oVal)) prev[key] = mergeDeep(pVal, oVal);\n else prev[key] = oVal;\n });\n return prev;\n }, {});\n}\n\n// helper function: return min and max from input array\nexport const minmax = (data: Array) => data.reduce((acc: Array, val) => {\n acc[0] = (acc[0] === undefined || val < acc[0]) ? val : acc[0];\n acc[1] = (acc[1] === undefined || val > acc[1]) ? val : acc[1];\n return acc;\n}, []);\n\n// helper function: async wait\nexport async function wait(time) {\n const waiting = new Promise((resolve) => setTimeout(() => resolve(true), time));\n await waiting;\n}\n", "/* eslint-disable indent */\n/* eslint-disable no-multi-spaces */\n\nexport interface GenericConfig {\n enabled: boolean,\n modelPath: string,\n skipFrames: number,\n skipTime: number,\n}\n\n/** Dectector part of face configuration */\nexport interface FaceDetectorConfig extends GenericConfig {\n rotation: boolean,\n maxDetected: number,\n minConfidence: number,\n iouThreshold: number,\n return: boolean,\n}\n\n/** Mesh part of face configuration */\nexport type FaceMeshConfig = GenericConfig\n\n/** Iris part of face configuration */\nexport type FaceIrisConfig = GenericConfig\n\n/** Description or face embedding part of face configuration\n * - also used by age and gender detection\n */\nexport interface FaceDescriptionConfig extends GenericConfig {\n minConfidence: number,\n}\n\n/** Emotion part of face configuration */\nexport interface FaceEmotionConfig extends GenericConfig {\n minConfidence: number,\n}\n\n/** Emotion part of face configuration */\nexport type FaceAntiSpoofConfig = GenericConfig\n\n/** Controlls and configures all face-specific options:\n * - face detection, face mesh detection, age, gender, emotion detection and face description\n *\n * Parameters:\n * - enabled: true/false\n * - modelPath: path for each of face models\n * - minConfidence: threshold for discarding a prediction\n * - iouThreshold: ammount of overlap between two detected objects before one object is removed\n * - maxDetected: maximum number of faces detected in the input, should be set to the minimum number for performance\n * - rotation: use calculated rotated face image or just box with rotation as-is, false means higher performance, but incorrect mesh mapping on higher face angles\n * - return: return extracted face as tensor for futher user processing, in which case user is reponsible for manually disposing the tensor\n*/\nexport interface FaceConfig {\n enabled: boolean,\n detector: Partial,\n mesh: Partial,\n iris: Partial,\n description: Partial,\n emotion: Partial,\n antispoof: Partial,\n}\n\n/** Controlls and configures all body detection specific options\n *\n * Parameters:\n * - enabled: true/false\n * - modelPath: body pose model, can be absolute path or relative to modelBasePath\n * - minConfidence: threshold for discarding a prediction\n * - maxDetected: maximum number of people detected in the input, should be set to the minimum number for performance\n * - detector: optional body detector\n *\n * `maxDetected` is valid for `posenet` and `movenet-multipose` as other models are single-pose only\n * `maxDetected` can be set to -1 to auto-detect based on number of detected faces\n *\n * Changing `modelPath` will change module responsible for hand detection and tracking\n * Allowed values are `posenet.json`, `blazepose.json`, `efficientpose.json`, `movenet-lightning.json`, `movenet-thunder.json`, `movenet-multipose.json`\n*/\nexport interface BodyConfig extends GenericConfig {\n maxDetected: number,\n minConfidence: number,\n detector?: {\n modelPath: string\n },\n}\n\n/** Controls and configures all hand detection specific options\n *\n * Parameters:\n * - enabled: true/false\n * - landmarks: detect hand landmarks or just hand boundary box\n * - modelPath: paths for hand detector and hand skeleton models, can be absolute path or relative to modelBasePath\n * - minConfidence: threshold for discarding a prediction\n * - iouThreshold: ammount of overlap between two detected objects before one object is removed\n * - maxDetected: maximum number of hands detected in the input, should be set to the minimum number for performance\n * - rotation: use best-guess rotated hand image or just box with rotation as-is, false means higher performance, but incorrect finger mapping if hand is inverted\n *\n * `maxDetected` can be set to -1 to auto-detect based on number of detected faces\n *\n * Changing `detector.modelPath` will change module responsible for hand detection and tracking\n * Allowed values are `handdetect.json` and `handtrack.json`\n*/\nexport interface HandConfig extends GenericConfig {\n rotation: boolean,\n minConfidence: number,\n iouThreshold: number,\n maxDetected: number,\n landmarks: boolean,\n detector: {\n modelPath?: string,\n },\n skeleton: {\n modelPath?: string,\n },\n}\n\n/** Controlls and configures all object detection specific options\n * - enabled: true/false\n * - modelPath: object detection model, can be absolute path or relative to modelBasePath\n * - minConfidence: minimum score that detection must have to return as valid object\n * - iouThreshold: ammount of overlap between two detected objects before one object is removed\n * - maxDetected: maximum number of detections to return\n *\n * Changing `modelPath` will change module responsible for hand detection and tracking\n * Allowed values are `mb3-centernet.json` and `nanodet.json`\n*/\nexport interface ObjectConfig extends GenericConfig {\n minConfidence: number,\n iouThreshold: number,\n maxDetected: number,\n}\n\n/** Controlls and configures all body segmentation module\n * removes background from input containing person\n * if segmentation is enabled it will run as preprocessing task before any other model\n * alternatively leave it disabled and use it on-demand using human.segmentation method which can\n * remove background or replace it with user-provided background\n *\n * - enabled: true/false\n * - modelPath: object detection model, can be absolute path or relative to modelBasePath\n * - blur: blur segmentation output by pixels for more realistic image\n *\n * Changing `modelPath` will change module responsible for hand detection and tracking\n * Allowed values are `selfie.json` and `meet.json`\n\n*/\nexport interface SegmentationConfig {\n enabled: boolean,\n modelPath: string,\n blur: number,\n}\n\n/** Run input through image filters before inference\n * - available only in Browser environments\n * - image filters run with near-zero latency as they are executed on the GPU using WebGL\n*/\nexport interface FilterConfig {\n enabled: boolean,\n /** Resize input width\n * - if both width and height are set to 0, there is no resizing\n * - if just one is set, second one is scaled automatically\n * - if both are set, values are used as-is\n */\n width: number,\n /** Resize input height\n * - if both width and height are set to 0, there is no resizing\n * - if just one is set, second one is scaled automatically\n * - if both are set, values are used as-is\n */\n height: number,\n /** Return processed canvas imagedata in result */\n return: boolean,\n /** Flip input as mirror image */\n flip: boolean,\n /** Range: -1 (darken) to 1 (lighten) */\n brightness: number,\n /** Range: -1 (reduce contrast) to 1 (increase contrast) */\n contrast: number,\n /** Range: 0 (no sharpening) to 1 (maximum sharpening) */\n sharpness: number,\n /** Range: 0 (no blur) to N (blur radius in pixels) */\n blur: number\n /** Range: -1 (reduce saturation) to 1 (increase saturation) */\n saturation: number,\n /** Range: 0 (no change) to 360 (hue rotation in degrees) */\n hue: number,\n /** Image negative */\n negative: boolean,\n /** Image sepia colors */\n sepia: boolean,\n /** Image vintage colors */\n vintage: boolean,\n /** Image kodachrome colors */\n kodachrome: boolean,\n /** Image technicolor colors */\n technicolor: boolean,\n /** Image polaroid camera effect */\n polaroid: boolean,\n /** Range: 0 (no pixelate) to N (number of pixels to pixelate) */\n pixelate: number,\n}\n\n/** Controlls gesture detection */\nexport interface GestureConfig {\n enabled: boolean,\n}\n\n/**\n * Configuration interface definition for **Human** library\n *\n * Contains all configurable parameters\n * @typedef Config\n *\n * Defaults: [config](https://github.com/vladmandic/human/blob/main/src/config.ts#L292)\n */\nexport interface Config {\n /** Backend used for TFJS operations\n * Valid build-in backends are:\n * - Browser: `cpu`, `wasm`, `webgl`, `humangl`\n * - NodeJS: `cpu`, `wasm`, `tensorflow`\n *\n * Experimental:\n * - Browser: `webgpu` - requires custom build of `tfjs-backend-webgpu`\n *\n * Defaults: `humangl` for browser and `tensorflow` for nodejs\n */\n backend: '' | 'cpu' | 'wasm' | 'webgl' | 'humangl' | 'tensorflow' | 'webgpu',\n // backend: string;\n\n /** Path to *.wasm files if backend is set to `wasm`\n * - if not set, auto-detects to link to CDN `jsdelivr` when running in browser\n */\n wasmPath: string,\n\n /** Print debug statements to console */\n debug: boolean,\n\n /** Perform model loading and inference concurrently or sequentially */\n async: boolean,\n\n /** What to use for `human.warmup()`\n * - warmup pre-initializes all models for faster inference but can take significant time on startup\n */\n warmup: 'none' | 'face' | 'full' | 'body',\n // warmup: string;\n\n /** Base model path (typically starting with file://, http:// or https://) for all models\n * - individual modelPath values are relative to this path\n */\n modelBasePath: string,\n\n /** Cache sensitivity\n * - values 0..1 where 0.01 means reset cache if input changed more than 1%\n * - set to 0 to disable caching\n */\n cacheSensitivity: number;\n\n /** Internal Variable */\n skipFrame: boolean;\n\n /** Run input through image filters before inference\n * - image filters run with near-zero latency as they are executed on the GPU\n *\n * {@link FilterConfig}\n */\n filter: Partial,\n\n /** {@link GestureConfig} */\n gesture: Partial;\n\n /** {@link FaceConfig} */\n face: Partial,\n\n /** {@link BodyConfig} */\n body: Partial,\n\n /** {@link HandConfig} */\n hand: Partial,\n\n /** {@link ObjectConfig} */\n object: Partial,\n\n /** {@link SegmentationConfig} */\n segmentation: Partial,\n}\n\n/**\n * [See all default Config values...](https://github.com/vladmandic/human/blob/main/src/config.ts#L244)\n *\n */\nconst config: Config = {\n backend: '', // select tfjs backend to use, leave empty to use default backend\n // for browser environments: 'webgl', 'wasm', 'cpu', or 'humangl' (which is a custom version of webgl)\n // for nodejs environments: 'tensorflow', 'wasm', 'cpu'\n // default set to `humangl` for browsers and `tensorflow` for nodejs\n modelBasePath: '', // base path for all models\n // default set to `../models/` for browsers and `file://models/` for nodejs\n wasmPath: '', // path for wasm binaries, only used for backend: wasm\n // default set to download from jsdeliv during Human class instantiation\n debug: true, // print additional status messages to console\n async: true, // execute enabled models in parallel\n warmup: 'full', // what to use for human.warmup(), can be 'none', 'face', 'full'\n // warmup pre-initializes all models for faster inference but can take\n // significant time on startup\n // only used for `webgl` and `humangl` backends\n cacheSensitivity: 0.75, // cache sensitivity\n // values 0..1 where 0.01 means reset cache if input changed more than 1%\n // set to 0 to disable caching\n skipFrame: false, // internal & dynamic\n filter: { // run input through image filters before inference\n // image filters run with near-zero latency as they are executed on the GPU\n enabled: true, // enable image pre-processing filters\n width: 0, // resize input width\n height: 0, // resize input height\n // if both width and height are set to 0, there is no resizing\n // if just one is set, second one is scaled automatically\n // if both are set, values are used as-is\n flip: false, // flip input as mirror image\n return: true, // return processed canvas imagedata in result\n brightness: 0, // range: -1 (darken) to 1 (lighten)\n contrast: 0, // range: -1 (reduce contrast) to 1 (increase contrast)\n sharpness: 0, // range: 0 (no sharpening) to 1 (maximum sharpening)\n blur: 0, // range: 0 (no blur) to N (blur radius in pixels)\n saturation: 0, // range: -1 (reduce saturation) to 1 (increase saturation)\n hue: 0, // range: 0 (no change) to 360 (hue rotation in degrees)\n negative: false, // image negative\n sepia: false, // image sepia colors\n vintage: false, // image vintage colors\n kodachrome: false, // image kodachrome colors\n technicolor: false, // image technicolor colors\n polaroid: false, // image polaroid camera effect\n pixelate: 0, // range: 0 (no pixelate) to N (number of pixels to pixelate)\n },\n\n gesture: {\n enabled: true, // enable gesture recognition based on model results\n },\n\n face: {\n enabled: true, // controls if specified modul is enabled\n // face.enabled is required for all face models:\n // detector, mesh, iris, age, gender, emotion\n // (note: module is not loaded until it is required)\n detector: {\n modelPath: 'blazeface.json', // detector model, can be absolute path or relative to modelBasePath\n rotation: true, // use best-guess rotated face image or just box with rotation as-is\n // false means higher performance, but incorrect mesh mapping if face angle is above 20 degrees\n // this parameter is not valid in nodejs\n maxDetected: 1, // maximum number of faces detected in the input\n // should be set to the minimum number for performance\n skipFrames: 11, // how many max frames to go without re-running the face bounding box detector\n // only used when cacheSensitivity is not zero\n skipTime: 2000, // how many ms to go without re-running the face bounding box detector\n // only used when cacheSensitivity is not zero\n minConfidence: 0.2, // threshold for discarding a prediction\n iouThreshold: 0.1, // ammount of overlap between two detected objects before one object is removed\n return: false, // return extracted face as tensor\n // in which case user is reponsible for disposing the tensor\n },\n\n mesh: {\n enabled: true,\n modelPath: 'facemesh.json', // facemesh model, can be absolute path or relative to modelBasePath\n },\n\n iris: {\n enabled: true,\n modelPath: 'iris.json', // face iris model\n // can be either absolute path or relative to modelBasePath\n },\n\n emotion: {\n enabled: true,\n minConfidence: 0.1, // threshold for discarding a prediction\n skipFrames: 12, // how max many frames to go without re-running the detector\n // only used when cacheSensitivity is not zero\n skipTime: 2000, // how many ms to go without re-running the face bounding box detector\n // only used when cacheSensitivity is not zero\n modelPath: 'emotion.json', // face emotion model, can be absolute path or relative to modelBasePath\n },\n\n description: {\n enabled: true, // to improve accuracy of face description extraction it is\n // recommended to enable detector.rotation and mesh.enabled\n modelPath: 'faceres.json', // face description model\n // can be either absolute path or relative to modelBasePath\n skipFrames: 13, // how many max frames to go without re-running the detector\n // only used when cacheSensitivity is not zero\n skipTime: 2000, // how many ms to go without re-running the face bounding box detector\n // only used when cacheSensitivity is not zero\n minConfidence: 0.1, // threshold for discarding a prediction\n },\n\n antispoof: {\n enabled: false,\n skipFrames: 14, // how max many frames to go without re-running the detector\n // only used when cacheSensitivity is not zero\n skipTime: 2000, // how many ms to go without re-running the face bounding box detector\n // only used when cacheSensitivity is not zero\n modelPath: 'antispoof.json', // face description model\n // can be either absolute path or relative to modelBasePath\n },\n },\n\n body: {\n enabled: true,\n modelPath: 'movenet-lightning.json', // body model, can be absolute path or relative to modelBasePath\n // can be 'posenet', 'blazepose', 'efficientpose', 'movenet-lightning', 'movenet-thunder'\n detector: {\n modelPath: '', // optional body detector\n },\n maxDetected: -1, // maximum number of people detected in the input\n // should be set to the minimum number for performance\n // only valid for posenet and movenet-multipose as other models detects single pose\n // set to -1 to autodetect based on number of detected faces\n minConfidence: 0.3, // threshold for discarding a prediction\n skipFrames: 1, // how many max frames to go without re-running the detector\n // only used when cacheSensitivity is not zero\n skipTime: 2000, // how many ms to go without re-running the face bounding box detector\n // only used when cacheSensitivity is not zero\n},\n\n hand: {\n enabled: true,\n rotation: true, // use best-guess rotated hand image or just box with rotation as-is\n // false means higher performance, but incorrect finger mapping if hand is inverted\n // only valid for `handdetect` variation\n skipFrames: 2, // how many max frames to go without re-running the hand bounding box detector\n // only used when cacheSensitivity is not zero\n skipTime: 2000, // how many ms to go without re-running the face bounding box detector\n // only used when cacheSensitivity is not zero\n minConfidence: 0.50, // threshold for discarding a prediction\n iouThreshold: 0.2, // ammount of overlap between two detected objects before one object is removed\n maxDetected: -1, // maximum number of hands detected in the input\n // should be set to the minimum number for performance\n // set to -1 to autodetect based on number of detected faces\n landmarks: true, // detect hand landmarks or just hand boundary box\n detector: {\n modelPath: 'handtrack.json', // hand detector model, can be absolute path or relative to modelBasePath\n // can be 'handdetect' or 'handtrack'\n },\n skeleton: {\n modelPath: 'handskeleton.json', // hand skeleton model, can be absolute path or relative to modelBasePath\n },\n },\n\n object: {\n enabled: false,\n modelPath: 'mb3-centernet.json', // experimental: object detection model, can be absolute path or relative to modelBasePath\n // can be 'mb3-centernet' or 'nanodet'\n minConfidence: 0.2, // threshold for discarding a prediction\n iouThreshold: 0.4, // ammount of overlap between two detected objects before one object is removed\n maxDetected: 10, // maximum number of objects detected in the input\n skipFrames: 15, // how many max frames to go without re-running the detector\n // only used when cacheSensitivity is not zero\n skipTime: 2000, // how many ms to go without re-running the face bounding box detector\n // only used when cacheSensitivity is not zero\n },\n\n segmentation: {\n enabled: false, // controlls and configures all body segmentation module\n // removes background from input containing person\n // if segmentation is enabled it will run as preprocessing task before any other model\n // alternatively leave it disabled and use it on-demand using human.segmentation method which can\n // remove background or replace it with user-provided background\n modelPath: 'selfie.json', // experimental: object detection model, can be absolute path or relative to modelBasePath\n // can be 'selfie' or 'meet'\n blur: 8, // blur segmentation output by n pixels for more realistic image\n },\n};\n\nexport { config as defaults };\n", "module.exports = Long;\r\n\r\n/**\r\n * wasm optimizations, to do native i64 multiplication and divide\r\n */\r\nvar wasm = null;\r\n\r\ntry {\r\n wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([\r\n 0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11\r\n ])), {}).exports;\r\n} catch (e) {\r\n // no wasm support :(\r\n}\r\n\r\n/**\r\n * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.\r\n * See the from* functions below for more convenient ways of constructing Longs.\r\n * @exports Long\r\n * @class A Long class for representing a 64 bit two's-complement integer value.\r\n * @param {number} low The low (signed) 32 bits of the long\r\n * @param {number} high The high (signed) 32 bits of the long\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @constructor\r\n */\r\nfunction Long(low, high, unsigned) {\r\n\r\n /**\r\n * The low 32 bits as a signed value.\r\n * @type {number}\r\n */\r\n this.low = low | 0;\r\n\r\n /**\r\n * The high 32 bits as a signed value.\r\n * @type {number}\r\n */\r\n this.high = high | 0;\r\n\r\n /**\r\n * Whether unsigned or not.\r\n * @type {boolean}\r\n */\r\n this.unsigned = !!unsigned;\r\n}\r\n\r\n// The internal representation of a long is the two given signed, 32-bit values.\r\n// We use 32-bit pieces because these are the size of integers on which\r\n// Javascript performs bit-operations. For operations like addition and\r\n// multiplication, we split each number into 16 bit pieces, which can easily be\r\n// multiplied within Javascript's floating-point representation without overflow\r\n// or change in sign.\r\n//\r\n// In the algorithms below, we frequently reduce the negative case to the\r\n// positive case by negating the input(s) and then post-processing the result.\r\n// Note that we must ALWAYS check specially whether those values are MIN_VALUE\r\n// (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as\r\n// a positive number, it overflows back into a negative). Not handling this\r\n// case would often result in infinite recursion.\r\n//\r\n// Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the from*\r\n// methods on which they depend.\r\n\r\n/**\r\n * An indicator used to reliably determine if an object is a Long or not.\r\n * @type {boolean}\r\n * @const\r\n * @private\r\n */\r\nLong.prototype.__isLong__;\r\n\r\nObject.defineProperty(Long.prototype, \"__isLong__\", { value: true });\r\n\r\n/**\r\n * @function\r\n * @param {*} obj Object\r\n * @returns {boolean}\r\n * @inner\r\n */\r\nfunction isLong(obj) {\r\n return (obj && obj[\"__isLong__\"]) === true;\r\n}\r\n\r\n/**\r\n * Tests if the specified object is a Long.\r\n * @function\r\n * @param {*} obj Object\r\n * @returns {boolean}\r\n */\r\nLong.isLong = isLong;\r\n\r\n/**\r\n * A cache of the Long representations of small integer values.\r\n * @type {!Object}\r\n * @inner\r\n */\r\nvar INT_CACHE = {};\r\n\r\n/**\r\n * A cache of the Long representations of small unsigned integer values.\r\n * @type {!Object}\r\n * @inner\r\n */\r\nvar UINT_CACHE = {};\r\n\r\n/**\r\n * @param {number} value\r\n * @param {boolean=} unsigned\r\n * @returns {!Long}\r\n * @inner\r\n */\r\nfunction fromInt(value, unsigned) {\r\n var obj, cachedObj, cache;\r\n if (unsigned) {\r\n value >>>= 0;\r\n if (cache = (0 <= value && value < 256)) {\r\n cachedObj = UINT_CACHE[value];\r\n if (cachedObj)\r\n return cachedObj;\r\n }\r\n obj = fromBits(value, (value | 0) < 0 ? -1 : 0, true);\r\n if (cache)\r\n UINT_CACHE[value] = obj;\r\n return obj;\r\n } else {\r\n value |= 0;\r\n if (cache = (-128 <= value && value < 128)) {\r\n cachedObj = INT_CACHE[value];\r\n if (cachedObj)\r\n return cachedObj;\r\n }\r\n obj = fromBits(value, value < 0 ? -1 : 0, false);\r\n if (cache)\r\n INT_CACHE[value] = obj;\r\n return obj;\r\n }\r\n}\r\n\r\n/**\r\n * Returns a Long representing the given 32 bit integer value.\r\n * @function\r\n * @param {number} value The 32 bit integer in question\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @returns {!Long} The corresponding Long value\r\n */\r\nLong.fromInt = fromInt;\r\n\r\n/**\r\n * @param {number} value\r\n * @param {boolean=} unsigned\r\n * @returns {!Long}\r\n * @inner\r\n */\r\nfunction fromNumber(value, unsigned) {\r\n if (isNaN(value))\r\n return unsigned ? UZERO : ZERO;\r\n if (unsigned) {\r\n if (value < 0)\r\n return UZERO;\r\n if (value >= TWO_PWR_64_DBL)\r\n return MAX_UNSIGNED_VALUE;\r\n } else {\r\n if (value <= -TWO_PWR_63_DBL)\r\n return MIN_VALUE;\r\n if (value + 1 >= TWO_PWR_63_DBL)\r\n return MAX_VALUE;\r\n }\r\n if (value < 0)\r\n return fromNumber(-value, unsigned).neg();\r\n return fromBits((value % TWO_PWR_32_DBL) | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);\r\n}\r\n\r\n/**\r\n * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.\r\n * @function\r\n * @param {number} value The number in question\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @returns {!Long} The corresponding Long value\r\n */\r\nLong.fromNumber = fromNumber;\r\n\r\n/**\r\n * @param {number} lowBits\r\n * @param {number} highBits\r\n * @param {boolean=} unsigned\r\n * @returns {!Long}\r\n * @inner\r\n */\r\nfunction fromBits(lowBits, highBits, unsigned) {\r\n return new Long(lowBits, highBits, unsigned);\r\n}\r\n\r\n/**\r\n * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is\r\n * assumed to use 32 bits.\r\n * @function\r\n * @param {number} lowBits The low 32 bits\r\n * @param {number} highBits The high 32 bits\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @returns {!Long} The corresponding Long value\r\n */\r\nLong.fromBits = fromBits;\r\n\r\n/**\r\n * @function\r\n * @param {number} base\r\n * @param {number} exponent\r\n * @returns {number}\r\n * @inner\r\n */\r\nvar pow_dbl = Math.pow; // Used 4 times (4*8 to 15+4)\r\n\r\n/**\r\n * @param {string} str\r\n * @param {(boolean|number)=} unsigned\r\n * @param {number=} radix\r\n * @returns {!Long}\r\n * @inner\r\n */\r\nfunction fromString(str, unsigned, radix) {\r\n if (str.length === 0)\r\n throw Error('empty string');\r\n if (str === \"NaN\" || str === \"Infinity\" || str === \"+Infinity\" || str === \"-Infinity\")\r\n return ZERO;\r\n if (typeof unsigned === 'number') {\r\n // For goog.math.long compatibility\r\n radix = unsigned,\r\n unsigned = false;\r\n } else {\r\n unsigned = !! unsigned;\r\n }\r\n radix = radix || 10;\r\n if (radix < 2 || 36 < radix)\r\n throw RangeError('radix');\r\n\r\n var p;\r\n if ((p = str.indexOf('-')) > 0)\r\n throw Error('interior hyphen');\r\n else if (p === 0) {\r\n return fromString(str.substring(1), unsigned, radix).neg();\r\n }\r\n\r\n // Do several (8) digits each time through the loop, so as to\r\n // minimize the calls to the very expensive emulated div.\r\n var radixToPower = fromNumber(pow_dbl(radix, 8));\r\n\r\n var result = ZERO;\r\n for (var i = 0; i < str.length; i += 8) {\r\n var size = Math.min(8, str.length - i),\r\n value = parseInt(str.substring(i, i + size), radix);\r\n if (size < 8) {\r\n var power = fromNumber(pow_dbl(radix, size));\r\n result = result.mul(power).add(fromNumber(value));\r\n } else {\r\n result = result.mul(radixToPower);\r\n result = result.add(fromNumber(value));\r\n }\r\n }\r\n result.unsigned = unsigned;\r\n return result;\r\n}\r\n\r\n/**\r\n * Returns a Long representation of the given string, written using the specified radix.\r\n * @function\r\n * @param {string} str The textual representation of the Long\r\n * @param {(boolean|number)=} unsigned Whether unsigned or not, defaults to signed\r\n * @param {number=} radix The radix in which the text is written (2-36), defaults to 10\r\n * @returns {!Long} The corresponding Long value\r\n */\r\nLong.fromString = fromString;\r\n\r\n/**\r\n * @function\r\n * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val\r\n * @param {boolean=} unsigned\r\n * @returns {!Long}\r\n * @inner\r\n */\r\nfunction fromValue(val, unsigned) {\r\n if (typeof val === 'number')\r\n return fromNumber(val, unsigned);\r\n if (typeof val === 'string')\r\n return fromString(val, unsigned);\r\n // Throws for non-objects, converts non-instanceof Long:\r\n return fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned);\r\n}\r\n\r\n/**\r\n * Converts the specified value to a Long using the appropriate from* function for its type.\r\n * @function\r\n * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val Value\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @returns {!Long}\r\n */\r\nLong.fromValue = fromValue;\r\n\r\n// NOTE: the compiler should inline these constant values below and then remove these variables, so there should be\r\n// no runtime penalty for these.\r\n\r\n/**\r\n * @type {number}\r\n * @const\r\n * @inner\r\n */\r\nvar TWO_PWR_16_DBL = 1 << 16;\r\n\r\n/**\r\n * @type {number}\r\n * @const\r\n * @inner\r\n */\r\nvar TWO_PWR_24_DBL = 1 << 24;\r\n\r\n/**\r\n * @type {number}\r\n * @const\r\n * @inner\r\n */\r\nvar TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;\r\n\r\n/**\r\n * @type {number}\r\n * @const\r\n * @inner\r\n */\r\nvar TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;\r\n\r\n/**\r\n * @type {number}\r\n * @const\r\n * @inner\r\n */\r\nvar TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;\r\n\r\n/**\r\n * @type {!Long}\r\n * @const\r\n * @inner\r\n */\r\nvar TWO_PWR_24 = fromInt(TWO_PWR_24_DBL);\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar ZERO = fromInt(0);\r\n\r\n/**\r\n * Signed zero.\r\n * @type {!Long}\r\n */\r\nLong.ZERO = ZERO;\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar UZERO = fromInt(0, true);\r\n\r\n/**\r\n * Unsigned zero.\r\n * @type {!Long}\r\n */\r\nLong.UZERO = UZERO;\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar ONE = fromInt(1);\r\n\r\n/**\r\n * Signed one.\r\n * @type {!Long}\r\n */\r\nLong.ONE = ONE;\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar UONE = fromInt(1, true);\r\n\r\n/**\r\n * Unsigned one.\r\n * @type {!Long}\r\n */\r\nLong.UONE = UONE;\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar NEG_ONE = fromInt(-1);\r\n\r\n/**\r\n * Signed negative one.\r\n * @type {!Long}\r\n */\r\nLong.NEG_ONE = NEG_ONE;\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar MAX_VALUE = fromBits(0xFFFFFFFF|0, 0x7FFFFFFF|0, false);\r\n\r\n/**\r\n * Maximum signed value.\r\n * @type {!Long}\r\n */\r\nLong.MAX_VALUE = MAX_VALUE;\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar MAX_UNSIGNED_VALUE = fromBits(0xFFFFFFFF|0, 0xFFFFFFFF|0, true);\r\n\r\n/**\r\n * Maximum unsigned value.\r\n * @type {!Long}\r\n */\r\nLong.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE;\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar MIN_VALUE = fromBits(0, 0x80000000|0, false);\r\n\r\n/**\r\n * Minimum signed value.\r\n * @type {!Long}\r\n */\r\nLong.MIN_VALUE = MIN_VALUE;\r\n\r\n/**\r\n * @alias Long.prototype\r\n * @inner\r\n */\r\nvar LongPrototype = Long.prototype;\r\n\r\n/**\r\n * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer.\r\n * @returns {number}\r\n */\r\nLongPrototype.toInt = function toInt() {\r\n return this.unsigned ? this.low >>> 0 : this.low;\r\n};\r\n\r\n/**\r\n * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa).\r\n * @returns {number}\r\n */\r\nLongPrototype.toNumber = function toNumber() {\r\n if (this.unsigned)\r\n return ((this.high >>> 0) * TWO_PWR_32_DBL) + (this.low >>> 0);\r\n return this.high * TWO_PWR_32_DBL + (this.low >>> 0);\r\n};\r\n\r\n/**\r\n * Converts the Long to a string written in the specified radix.\r\n * @param {number=} radix Radix (2-36), defaults to 10\r\n * @returns {string}\r\n * @override\r\n * @throws {RangeError} If `radix` is out of range\r\n */\r\nLongPrototype.toString = function toString(radix) {\r\n radix = radix || 10;\r\n if (radix < 2 || 36 < radix)\r\n throw RangeError('radix');\r\n if (this.isZero())\r\n return '0';\r\n if (this.isNegative()) { // Unsigned Longs are never negative\r\n if (this.eq(MIN_VALUE)) {\r\n // We need to change the Long value before it can be negated, so we remove\r\n // the bottom-most digit in this base and then recurse to do the rest.\r\n var radixLong = fromNumber(radix),\r\n div = this.div(radixLong),\r\n rem1 = div.mul(radixLong).sub(this);\r\n return div.toString(radix) + rem1.toInt().toString(radix);\r\n } else\r\n return '-' + this.neg().toString(radix);\r\n }\r\n\r\n // Do several (6) digits each time through the loop, so as to\r\n // minimize the calls to the very expensive emulated div.\r\n var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned),\r\n rem = this;\r\n var result = '';\r\n while (true) {\r\n var remDiv = rem.div(radixToPower),\r\n intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0,\r\n digits = intval.toString(radix);\r\n rem = remDiv;\r\n if (rem.isZero())\r\n return digits + result;\r\n else {\r\n while (digits.length < 6)\r\n digits = '0' + digits;\r\n result = '' + digits + result;\r\n }\r\n }\r\n};\r\n\r\n/**\r\n * Gets the high 32 bits as a signed integer.\r\n * @returns {number} Signed high bits\r\n */\r\nLongPrototype.getHighBits = function getHighBits() {\r\n return this.high;\r\n};\r\n\r\n/**\r\n * Gets the high 32 bits as an unsigned integer.\r\n * @returns {number} Unsigned high bits\r\n */\r\nLongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() {\r\n return this.high >>> 0;\r\n};\r\n\r\n/**\r\n * Gets the low 32 bits as a signed integer.\r\n * @returns {number} Signed low bits\r\n */\r\nLongPrototype.getLowBits = function getLowBits() {\r\n return this.low;\r\n};\r\n\r\n/**\r\n * Gets the low 32 bits as an unsigned integer.\r\n * @returns {number} Unsigned low bits\r\n */\r\nLongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() {\r\n return this.low >>> 0;\r\n};\r\n\r\n/**\r\n * Gets the number of bits needed to represent the absolute value of this Long.\r\n * @returns {number}\r\n */\r\nLongPrototype.getNumBitsAbs = function getNumBitsAbs() {\r\n if (this.isNegative()) // Unsigned Longs are never negative\r\n return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();\r\n var val = this.high != 0 ? this.high : this.low;\r\n for (var bit = 31; bit > 0; bit--)\r\n if ((val & (1 << bit)) != 0)\r\n break;\r\n return this.high != 0 ? bit + 33 : bit + 1;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value equals zero.\r\n * @returns {boolean}\r\n */\r\nLongPrototype.isZero = function isZero() {\r\n return this.high === 0 && this.low === 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value equals zero. This is an alias of {@link Long#isZero}.\r\n * @returns {boolean}\r\n */\r\nLongPrototype.eqz = LongPrototype.isZero;\r\n\r\n/**\r\n * Tests if this Long's value is negative.\r\n * @returns {boolean}\r\n */\r\nLongPrototype.isNegative = function isNegative() {\r\n return !this.unsigned && this.high < 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value is positive.\r\n * @returns {boolean}\r\n */\r\nLongPrototype.isPositive = function isPositive() {\r\n return this.unsigned || this.high >= 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value is odd.\r\n * @returns {boolean}\r\n */\r\nLongPrototype.isOdd = function isOdd() {\r\n return (this.low & 1) === 1;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value is even.\r\n * @returns {boolean}\r\n */\r\nLongPrototype.isEven = function isEven() {\r\n return (this.low & 1) === 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value equals the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.equals = function equals(other) {\r\n if (!isLong(other))\r\n other = fromValue(other);\r\n if (this.unsigned !== other.unsigned && (this.high >>> 31) === 1 && (other.high >>> 31) === 1)\r\n return false;\r\n return this.high === other.high && this.low === other.low;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value equals the specified's. This is an alias of {@link Long#equals}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.eq = LongPrototype.equals;\r\n\r\n/**\r\n * Tests if this Long's value differs from the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.notEquals = function notEquals(other) {\r\n return !this.eq(/* validates */ other);\r\n};\r\n\r\n/**\r\n * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.neq = LongPrototype.notEquals;\r\n\r\n/**\r\n * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.ne = LongPrototype.notEquals;\r\n\r\n/**\r\n * Tests if this Long's value is less than the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.lessThan = function lessThan(other) {\r\n return this.comp(/* validates */ other) < 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value is less than the specified's. This is an alias of {@link Long#lessThan}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.lt = LongPrototype.lessThan;\r\n\r\n/**\r\n * Tests if this Long's value is less than or equal the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.lessThanOrEqual = function lessThanOrEqual(other) {\r\n return this.comp(/* validates */ other) <= 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.lte = LongPrototype.lessThanOrEqual;\r\n\r\n/**\r\n * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.le = LongPrototype.lessThanOrEqual;\r\n\r\n/**\r\n * Tests if this Long's value is greater than the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.greaterThan = function greaterThan(other) {\r\n return this.comp(/* validates */ other) > 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value is greater than the specified's. This is an alias of {@link Long#greaterThan}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.gt = LongPrototype.greaterThan;\r\n\r\n/**\r\n * Tests if this Long's value is greater than or equal the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) {\r\n return this.comp(/* validates */ other) >= 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.gte = LongPrototype.greaterThanOrEqual;\r\n\r\n/**\r\n * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.ge = LongPrototype.greaterThanOrEqual;\r\n\r\n/**\r\n * Compares this Long's value with the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {number} 0 if they are the same, 1 if the this is greater and -1\r\n * if the given one is greater\r\n */\r\nLongPrototype.compare = function compare(other) {\r\n if (!isLong(other))\r\n other = fromValue(other);\r\n if (this.eq(other))\r\n return 0;\r\n var thisNeg = this.isNegative(),\r\n otherNeg = other.isNegative();\r\n if (thisNeg && !otherNeg)\r\n return -1;\r\n if (!thisNeg && otherNeg)\r\n return 1;\r\n // At this point the sign bits are the same\r\n if (!this.unsigned)\r\n return this.sub(other).isNegative() ? -1 : 1;\r\n // Both are positive if at least one is unsigned\r\n return (other.high >>> 0) > (this.high >>> 0) || (other.high === this.high && (other.low >>> 0) > (this.low >>> 0)) ? -1 : 1;\r\n};\r\n\r\n/**\r\n * Compares this Long's value with the specified's. This is an alias of {@link Long#compare}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {number} 0 if they are the same, 1 if the this is greater and -1\r\n * if the given one is greater\r\n */\r\nLongPrototype.comp = LongPrototype.compare;\r\n\r\n/**\r\n * Negates this Long's value.\r\n * @returns {!Long} Negated Long\r\n */\r\nLongPrototype.negate = function negate() {\r\n if (!this.unsigned && this.eq(MIN_VALUE))\r\n return MIN_VALUE;\r\n return this.not().add(ONE);\r\n};\r\n\r\n/**\r\n * Negates this Long's value. This is an alias of {@link Long#negate}.\r\n * @function\r\n * @returns {!Long} Negated Long\r\n */\r\nLongPrototype.neg = LongPrototype.negate;\r\n\r\n/**\r\n * Returns the sum of this and the specified Long.\r\n * @param {!Long|number|string} addend Addend\r\n * @returns {!Long} Sum\r\n */\r\nLongPrototype.add = function add(addend) {\r\n if (!isLong(addend))\r\n addend = fromValue(addend);\r\n\r\n // Divide each number into 4 chunks of 16 bits, and then sum the chunks.\r\n\r\n var a48 = this.high >>> 16;\r\n var a32 = this.high & 0xFFFF;\r\n var a16 = this.low >>> 16;\r\n var a00 = this.low & 0xFFFF;\r\n\r\n var b48 = addend.high >>> 16;\r\n var b32 = addend.high & 0xFFFF;\r\n var b16 = addend.low >>> 16;\r\n var b00 = addend.low & 0xFFFF;\r\n\r\n var c48 = 0, c32 = 0, c16 = 0, c00 = 0;\r\n c00 += a00 + b00;\r\n c16 += c00 >>> 16;\r\n c00 &= 0xFFFF;\r\n c16 += a16 + b16;\r\n c32 += c16 >>> 16;\r\n c16 &= 0xFFFF;\r\n c32 += a32 + b32;\r\n c48 += c32 >>> 16;\r\n c32 &= 0xFFFF;\r\n c48 += a48 + b48;\r\n c48 &= 0xFFFF;\r\n return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns the difference of this and the specified Long.\r\n * @param {!Long|number|string} subtrahend Subtrahend\r\n * @returns {!Long} Difference\r\n */\r\nLongPrototype.subtract = function subtract(subtrahend) {\r\n if (!isLong(subtrahend))\r\n subtrahend = fromValue(subtrahend);\r\n return this.add(subtrahend.neg());\r\n};\r\n\r\n/**\r\n * Returns the difference of this and the specified Long. This is an alias of {@link Long#subtract}.\r\n * @function\r\n * @param {!Long|number|string} subtrahend Subtrahend\r\n * @returns {!Long} Difference\r\n */\r\nLongPrototype.sub = LongPrototype.subtract;\r\n\r\n/**\r\n * Returns the product of this and the specified Long.\r\n * @param {!Long|number|string} multiplier Multiplier\r\n * @returns {!Long} Product\r\n */\r\nLongPrototype.multiply = function multiply(multiplier) {\r\n if (this.isZero())\r\n return ZERO;\r\n if (!isLong(multiplier))\r\n multiplier = fromValue(multiplier);\r\n\r\n // use wasm support if present\r\n if (wasm) {\r\n var low = wasm.mul(this.low,\r\n this.high,\r\n multiplier.low,\r\n multiplier.high);\r\n return fromBits(low, wasm.get_high(), this.unsigned);\r\n }\r\n\r\n if (multiplier.isZero())\r\n return ZERO;\r\n if (this.eq(MIN_VALUE))\r\n return multiplier.isOdd() ? MIN_VALUE : ZERO;\r\n if (multiplier.eq(MIN_VALUE))\r\n return this.isOdd() ? MIN_VALUE : ZERO;\r\n\r\n if (this.isNegative()) {\r\n if (multiplier.isNegative())\r\n return this.neg().mul(multiplier.neg());\r\n else\r\n return this.neg().mul(multiplier).neg();\r\n } else if (multiplier.isNegative())\r\n return this.mul(multiplier.neg()).neg();\r\n\r\n // If both longs are small, use float multiplication\r\n if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24))\r\n return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);\r\n\r\n // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.\r\n // We can skip products that would overflow.\r\n\r\n var a48 = this.high >>> 16;\r\n var a32 = this.high & 0xFFFF;\r\n var a16 = this.low >>> 16;\r\n var a00 = this.low & 0xFFFF;\r\n\r\n var b48 = multiplier.high >>> 16;\r\n var b32 = multiplier.high & 0xFFFF;\r\n var b16 = multiplier.low >>> 16;\r\n var b00 = multiplier.low & 0xFFFF;\r\n\r\n var c48 = 0, c32 = 0, c16 = 0, c00 = 0;\r\n c00 += a00 * b00;\r\n c16 += c00 >>> 16;\r\n c00 &= 0xFFFF;\r\n c16 += a16 * b00;\r\n c32 += c16 >>> 16;\r\n c16 &= 0xFFFF;\r\n c16 += a00 * b16;\r\n c32 += c16 >>> 16;\r\n c16 &= 0xFFFF;\r\n c32 += a32 * b00;\r\n c48 += c32 >>> 16;\r\n c32 &= 0xFFFF;\r\n c32 += a16 * b16;\r\n c48 += c32 >>> 16;\r\n c32 &= 0xFFFF;\r\n c32 += a00 * b32;\r\n c48 += c32 >>> 16;\r\n c32 &= 0xFFFF;\r\n c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;\r\n c48 &= 0xFFFF;\r\n return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns the product of this and the specified Long. This is an alias of {@link Long#multiply}.\r\n * @function\r\n * @param {!Long|number|string} multiplier Multiplier\r\n * @returns {!Long} Product\r\n */\r\nLongPrototype.mul = LongPrototype.multiply;\r\n\r\n/**\r\n * Returns this Long divided by the specified. The result is signed if this Long is signed or\r\n * unsigned if this Long is unsigned.\r\n * @param {!Long|number|string} divisor Divisor\r\n * @returns {!Long} Quotient\r\n */\r\nLongPrototype.divide = function divide(divisor) {\r\n if (!isLong(divisor))\r\n divisor = fromValue(divisor);\r\n if (divisor.isZero())\r\n throw Error('division by zero');\r\n\r\n // use wasm support if present\r\n if (wasm) {\r\n // guard against signed division overflow: the largest\r\n // negative number / -1 would be 1 larger than the largest\r\n // positive number, due to two's complement.\r\n if (!this.unsigned &&\r\n this.high === -0x80000000 &&\r\n divisor.low === -1 && divisor.high === -1) {\r\n // be consistent with non-wasm code path\r\n return this;\r\n }\r\n var low = (this.unsigned ? wasm.div_u : wasm.div_s)(\r\n this.low,\r\n this.high,\r\n divisor.low,\r\n divisor.high\r\n );\r\n return fromBits(low, wasm.get_high(), this.unsigned);\r\n }\r\n\r\n if (this.isZero())\r\n return this.unsigned ? UZERO : ZERO;\r\n var approx, rem, res;\r\n if (!this.unsigned) {\r\n // This section is only relevant for signed longs and is derived from the\r\n // closure library as a whole.\r\n if (this.eq(MIN_VALUE)) {\r\n if (divisor.eq(ONE) || divisor.eq(NEG_ONE))\r\n return MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE\r\n else if (divisor.eq(MIN_VALUE))\r\n return ONE;\r\n else {\r\n // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.\r\n var halfThis = this.shr(1);\r\n approx = halfThis.div(divisor).shl(1);\r\n if (approx.eq(ZERO)) {\r\n return divisor.isNegative() ? ONE : NEG_ONE;\r\n } else {\r\n rem = this.sub(divisor.mul(approx));\r\n res = approx.add(rem.div(divisor));\r\n return res;\r\n }\r\n }\r\n } else if (divisor.eq(MIN_VALUE))\r\n return this.unsigned ? UZERO : ZERO;\r\n if (this.isNegative()) {\r\n if (divisor.isNegative())\r\n return this.neg().div(divisor.neg());\r\n return this.neg().div(divisor).neg();\r\n } else if (divisor.isNegative())\r\n return this.div(divisor.neg()).neg();\r\n res = ZERO;\r\n } else {\r\n // The algorithm below has not been made for unsigned longs. It's therefore\r\n // required to take special care of the MSB prior to running it.\r\n if (!divisor.unsigned)\r\n divisor = divisor.toUnsigned();\r\n if (divisor.gt(this))\r\n return UZERO;\r\n if (divisor.gt(this.shru(1))) // 15 >>> 1 = 7 ; with divisor = 8 ; true\r\n return UONE;\r\n res = UZERO;\r\n }\r\n\r\n // Repeat the following until the remainder is less than other: find a\r\n // floating-point that approximates remainder / other *from below*, add this\r\n // into the result, and subtract it from the remainder. It is critical that\r\n // the approximate value is less than or equal to the real value so that the\r\n // remainder never becomes negative.\r\n rem = this;\r\n while (rem.gte(divisor)) {\r\n // Approximate the result of division. This may be a little greater or\r\n // smaller than the actual value.\r\n approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));\r\n\r\n // We will tweak the approximate result by changing it in the 48-th digit or\r\n // the smallest non-fractional digit, whichever is larger.\r\n var log2 = Math.ceil(Math.log(approx) / Math.LN2),\r\n delta = (log2 <= 48) ? 1 : pow_dbl(2, log2 - 48),\r\n\r\n // Decrease the approximation until it is smaller than the remainder. Note\r\n // that if it is too large, the product overflows and is negative.\r\n approxRes = fromNumber(approx),\r\n approxRem = approxRes.mul(divisor);\r\n while (approxRem.isNegative() || approxRem.gt(rem)) {\r\n approx -= delta;\r\n approxRes = fromNumber(approx, this.unsigned);\r\n approxRem = approxRes.mul(divisor);\r\n }\r\n\r\n // We know the answer can't be zero... and actually, zero would cause\r\n // infinite recursion since we would make no progress.\r\n if (approxRes.isZero())\r\n approxRes = ONE;\r\n\r\n res = res.add(approxRes);\r\n rem = rem.sub(approxRem);\r\n }\r\n return res;\r\n};\r\n\r\n/**\r\n * Returns this Long divided by the specified. This is an alias of {@link Long#divide}.\r\n * @function\r\n * @param {!Long|number|string} divisor Divisor\r\n * @returns {!Long} Quotient\r\n */\r\nLongPrototype.div = LongPrototype.divide;\r\n\r\n/**\r\n * Returns this Long modulo the specified.\r\n * @param {!Long|number|string} divisor Divisor\r\n * @returns {!Long} Remainder\r\n */\r\nLongPrototype.modulo = function modulo(divisor) {\r\n if (!isLong(divisor))\r\n divisor = fromValue(divisor);\r\n\r\n // use wasm support if present\r\n if (wasm) {\r\n var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(\r\n this.low,\r\n this.high,\r\n divisor.low,\r\n divisor.high\r\n );\r\n return fromBits(low, wasm.get_high(), this.unsigned);\r\n }\r\n\r\n return this.sub(this.div(divisor).mul(divisor));\r\n};\r\n\r\n/**\r\n * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.\r\n * @function\r\n * @param {!Long|number|string} divisor Divisor\r\n * @returns {!Long} Remainder\r\n */\r\nLongPrototype.mod = LongPrototype.modulo;\r\n\r\n/**\r\n * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.\r\n * @function\r\n * @param {!Long|number|string} divisor Divisor\r\n * @returns {!Long} Remainder\r\n */\r\nLongPrototype.rem = LongPrototype.modulo;\r\n\r\n/**\r\n * Returns the bitwise NOT of this Long.\r\n * @returns {!Long}\r\n */\r\nLongPrototype.not = function not() {\r\n return fromBits(~this.low, ~this.high, this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns the bitwise AND of this Long and the specified.\r\n * @param {!Long|number|string} other Other Long\r\n * @returns {!Long}\r\n */\r\nLongPrototype.and = function and(other) {\r\n if (!isLong(other))\r\n other = fromValue(other);\r\n return fromBits(this.low & other.low, this.high & other.high, this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns the bitwise OR of this Long and the specified.\r\n * @param {!Long|number|string} other Other Long\r\n * @returns {!Long}\r\n */\r\nLongPrototype.or = function or(other) {\r\n if (!isLong(other))\r\n other = fromValue(other);\r\n return fromBits(this.low | other.low, this.high | other.high, this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns the bitwise XOR of this Long and the given one.\r\n * @param {!Long|number|string} other Other Long\r\n * @returns {!Long}\r\n */\r\nLongPrototype.xor = function xor(other) {\r\n if (!isLong(other))\r\n other = fromValue(other);\r\n return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns this Long with bits shifted to the left by the given amount.\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\nLongPrototype.shiftLeft = function shiftLeft(numBits) {\r\n if (isLong(numBits))\r\n numBits = numBits.toInt();\r\n if ((numBits &= 63) === 0)\r\n return this;\r\n else if (numBits < 32)\r\n return fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);\r\n else\r\n return fromBits(0, this.low << (numBits - 32), this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns this Long with bits shifted to the left by the given amount. This is an alias of {@link Long#shiftLeft}.\r\n * @function\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\nLongPrototype.shl = LongPrototype.shiftLeft;\r\n\r\n/**\r\n * Returns this Long with bits arithmetically shifted to the right by the given amount.\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\nLongPrototype.shiftRight = function shiftRight(numBits) {\r\n if (isLong(numBits))\r\n numBits = numBits.toInt();\r\n if ((numBits &= 63) === 0)\r\n return this;\r\n else if (numBits < 32)\r\n return fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);\r\n else\r\n return fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns this Long with bits arithmetically shifted to the right by the given amount. This is an alias of {@link Long#shiftRight}.\r\n * @function\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\nLongPrototype.shr = LongPrototype.shiftRight;\r\n\r\n/**\r\n * Returns this Long with bits logically shifted to the right by the given amount.\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\nLongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) {\r\n if (isLong(numBits))\r\n numBits = numBits.toInt();\r\n numBits &= 63;\r\n if (numBits === 0)\r\n return this;\r\n else {\r\n var high = this.high;\r\n if (numBits < 32) {\r\n var low = this.low;\r\n return fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned);\r\n } else if (numBits === 32)\r\n return fromBits(high, 0, this.unsigned);\r\n else\r\n return fromBits(high >>> (numBits - 32), 0, this.unsigned);\r\n }\r\n};\r\n\r\n/**\r\n * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}.\r\n * @function\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\nLongPrototype.shru = LongPrototype.shiftRightUnsigned;\r\n\r\n/**\r\n * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}.\r\n * @function\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\nLongPrototype.shr_u = LongPrototype.shiftRightUnsigned;\r\n\r\n/**\r\n * Converts this Long to signed.\r\n * @returns {!Long} Signed long\r\n */\r\nLongPrototype.toSigned = function toSigned() {\r\n if (!this.unsigned)\r\n return this;\r\n return fromBits(this.low, this.high, false);\r\n};\r\n\r\n/**\r\n * Converts this Long to unsigned.\r\n * @returns {!Long} Unsigned long\r\n */\r\nLongPrototype.toUnsigned = function toUnsigned() {\r\n if (this.unsigned)\r\n return this;\r\n return fromBits(this.low, this.high, true);\r\n};\r\n\r\n/**\r\n * Converts this Long to its byte representation.\r\n * @param {boolean=} le Whether little or big endian, defaults to big endian\r\n * @returns {!Array.} Byte representation\r\n */\r\nLongPrototype.toBytes = function toBytes(le) {\r\n return le ? this.toBytesLE() : this.toBytesBE();\r\n};\r\n\r\n/**\r\n * Converts this Long to its little endian byte representation.\r\n * @returns {!Array.} Little endian byte representation\r\n */\r\nLongPrototype.toBytesLE = function toBytesLE() {\r\n var hi = this.high,\r\n lo = this.low;\r\n return [\r\n lo & 0xff,\r\n lo >>> 8 & 0xff,\r\n lo >>> 16 & 0xff,\r\n lo >>> 24 ,\r\n hi & 0xff,\r\n hi >>> 8 & 0xff,\r\n hi >>> 16 & 0xff,\r\n hi >>> 24\r\n ];\r\n};\r\n\r\n/**\r\n * Converts this Long to its big endian byte representation.\r\n * @returns {!Array.} Big endian byte representation\r\n */\r\nLongPrototype.toBytesBE = function toBytesBE() {\r\n var hi = this.high,\r\n lo = this.low;\r\n return [\r\n hi >>> 24 ,\r\n hi >>> 16 & 0xff,\r\n hi >>> 8 & 0xff,\r\n hi & 0xff,\r\n lo >>> 24 ,\r\n lo >>> 16 & 0xff,\r\n lo >>> 8 & 0xff,\r\n lo & 0xff\r\n ];\r\n};\r\n\r\n/**\r\n * Creates a Long from its byte representation.\r\n * @param {!Array.} bytes Byte representation\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @param {boolean=} le Whether little or big endian, defaults to big endian\r\n * @returns {Long} The corresponding Long value\r\n */\r\nLong.fromBytes = function fromBytes(bytes, unsigned, le) {\r\n return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned);\r\n};\r\n\r\n/**\r\n * Creates a Long from its little endian byte representation.\r\n * @param {!Array.} bytes Little endian byte representation\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @returns {Long} The corresponding Long value\r\n */\r\nLong.fromBytesLE = function fromBytesLE(bytes, unsigned) {\r\n return new Long(\r\n bytes[0] |\r\n bytes[1] << 8 |\r\n bytes[2] << 16 |\r\n bytes[3] << 24,\r\n bytes[4] |\r\n bytes[5] << 8 |\r\n bytes[6] << 16 |\r\n bytes[7] << 24,\r\n unsigned\r\n );\r\n};\r\n\r\n/**\r\n * Creates a Long from its big endian byte representation.\r\n * @param {!Array.} bytes Big endian byte representation\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @returns {Long} The corresponding Long value\r\n */\r\nLong.fromBytesBE = function fromBytesBE(bytes, unsigned) {\r\n return new Long(\r\n bytes[4] << 24 |\r\n bytes[5] << 16 |\r\n bytes[6] << 8 |\r\n bytes[7],\r\n bytes[0] << 24 |\r\n bytes[1] << 16 |\r\n bytes[2] << 8 |\r\n bytes[3],\r\n unsigned\r\n );\r\n};\r\n", "", "", "// A port of an algorithm by Johannes Baag\u00F8e , 2010\n// http://baagoe.com/en/RandomMusings/javascript/\n// https://github.com/nquinlan/better-random-numbers-for-javascript-mirror\n// Original work is under MIT license -\n\n// Copyright (C) 2010 by Johannes Baag\u00F8e \n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n\n\n(function(global, module, define) {\n\nfunction Alea(seed) {\n var me = this, mash = Mash();\n\n me.next = function() {\n var t = 2091639 * me.s0 + me.c * 2.3283064365386963e-10; // 2^-32\n me.s0 = me.s1;\n me.s1 = me.s2;\n return me.s2 = t - (me.c = t | 0);\n };\n\n // Apply the seeding algorithm from Baagoe.\n me.c = 1;\n me.s0 = mash(' ');\n me.s1 = mash(' ');\n me.s2 = mash(' ');\n me.s0 -= mash(seed);\n if (me.s0 < 0) { me.s0 += 1; }\n me.s1 -= mash(seed);\n if (me.s1 < 0) { me.s1 += 1; }\n me.s2 -= mash(seed);\n if (me.s2 < 0) { me.s2 += 1; }\n mash = null;\n}\n\nfunction copy(f, t) {\n t.c = f.c;\n t.s0 = f.s0;\n t.s1 = f.s1;\n t.s2 = f.s2;\n return t;\n}\n\nfunction impl(seed, opts) {\n var xg = new Alea(seed),\n state = opts && opts.state,\n prng = xg.next;\n prng.int32 = function() { return (xg.next() * 0x100000000) | 0; }\n prng.double = function() {\n return prng() + (prng() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53\n };\n prng.quick = prng;\n if (state) {\n if (typeof(state) == 'object') copy(state, xg);\n prng.state = function() { return copy(xg, {}); }\n }\n return prng;\n}\n\nfunction Mash() {\n var n = 0xefc8249d;\n\n var mash = function(data) {\n data = String(data);\n for (var i = 0; i < data.length; i++) {\n n += data.charCodeAt(i);\n var h = 0.02519603282416938 * n;\n n = h >>> 0;\n h -= n;\n h *= n;\n n = h >>> 0;\n h -= n;\n n += h * 0x100000000; // 2^32\n }\n return (n >>> 0) * 2.3283064365386963e-10; // 2^-32\n };\n\n return mash;\n}\n\n\nif (module && module.exports) {\n module.exports = impl;\n} else if (define && define.amd) {\n define(function() { return impl; });\n} else {\n this.alea = impl;\n}\n\n})(\n this,\n (typeof module) == 'object' && module, // present in node.js\n (typeof define) == 'function' && define // present with an AMD loader\n);\n\n\n", "// A Javascript implementaion of the \"xor128\" prng algorithm by\n// George Marsaglia. See http://www.jstatsoft.org/v08/i14/paper\n\n(function(global, module, define) {\n\nfunction XorGen(seed) {\n var me = this, strseed = '';\n\n me.x = 0;\n me.y = 0;\n me.z = 0;\n me.w = 0;\n\n // Set up generator function.\n me.next = function() {\n var t = me.x ^ (me.x << 11);\n me.x = me.y;\n me.y = me.z;\n me.z = me.w;\n return me.w ^= (me.w >>> 19) ^ t ^ (t >>> 8);\n };\n\n if (seed === (seed | 0)) {\n // Integer seed.\n me.x = seed;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (var k = 0; k < strseed.length + 64; k++) {\n me.x ^= strseed.charCodeAt(k) | 0;\n me.next();\n }\n}\n\nfunction copy(f, t) {\n t.x = f.x;\n t.y = f.y;\n t.z = f.z;\n t.w = f.w;\n return t;\n}\n\nfunction impl(seed, opts) {\n var xg = new XorGen(seed),\n state = opts && opts.state,\n prng = function() { return (xg.next() >>> 0) / 0x100000000; };\n prng.double = function() {\n do {\n var top = xg.next() >>> 11,\n bot = (xg.next() >>> 0) / 0x100000000,\n result = (top + bot) / (1 << 21);\n } while (result === 0);\n return result;\n };\n prng.int32 = xg.next;\n prng.quick = prng;\n if (state) {\n if (typeof(state) == 'object') copy(state, xg);\n prng.state = function() { return copy(xg, {}); }\n }\n return prng;\n}\n\nif (module && module.exports) {\n module.exports = impl;\n} else if (define && define.amd) {\n define(function() { return impl; });\n} else {\n this.xor128 = impl;\n}\n\n})(\n this,\n (typeof module) == 'object' && module, // present in node.js\n (typeof define) == 'function' && define // present with an AMD loader\n);\n\n\n", "// A Javascript implementaion of the \"xorwow\" prng algorithm by\n// George Marsaglia. See http://www.jstatsoft.org/v08/i14/paper\n\n(function(global, module, define) {\n\nfunction XorGen(seed) {\n var me = this, strseed = '';\n\n // Set up generator function.\n me.next = function() {\n var t = (me.x ^ (me.x >>> 2));\n me.x = me.y; me.y = me.z; me.z = me.w; me.w = me.v;\n return (me.d = (me.d + 362437 | 0)) +\n (me.v = (me.v ^ (me.v << 4)) ^ (t ^ (t << 1))) | 0;\n };\n\n me.x = 0;\n me.y = 0;\n me.z = 0;\n me.w = 0;\n me.v = 0;\n\n if (seed === (seed | 0)) {\n // Integer seed.\n me.x = seed;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (var k = 0; k < strseed.length + 64; k++) {\n me.x ^= strseed.charCodeAt(k) | 0;\n if (k == strseed.length) {\n me.d = me.x << 10 ^ me.x >>> 4;\n }\n me.next();\n }\n}\n\nfunction copy(f, t) {\n t.x = f.x;\n t.y = f.y;\n t.z = f.z;\n t.w = f.w;\n t.v = f.v;\n t.d = f.d;\n return t;\n}\n\nfunction impl(seed, opts) {\n var xg = new XorGen(seed),\n state = opts && opts.state,\n prng = function() { return (xg.next() >>> 0) / 0x100000000; };\n prng.double = function() {\n do {\n var top = xg.next() >>> 11,\n bot = (xg.next() >>> 0) / 0x100000000,\n result = (top + bot) / (1 << 21);\n } while (result === 0);\n return result;\n };\n prng.int32 = xg.next;\n prng.quick = prng;\n if (state) {\n if (typeof(state) == 'object') copy(state, xg);\n prng.state = function() { return copy(xg, {}); }\n }\n return prng;\n}\n\nif (module && module.exports) {\n module.exports = impl;\n} else if (define && define.amd) {\n define(function() { return impl; });\n} else {\n this.xorwow = impl;\n}\n\n})(\n this,\n (typeof module) == 'object' && module, // present in node.js\n (typeof define) == 'function' && define // present with an AMD loader\n);\n\n\n", "// A Javascript implementaion of the \"xorshift7\" algorithm by\n// Fran\u00E7ois Panneton and Pierre L'ecuyer:\n// \"On the Xorgshift Random Number Generators\"\n// http://saluc.engr.uconn.edu/refs/crypto/rng/panneton05onthexorshift.pdf\n\n(function(global, module, define) {\n\nfunction XorGen(seed) {\n var me = this;\n\n // Set up generator function.\n me.next = function() {\n // Update xor generator.\n var X = me.x, i = me.i, t, v, w;\n t = X[i]; t ^= (t >>> 7); v = t ^ (t << 24);\n t = X[(i + 1) & 7]; v ^= t ^ (t >>> 10);\n t = X[(i + 3) & 7]; v ^= t ^ (t >>> 3);\n t = X[(i + 4) & 7]; v ^= t ^ (t << 7);\n t = X[(i + 7) & 7]; t = t ^ (t << 13); v ^= t ^ (t << 9);\n X[i] = v;\n me.i = (i + 1) & 7;\n return v;\n };\n\n function init(me, seed) {\n var j, w, X = [];\n\n if (seed === (seed | 0)) {\n // Seed state array using a 32-bit integer.\n w = X[0] = seed;\n } else {\n // Seed state using a string.\n seed = '' + seed;\n for (j = 0; j < seed.length; ++j) {\n X[j & 7] = (X[j & 7] << 15) ^\n (seed.charCodeAt(j) + X[(j + 1) & 7] << 13);\n }\n }\n // Enforce an array length of 8, not all zeroes.\n while (X.length < 8) X.push(0);\n for (j = 0; j < 8 && X[j] === 0; ++j);\n if (j == 8) w = X[7] = -1; else w = X[j];\n\n me.x = X;\n me.i = 0;\n\n // Discard an initial 256 values.\n for (j = 256; j > 0; --j) {\n me.next();\n }\n }\n\n init(me, seed);\n}\n\nfunction copy(f, t) {\n t.x = f.x.slice();\n t.i = f.i;\n return t;\n}\n\nfunction impl(seed, opts) {\n if (seed == null) seed = +(new Date);\n var xg = new XorGen(seed),\n state = opts && opts.state,\n prng = function() { return (xg.next() >>> 0) / 0x100000000; };\n prng.double = function() {\n do {\n var top = xg.next() >>> 11,\n bot = (xg.next() >>> 0) / 0x100000000,\n result = (top + bot) / (1 << 21);\n } while (result === 0);\n return result;\n };\n prng.int32 = xg.next;\n prng.quick = prng;\n if (state) {\n if (state.x) copy(state, xg);\n prng.state = function() { return copy(xg, {}); }\n }\n return prng;\n}\n\nif (module && module.exports) {\n module.exports = impl;\n} else if (define && define.amd) {\n define(function() { return impl; });\n} else {\n this.xorshift7 = impl;\n}\n\n})(\n this,\n (typeof module) == 'object' && module, // present in node.js\n (typeof define) == 'function' && define // present with an AMD loader\n);\n\n", "// A Javascript implementaion of Richard Brent's Xorgens xor4096 algorithm.\n//\n// This fast non-cryptographic random number generator is designed for\n// use in Monte-Carlo algorithms. It combines a long-period xorshift\n// generator with a Weyl generator, and it passes all common batteries\n// of stasticial tests for randomness while consuming only a few nanoseconds\n// for each prng generated. For background on the generator, see Brent's\n// paper: \"Some long-period random number generators using shifts and xors.\"\n// http://arxiv.org/pdf/1004.3115v1.pdf\n//\n// Usage:\n//\n// var xor4096 = require('xor4096');\n// random = xor4096(1); // Seed with int32 or string.\n// assert.equal(random(), 0.1520436450538547); // (0, 1) range, 53 bits.\n// assert.equal(random.int32(), 1806534897); // signed int32, 32 bits.\n//\n// For nonzero numeric keys, this impelementation provides a sequence\n// identical to that by Brent's xorgens 3 implementaion in C. This\n// implementation also provides for initalizing the generator with\n// string seeds, or for saving and restoring the state of the generator.\n//\n// On Chrome, this prng benchmarks about 2.1 times slower than\n// Javascript's built-in Math.random().\n\n(function(global, module, define) {\n\nfunction XorGen(seed) {\n var me = this;\n\n // Set up generator function.\n me.next = function() {\n var w = me.w,\n X = me.X, i = me.i, t, v;\n // Update Weyl generator.\n me.w = w = (w + 0x61c88647) | 0;\n // Update xor generator.\n v = X[(i + 34) & 127];\n t = X[i = ((i + 1) & 127)];\n v ^= v << 13;\n t ^= t << 17;\n v ^= v >>> 15;\n t ^= t >>> 12;\n // Update Xor generator array state.\n v = X[i] = v ^ t;\n me.i = i;\n // Result is the combination.\n return (v + (w ^ (w >>> 16))) | 0;\n };\n\n function init(me, seed) {\n var t, v, i, j, w, X = [], limit = 128;\n if (seed === (seed | 0)) {\n // Numeric seeds initialize v, which is used to generates X.\n v = seed;\n seed = null;\n } else {\n // String seeds are mixed into v and X one character at a time.\n seed = seed + '\\0';\n v = 0;\n limit = Math.max(limit, seed.length);\n }\n // Initialize circular array and weyl value.\n for (i = 0, j = -32; j < limit; ++j) {\n // Put the unicode characters into the array, and shuffle them.\n if (seed) v ^= seed.charCodeAt((j + 32) % seed.length);\n // After 32 shuffles, take v as the starting w value.\n if (j === 0) w = v;\n v ^= v << 10;\n v ^= v >>> 15;\n v ^= v << 4;\n v ^= v >>> 13;\n if (j >= 0) {\n w = (w + 0x61c88647) | 0; // Weyl.\n t = (X[j & 127] ^= (v + w)); // Combine xor and weyl to init array.\n i = (0 == t) ? i + 1 : 0; // Count zeroes.\n }\n }\n // We have detected all zeroes; make the key nonzero.\n if (i >= 128) {\n X[(seed && seed.length || 0) & 127] = -1;\n }\n // Run the generator 512 times to further mix the state before using it.\n // Factoring this as a function slows the main generator, so it is just\n // unrolled here. The weyl generator is not advanced while warming up.\n i = 127;\n for (j = 4 * 128; j > 0; --j) {\n v = X[(i + 34) & 127];\n t = X[i = ((i + 1) & 127)];\n v ^= v << 13;\n t ^= t << 17;\n v ^= v >>> 15;\n t ^= t >>> 12;\n X[i] = v ^ t;\n }\n // Storing state as object members is faster than using closure variables.\n me.w = w;\n me.X = X;\n me.i = i;\n }\n\n init(me, seed);\n}\n\nfunction copy(f, t) {\n t.i = f.i;\n t.w = f.w;\n t.X = f.X.slice();\n return t;\n};\n\nfunction impl(seed, opts) {\n if (seed == null) seed = +(new Date);\n var xg = new XorGen(seed),\n state = opts && opts.state,\n prng = function() { return (xg.next() >>> 0) / 0x100000000; };\n prng.double = function() {\n do {\n var top = xg.next() >>> 11,\n bot = (xg.next() >>> 0) / 0x100000000,\n result = (top + bot) / (1 << 21);\n } while (result === 0);\n return result;\n };\n prng.int32 = xg.next;\n prng.quick = prng;\n if (state) {\n if (state.X) copy(state, xg);\n prng.state = function() { return copy(xg, {}); }\n }\n return prng;\n}\n\nif (module && module.exports) {\n module.exports = impl;\n} else if (define && define.amd) {\n define(function() { return impl; });\n} else {\n this.xor4096 = impl;\n}\n\n})(\n this, // window object or global\n (typeof module) == 'object' && module, // present in node.js\n (typeof define) == 'function' && define // present with an AMD loader\n);\n", "// A Javascript implementaion of the \"Tyche-i\" prng algorithm by\n// Samuel Neves and Filipe Araujo.\n// See https://eden.dei.uc.pt/~sneves/pubs/2011-snfa2.pdf\n\n(function(global, module, define) {\n\nfunction XorGen(seed) {\n var me = this, strseed = '';\n\n // Set up generator function.\n me.next = function() {\n var b = me.b, c = me.c, d = me.d, a = me.a;\n b = (b << 25) ^ (b >>> 7) ^ c;\n c = (c - d) | 0;\n d = (d << 24) ^ (d >>> 8) ^ a;\n a = (a - b) | 0;\n me.b = b = (b << 20) ^ (b >>> 12) ^ c;\n me.c = c = (c - d) | 0;\n me.d = (d << 16) ^ (c >>> 16) ^ a;\n return me.a = (a - b) | 0;\n };\n\n /* The following is non-inverted tyche, which has better internal\n * bit diffusion, but which is about 25% slower than tyche-i in JS.\n me.next = function() {\n var a = me.a, b = me.b, c = me.c, d = me.d;\n a = (me.a + me.b | 0) >>> 0;\n d = me.d ^ a; d = d << 16 ^ d >>> 16;\n c = me.c + d | 0;\n b = me.b ^ c; b = b << 12 ^ d >>> 20;\n me.a = a = a + b | 0;\n d = d ^ a; me.d = d = d << 8 ^ d >>> 24;\n me.c = c = c + d | 0;\n b = b ^ c;\n return me.b = (b << 7 ^ b >>> 25);\n }\n */\n\n me.a = 0;\n me.b = 0;\n me.c = 2654435769 | 0;\n me.d = 1367130551;\n\n if (seed === Math.floor(seed)) {\n // Integer seed.\n me.a = (seed / 0x100000000) | 0;\n me.b = seed | 0;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (var k = 0; k < strseed.length + 20; k++) {\n me.b ^= strseed.charCodeAt(k) | 0;\n me.next();\n }\n}\n\nfunction copy(f, t) {\n t.a = f.a;\n t.b = f.b;\n t.c = f.c;\n t.d = f.d;\n return t;\n};\n\nfunction impl(seed, opts) {\n var xg = new XorGen(seed),\n state = opts && opts.state,\n prng = function() { return (xg.next() >>> 0) / 0x100000000; };\n prng.double = function() {\n do {\n var top = xg.next() >>> 11,\n bot = (xg.next() >>> 0) / 0x100000000,\n result = (top + bot) / (1 << 21);\n } while (result === 0);\n return result;\n };\n prng.int32 = xg.next;\n prng.quick = prng;\n if (state) {\n if (typeof(state) == 'object') copy(state, xg);\n prng.state = function() { return copy(xg, {}); }\n }\n return prng;\n}\n\nif (module && module.exports) {\n module.exports = impl;\n} else if (define && define.amd) {\n define(function() { return impl; });\n} else {\n this.tychei = impl;\n}\n\n})(\n this,\n (typeof module) == 'object' && module, // present in node.js\n (typeof define) == 'function' && define // present with an AMD loader\n);\n\n\n", "", "/*\nCopyright 2019 David Bau.\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n*/\n\n(function (global, pool, math) {\n//\n// The following constants are related to IEEE 754 limits.\n//\n\nvar width = 256, // each RC4 output is 0 <= x < 256\n chunks = 6, // at least six RC4 outputs for each double\n digits = 52, // there are 52 significant digits in a double\n rngname = 'random', // rngname: name for Math.random and Math.seedrandom\n startdenom = math.pow(width, chunks),\n significance = math.pow(2, digits),\n overflow = significance * 2,\n mask = width - 1,\n nodecrypto; // node.js crypto module, initialized at the bottom.\n\n//\n// seedrandom()\n// This is the seedrandom function described above.\n//\nfunction seedrandom(seed, options, callback) {\n var key = [];\n options = (options == true) ? { entropy: true } : (options || {});\n\n // Flatten the seed string or build one from local entropy if needed.\n var shortseed = mixkey(flatten(\n options.entropy ? [seed, tostring(pool)] :\n (seed == null) ? autoseed() : seed, 3), key);\n\n // Use the seed to initialize an ARC4 generator.\n var arc4 = new ARC4(key);\n\n // This function returns a random double in [0, 1) that contains\n // randomness in every bit of the mantissa of the IEEE 754 value.\n var prng = function() {\n var n = arc4.g(chunks), // Start with a numerator n < 2 ^ 48\n d = startdenom, // and denominator d = 2 ^ 48.\n x = 0; // and no 'extra last byte'.\n while (n < significance) { // Fill up all significant digits by\n n = (n + x) * width; // shifting numerator and\n d *= width; // denominator and generating a\n x = arc4.g(1); // new least-significant-byte.\n }\n while (n >= overflow) { // To avoid rounding up, before adding\n n /= 2; // last byte, shift everything\n d /= 2; // right using integer math until\n x >>>= 1; // we have exactly the desired bits.\n }\n return (n + x) / d; // Form the number within [0, 1).\n };\n\n prng.int32 = function() { return arc4.g(4) | 0; }\n prng.quick = function() { return arc4.g(4) / 0x100000000; }\n prng.double = prng;\n\n // Mix the randomness into accumulated entropy.\n mixkey(tostring(arc4.S), pool);\n\n // Calling convention: what to return as a function of prng, seed, is_math.\n return (options.pass || callback ||\n function(prng, seed, is_math_call, state) {\n if (state) {\n // Load the arc4 state from the given state if it has an S array.\n if (state.S) { copy(state, arc4); }\n // Only provide the .state method if requested via options.state.\n prng.state = function() { return copy(arc4, {}); }\n }\n\n // If called as a method of Math (Math.seedrandom()), mutate\n // Math.random because that is how seedrandom.js has worked since v1.0.\n if (is_math_call) { math[rngname] = prng; return seed; }\n\n // Otherwise, it is a newer calling convention, so return the\n // prng directly.\n else return prng;\n })(\n prng,\n shortseed,\n 'global' in options ? options.global : (this == math),\n options.state);\n}\n\n//\n// ARC4\n//\n// An ARC4 implementation. The constructor takes a key in the form of\n// an array of at most (width) integers that should be 0 <= x < (width).\n//\n// The g(count) method returns a pseudorandom integer that concatenates\n// the next (count) outputs from ARC4. Its return value is a number x\n// that is in the range 0 <= x < (width ^ count).\n//\nfunction ARC4(key) {\n var t, keylen = key.length,\n me = this, i = 0, j = me.i = me.j = 0, s = me.S = [];\n\n // The empty key [] is treated as [0].\n if (!keylen) { key = [keylen++]; }\n\n // Set up S using the standard key scheduling algorithm.\n while (i < width) {\n s[i] = i++;\n }\n for (i = 0; i < width; i++) {\n s[i] = s[j = mask & (j + key[i % keylen] + (t = s[i]))];\n s[j] = t;\n }\n\n // The \"g\" method returns the next (count) outputs as one number.\n (me.g = function(count) {\n // Using instance members instead of closure state nearly doubles speed.\n var t, r = 0,\n i = me.i, j = me.j, s = me.S;\n while (count--) {\n t = s[i = mask & (i + 1)];\n r = r * width + s[mask & ((s[i] = s[j = mask & (j + t)]) + (s[j] = t))];\n }\n me.i = i; me.j = j;\n return r;\n // For robust unpredictability, the function call below automatically\n // discards an initial batch of values. This is called RC4-drop[256].\n // See http://google.com/search?q=rsa+fluhrer+response&btnI\n })(width);\n}\n\n//\n// copy()\n// Copies internal state of ARC4 to or from a plain object.\n//\nfunction copy(f, t) {\n t.i = f.i;\n t.j = f.j;\n t.S = f.S.slice();\n return t;\n};\n\n//\n// flatten()\n// Converts an object tree to nested arrays of strings.\n//\nfunction flatten(obj, depth) {\n var result = [], typ = (typeof obj), prop;\n if (depth && typ == 'object') {\n for (prop in obj) {\n try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {}\n }\n }\n return (result.length ? result : typ == 'string' ? obj : obj + '\\0');\n}\n\n//\n// mixkey()\n// Mixes a string seed into a key that is an array of integers, and\n// returns a shortened string seed that is equivalent to the result key.\n//\nfunction mixkey(seed, key) {\n var stringseed = seed + '', smear, j = 0;\n while (j < stringseed.length) {\n key[mask & j] =\n mask & ((smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++));\n }\n return tostring(key);\n}\n\n//\n// autoseed()\n// Returns an object for autoseeding, using window.crypto and Node crypto\n// module if available.\n//\nfunction autoseed() {\n try {\n var out;\n if (nodecrypto && (out = nodecrypto.randomBytes)) {\n // The use of 'out' to remember randomBytes makes tight minified code.\n out = out(width);\n } else {\n out = new Uint8Array(width);\n (global.crypto || global.msCrypto).getRandomValues(out);\n }\n return tostring(out);\n } catch (e) {\n var browser = global.navigator,\n plugins = browser && browser.plugins;\n return [+new Date, global, plugins, global.screen, tostring(pool)];\n }\n}\n\n//\n// tostring()\n// Converts an array of charcodes to a string\n//\nfunction tostring(a) {\n return String.fromCharCode.apply(0, a);\n}\n\n//\n// When seedrandom.js is loaded, we immediately mix a few bits\n// from the built-in RNG into the entropy pool. Because we do\n// not want to interfere with deterministic PRNG state later,\n// seedrandom will not call math.random on its own again after\n// initialization.\n//\nmixkey(math.random(), pool);\n\n//\n// Nodejs and AMD support: export the implementation as a module using\n// either convention.\n//\nif ((typeof module) == 'object' && module.exports) {\n module.exports = seedrandom;\n // When in node.js, try using crypto package for autoseeding.\n try {\n nodecrypto = require('crypto');\n } catch (ex) {}\n} else if ((typeof define) == 'function' && define.amd) {\n define(function() { return seedrandom; });\n} else {\n // When included as a plain script, set up Math.seedrandom global.\n math['seed' + rngname] = seedrandom;\n}\n\n\n// End anonymous scope, and pass initial values.\n})(\n // global: `self` in browsers (including strict mode and web workers),\n // otherwise `this` in Node and other environments\n (typeof self !== 'undefined') ? self : this,\n [], // pool: entropy pool starts empty\n Math // math: package containing random, pow, and seedrandom\n);\n", "// A library of seedable RNGs implemented in Javascript.\n//\n// Usage:\n//\n// var seedrandom = require('seedrandom');\n// var random = seedrandom(1); // or any seed.\n// var x = random(); // 0 <= x < 1. Every bit is random.\n// var x = random.quick(); // 0 <= x < 1. 32 bits of randomness.\n\n// alea, a 53-bit multiply-with-carry generator by Johannes Baag\u00F8e.\n// Period: ~2^116\n// Reported to pass all BigCrush tests.\nvar alea = require('./lib/alea');\n\n// xor128, a pure xor-shift generator by George Marsaglia.\n// Period: 2^128-1.\n// Reported to fail: MatrixRank and LinearComp.\nvar xor128 = require('./lib/xor128');\n\n// xorwow, George Marsaglia's 160-bit xor-shift combined plus weyl.\n// Period: 2^192-2^32\n// Reported to fail: CollisionOver, SimpPoker, and LinearComp.\nvar xorwow = require('./lib/xorwow');\n\n// xorshift7, by Fran\u00E7ois Panneton and Pierre L'ecuyer, takes\n// a different approach: it adds robustness by allowing more shifts\n// than Marsaglia's original three. It is a 7-shift generator\n// with 256 bits, that passes BigCrush with no systmatic failures.\n// Period 2^256-1.\n// No systematic BigCrush failures reported.\nvar xorshift7 = require('./lib/xorshift7');\n\n// xor4096, by Richard Brent, is a 4096-bit xor-shift with a\n// very long period that also adds a Weyl generator. It also passes\n// BigCrush with no systematic failures. Its long period may\n// be useful if you have many generators and need to avoid\n// collisions.\n// Period: 2^4128-2^32.\n// No systematic BigCrush failures reported.\nvar xor4096 = require('./lib/xor4096');\n\n// Tyche-i, by Samuel Neves and Filipe Araujo, is a bit-shifting random\n// number generator derived from ChaCha, a modern stream cipher.\n// https://eden.dei.uc.pt/~sneves/pubs/2011-snfa2.pdf\n// Period: ~2^127\n// No systematic BigCrush failures reported.\nvar tychei = require('./lib/tychei');\n\n// The original ARC4-based prng included in this library.\n// Period: ~2^1600\nvar sr = require('./seedrandom');\n\nsr.alea = alea;\nsr.xor128 = xor128;\nsr.xorwow = xorwow;\nsr.xorshift7 = xorshift7;\nsr.xor4096 = xor4096;\nsr.tychei = tychei;\n\nmodule.exports = sr;\n", "", "\nvar WasmBackendModuleThreadedSimd = (function() {\n var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;\n if (typeof __filename !== 'undefined') _scriptDir = _scriptDir || __filename;\n return (\nfunction(WasmBackendModuleThreadedSimd) {\n WasmBackendModuleThreadedSimd = WasmBackendModuleThreadedSimd || {};\n\nfunction GROWABLE_HEAP_I8(){if(wasmMemory.buffer!=buffer){updateGlobalBufferAndViews(wasmMemory.buffer)}return HEAP8}function GROWABLE_HEAP_U8(){if(wasmMemory.buffer!=buffer){updateGlobalBufferAndViews(wasmMemory.buffer)}return HEAPU8}function GROWABLE_HEAP_I32(){if(wasmMemory.buffer!=buffer){updateGlobalBufferAndViews(wasmMemory.buffer)}return HEAP32}function GROWABLE_HEAP_U32(){if(wasmMemory.buffer!=buffer){updateGlobalBufferAndViews(wasmMemory.buffer)}return HEAPU32}function GROWABLE_HEAP_F64(){if(wasmMemory.buffer!=buffer){updateGlobalBufferAndViews(wasmMemory.buffer)}return HEAPF64}var Module=typeof WasmBackendModuleThreadedSimd!==\"undefined\"?WasmBackendModuleThreadedSimd:{};var readyPromiseResolve,readyPromiseReject;Module[\"ready\"]=new Promise(function(resolve,reject){readyPromiseResolve=resolve;readyPromiseReject=reject});var moduleOverrides={};var key;for(key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var arguments_=[];var thisProgram=\"./this.program\";var quit_=function(status,toThrow){throw toThrow};var ENVIRONMENT_IS_WEB=false;var ENVIRONMENT_IS_WORKER=false;var ENVIRONMENT_IS_NODE=false;var ENVIRONMENT_IS_SHELL=false;ENVIRONMENT_IS_WEB=typeof window===\"object\";ENVIRONMENT_IS_WORKER=typeof importScripts===\"function\";ENVIRONMENT_IS_NODE=typeof process===\"object\"&&typeof process.versions===\"object\"&&typeof process.versions.node===\"string\";ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;var ENVIRONMENT_IS_PTHREAD=Module[\"ENVIRONMENT_IS_PTHREAD\"]||false;if(ENVIRONMENT_IS_PTHREAD){buffer=Module[\"buffer\"]}var scriptDirectory=\"\";function locateFile(path){if(Module[\"locateFile\"]){return Module[\"locateFile\"](path,scriptDirectory)}return scriptDirectory+path}var read_,readAsync,readBinary,setWindowTitle;var nodeFS;var nodePath;if(ENVIRONMENT_IS_NODE){if(ENVIRONMENT_IS_WORKER){scriptDirectory=require(\"path\").dirname(scriptDirectory)+\"/\"}else{scriptDirectory=__dirname+\"/\"}read_=function shell_read(filename,binary){if(!nodeFS)nodeFS=require(\"fs\");if(!nodePath)nodePath=require(\"path\");filename=nodePath[\"normalize\"](filename);return nodeFS[\"readFileSync\"](filename,binary?null:\"utf8\")};readBinary=function readBinary(filename){var ret=read_(filename,true);if(!ret.buffer){ret=new Uint8Array(ret)}assert(ret.buffer);return ret};if(process[\"argv\"].length>1){thisProgram=process[\"argv\"][1].replace(/\\\\/g,\"/\")}arguments_=process[\"argv\"].slice(2);process[\"on\"](\"uncaughtException\",function(ex){if(!(ex instanceof ExitStatus)){throw ex}});process[\"on\"](\"unhandledRejection\",abort);quit_=function(status){process[\"exit\"](status)};Module[\"inspect\"]=function(){return\"[Emscripten Module object]\"};var nodeWorkerThreads;try{nodeWorkerThreads=require(\"worker_threads\")}catch(e){console.error('The \"worker_threads\" module is not supported in this node.js build - perhaps a newer version is needed?');throw e}global.Worker=nodeWorkerThreads.Worker}else if(ENVIRONMENT_IS_SHELL){if(typeof read!=\"undefined\"){read_=function shell_read(f){return read(f)}}readBinary=function readBinary(f){var data;if(typeof readbuffer===\"function\"){return new Uint8Array(readbuffer(f))}data=read(f,\"binary\");assert(typeof data===\"object\");return data};if(typeof scriptArgs!=\"undefined\"){arguments_=scriptArgs}else if(typeof arguments!=\"undefined\"){arguments_=arguments}if(typeof quit===\"function\"){quit_=function(status){quit(status)}}if(typeof print!==\"undefined\"){if(typeof console===\"undefined\")console={};console.log=print;console.warn=console.error=typeof printErr!==\"undefined\"?printErr:print}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(typeof document!==\"undefined\"&&document.currentScript){scriptDirectory=document.currentScript.src}if(typeof _scriptDir !== \"undefined\" && _scriptDir){scriptDirectory=_scriptDir}if(scriptDirectory.indexOf(\"blob:\")!==0){scriptDirectory=scriptDirectory.substr(0,scriptDirectory.lastIndexOf(\"/\")+1)}else{scriptDirectory=\"\"}if(ENVIRONMENT_IS_NODE){read_=function shell_read(filename,binary){if(!nodeFS)nodeFS=require(\"fs\");if(!nodePath)nodePath=require(\"path\");filename=nodePath[\"normalize\"](filename);return nodeFS[\"readFileSync\"](filename,binary?null:\"utf8\")};readBinary=function readBinary(filename){var ret=read_(filename,true);if(!ret.buffer){ret=new Uint8Array(ret)}assert(ret.buffer);return ret}}else{read_=function(url){var xhr=new XMLHttpRequest;xhr.open(\"GET\",url,false);xhr.send(null);return xhr.responseText};if(ENVIRONMENT_IS_WORKER){readBinary=function(url){var xhr=new XMLHttpRequest;xhr.open(\"GET\",url,false);xhr.responseType=\"arraybuffer\";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=function(url,onload,onerror){var xhr=new XMLHttpRequest;xhr.open(\"GET\",url,true);xhr.responseType=\"arraybuffer\";xhr.onload=function(){if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}onerror()};xhr.onerror=onerror;xhr.send(null)}}setWindowTitle=function(title){document.title=title}}else{}if(ENVIRONMENT_IS_NODE){if(typeof performance===\"undefined\"){global.performance=require(\"perf_hooks\").performance}}var out=Module[\"print\"]||console.log.bind(console);var err=Module[\"printErr\"]||console.warn.bind(console);for(key in moduleOverrides){if(moduleOverrides.hasOwnProperty(key)){Module[key]=moduleOverrides[key]}}moduleOverrides=null;if(Module[\"arguments\"])arguments_=Module[\"arguments\"];if(Module[\"thisProgram\"])thisProgram=Module[\"thisProgram\"];if(Module[\"quit\"])quit_=Module[\"quit\"];function warnOnce(text){if(!warnOnce.shown)warnOnce.shown={};if(!warnOnce.shown[text]){warnOnce.shown[text]=1;err(text)}}var Atomics_load=Atomics.load;var Atomics_store=Atomics.store;var Atomics_compareExchange=Atomics.compareExchange;var wasmBinary;if(Module[\"wasmBinary\"])wasmBinary=Module[\"wasmBinary\"];var noExitRuntime=Module[\"noExitRuntime\"]||true;if(typeof WebAssembly!==\"object\"){abort(\"no native wasm support detected\")}var wasmMemory;var wasmModule;var ABORT=false;var EXITSTATUS;function assert(condition,text){if(!condition){abort(\"Assertion failed: \"+text)}}function getCFunc(ident){var func=Module[\"_\"+ident];assert(func,\"Cannot call unknown function \"+ident+\", make sure it is exported\");return func}function ccall(ident,returnType,argTypes,args,opts){var toC={\"string\":function(str){var ret=0;if(str!==null&&str!==undefined&&str!==0){var len=(str.length<<2)+1;ret=stackAlloc(len);stringToUTF8(str,ret,len)}return ret},\"array\":function(arr){var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType===\"string\")return UTF8ToString(ret);if(returnType===\"boolean\")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i=endIdx)){var u0=heap[idx++];if(!u0)return str;if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heap[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heap[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heap[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return str}function UTF8ToString(ptr,maxBytesToRead){return ptr?UTF8ArrayToString(GROWABLE_HEAP_U8(),ptr,maxBytesToRead):\"\"}function stringToUTF8Array(str,heap,outIdx,maxBytesToWrite){if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}}heap[outIdx]=0;return outIdx-startIdx}function stringToUTF8(str,outPtr,maxBytesToWrite){return stringToUTF8Array(str,GROWABLE_HEAP_U8(),outPtr,maxBytesToWrite)}function lengthBytesUTF8(str){var len=0;for(var i=0;i=55296&&u<=57343)u=65536+((u&1023)<<10)|str.charCodeAt(++i)&1023;if(u<=127)++len;else if(u<=2047)len+=2;else if(u<=65535)len+=3;else len+=4}return len}function writeArrayToMemory(array,buffer){GROWABLE_HEAP_I8().set(array,buffer)}function alignUp(x,multiple){if(x%multiple>0){x+=multiple-x%multiple}return x}var buffer,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateGlobalBufferAndViews(buf){buffer=buf;Module[\"HEAP8\"]=HEAP8=new Int8Array(buf);Module[\"HEAP16\"]=HEAP16=new Int16Array(buf);Module[\"HEAP32\"]=HEAP32=new Int32Array(buf);Module[\"HEAPU8\"]=HEAPU8=new Uint8Array(buf);Module[\"HEAPU16\"]=HEAPU16=new Uint16Array(buf);Module[\"HEAPU32\"]=HEAPU32=new Uint32Array(buf);Module[\"HEAPF32\"]=HEAPF32=new Float32Array(buf);Module[\"HEAPF64\"]=HEAPF64=new Float64Array(buf)}var INITIAL_MEMORY=Module[\"INITIAL_MEMORY\"]||16777216;if(ENVIRONMENT_IS_PTHREAD){wasmMemory=Module[\"wasmMemory\"];buffer=Module[\"buffer\"]}else{if(Module[\"wasmMemory\"]){wasmMemory=Module[\"wasmMemory\"]}else{wasmMemory=new WebAssembly.Memory({\"initial\":INITIAL_MEMORY/65536,\"maximum\":2147483648/65536,\"shared\":true});if(!(wasmMemory.buffer instanceof SharedArrayBuffer)){err(\"requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag\");if(ENVIRONMENT_IS_NODE){console.log(\"(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)\")}throw Error(\"bad memory\")}}}if(wasmMemory){buffer=wasmMemory.buffer}INITIAL_MEMORY=buffer.byteLength;updateGlobalBufferAndViews(buffer);var wasmTable;var __ATPRERUN__=[];var __ATINIT__=[];var __ATMAIN__=[];var __ATEXIT__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;var runtimeExited=false;if(!ENVIRONMENT_IS_PTHREAD)__ATINIT__.push({func:function(){___wasm_call_ctors()}});function preRun(){if(ENVIRONMENT_IS_PTHREAD)return;if(Module[\"preRun\"]){if(typeof Module[\"preRun\"]==\"function\")Module[\"preRun\"]=[Module[\"preRun\"]];while(Module[\"preRun\"].length){addOnPreRun(Module[\"preRun\"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;if(ENVIRONMENT_IS_PTHREAD)return;callRuntimeCallbacks(__ATINIT__)}function preMain(){if(ENVIRONMENT_IS_PTHREAD)return;callRuntimeCallbacks(__ATMAIN__)}function exitRuntime(){if(ENVIRONMENT_IS_PTHREAD)return;runtimeExited=true}function postRun(){if(ENVIRONMENT_IS_PTHREAD)return;if(Module[\"postRun\"]){if(typeof Module[\"postRun\"]==\"function\")Module[\"postRun\"]=[Module[\"postRun\"]];while(Module[\"postRun\"].length){addOnPostRun(Module[\"postRun\"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function addRunDependency(id){assert(!ENVIRONMENT_IS_PTHREAD,\"addRunDependency cannot be used in a pthread worker\");runDependencies++;if(Module[\"monitorRunDependencies\"]){Module[\"monitorRunDependencies\"](runDependencies)}}function removeRunDependency(id){runDependencies--;if(Module[\"monitorRunDependencies\"]){Module[\"monitorRunDependencies\"](runDependencies)}if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}Module[\"preloadedImages\"]={};Module[\"preloadedAudios\"]={};function abort(what){if(Module[\"onAbort\"]){Module[\"onAbort\"](what)}if(ENVIRONMENT_IS_PTHREAD)console.error(\"Pthread aborting at \"+(new Error).stack);what+=\"\";err(what);ABORT=true;EXITSTATUS=1;what=\"abort(\"+what+\"). Build with -s ASSERTIONS=1 for more info.\";var e=new WebAssembly.RuntimeError(what);readyPromiseReject(e);throw e}function hasPrefix(str,prefix){return String.prototype.startsWith?str.startsWith(prefix):str.indexOf(prefix)===0}var dataURIPrefix=\"data:application/octet-stream;base64,\";function isDataURI(filename){return hasPrefix(filename,dataURIPrefix)}var fileURIPrefix=\"file://\";function isFileURI(filename){return hasPrefix(filename,fileURIPrefix)}var wasmBinaryFile=\"tfjs-backend-wasm-threaded-simd.wasm\";if(!isDataURI(wasmBinaryFile)){wasmBinaryFile=locateFile(wasmBinaryFile)}function getBinary(file){try{if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}else{throw\"both async and sync fetching of the wasm failed\"}}catch(err){abort(err)}}function getBinaryPromise(){if(!wasmBinary&&(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)){if(typeof fetch===\"function\"&&!isFileURI(wasmBinaryFile)){return fetch(wasmBinaryFile,{credentials:\"same-origin\"}).then(function(response){if(!response[\"ok\"]){throw\"failed to load wasm binary file at '\"+wasmBinaryFile+\"'\"}return response[\"arrayBuffer\"]()}).catch(function(){return getBinary(wasmBinaryFile)})}else{if(readAsync){return new Promise(function(resolve,reject){readAsync(wasmBinaryFile,function(response){resolve(new Uint8Array(response))},reject)})}}}return Promise.resolve().then(function(){return getBinary(wasmBinaryFile)})}function createWasm(){var info={\"a\":asmLibraryArg};function receiveInstance(instance,module){var exports=instance.exports;Module[\"asm\"]=exports;wasmTable=Module[\"asm\"][\"kb\"];wasmModule=module;if(!ENVIRONMENT_IS_PTHREAD){var numWorkersToLoad=PThread.unusedWorkers.length;PThread.unusedWorkers.forEach(function(w){PThread.loadWasmModuleToWorker(w,function(){if(!--numWorkersToLoad)removeRunDependency(\"wasm-instantiate\")})})}}if(!ENVIRONMENT_IS_PTHREAD){addRunDependency(\"wasm-instantiate\")}function receiveInstantiatedSource(output){receiveInstance(output[\"instance\"],output[\"module\"])}function instantiateArrayBuffer(receiver){return getBinaryPromise().then(function(binary){return WebAssembly.instantiate(binary,info)}).then(receiver,function(reason){err(\"failed to asynchronously prepare wasm: \"+reason);abort(reason)})}function instantiateAsync(){if(!wasmBinary&&typeof WebAssembly.instantiateStreaming===\"function\"&&!isDataURI(wasmBinaryFile)&&!isFileURI(wasmBinaryFile)&&typeof fetch===\"function\"){return fetch(wasmBinaryFile,{credentials:\"same-origin\"}).then(function(response){var result=WebAssembly.instantiateStreaming(response,info);return result.then(receiveInstantiatedSource,function(reason){err(\"wasm streaming compile failed: \"+reason);err(\"falling back to ArrayBuffer instantiation\");return instantiateArrayBuffer(receiveInstantiatedSource)})})}else{return instantiateArrayBuffer(receiveInstantiatedSource)}}if(Module[\"instantiateWasm\"]){try{var exports=Module[\"instantiateWasm\"](info,receiveInstance);return exports}catch(e){err(\"Module.instantiateWasm callback failed with error: \"+e);return false}}instantiateAsync().catch(readyPromiseReject);return{}}var ASM_CONSTS={10072:function(){throw\"Canceled!\"},10090:function($0,$1){setTimeout(function(){__emscripten_do_dispatch_to_thread($0,$1)},0)}};function initPthreadsJS(){PThread.initRuntime()}function callRuntimeCallbacks(callbacks){while(callbacks.length>0){var callback=callbacks.shift();if(typeof callback==\"function\"){callback(Module);continue}var func=callback.func;if(typeof func===\"number\"){if(callback.arg===undefined){wasmTable.get(func)()}else{wasmTable.get(func)(callback.arg)}}else{func(callback.arg===undefined?null:callback.arg)}}}var ERRNO_CODES={EPERM:63,ENOENT:44,ESRCH:71,EINTR:27,EIO:29,ENXIO:60,E2BIG:1,ENOEXEC:45,EBADF:8,ECHILD:12,EAGAIN:6,EWOULDBLOCK:6,ENOMEM:48,EACCES:2,EFAULT:21,ENOTBLK:105,EBUSY:10,EEXIST:20,EXDEV:75,ENODEV:43,ENOTDIR:54,EISDIR:31,EINVAL:28,ENFILE:41,EMFILE:33,ENOTTY:59,ETXTBSY:74,EFBIG:22,ENOSPC:51,ESPIPE:70,EROFS:69,EMLINK:34,EPIPE:64,EDOM:18,ERANGE:68,ENOMSG:49,EIDRM:24,ECHRNG:106,EL2NSYNC:156,EL3HLT:107,EL3RST:108,ELNRNG:109,EUNATCH:110,ENOCSI:111,EL2HLT:112,EDEADLK:16,ENOLCK:46,EBADE:113,EBADR:114,EXFULL:115,ENOANO:104,EBADRQC:103,EBADSLT:102,EDEADLOCK:16,EBFONT:101,ENOSTR:100,ENODATA:116,ETIME:117,ENOSR:118,ENONET:119,ENOPKG:120,EREMOTE:121,ENOLINK:47,EADV:122,ESRMNT:123,ECOMM:124,EPROTO:65,EMULTIHOP:36,EDOTDOT:125,EBADMSG:9,ENOTUNIQ:126,EBADFD:127,EREMCHG:128,ELIBACC:129,ELIBBAD:130,ELIBSCN:131,ELIBMAX:132,ELIBEXEC:133,ENOSYS:52,ENOTEMPTY:55,ENAMETOOLONG:37,ELOOP:32,EOPNOTSUPP:138,EPFNOSUPPORT:139,ECONNRESET:15,ENOBUFS:42,EAFNOSUPPORT:5,EPROTOTYPE:67,ENOTSOCK:57,ENOPROTOOPT:50,ESHUTDOWN:140,ECONNREFUSED:14,EADDRINUSE:3,ECONNABORTED:13,ENETUNREACH:40,ENETDOWN:38,ETIMEDOUT:73,EHOSTDOWN:142,EHOSTUNREACH:23,EINPROGRESS:26,EALREADY:7,EDESTADDRREQ:17,EMSGSIZE:35,EPROTONOSUPPORT:66,ESOCKTNOSUPPORT:137,EADDRNOTAVAIL:4,ENETRESET:39,EISCONN:30,ENOTCONN:53,ETOOMANYREFS:141,EUSERS:136,EDQUOT:19,ESTALE:72,ENOTSUP:138,ENOMEDIUM:148,EILSEQ:25,EOVERFLOW:61,ECANCELED:11,ENOTRECOVERABLE:56,EOWNERDEAD:62,ESTRPIPE:135};function _emscripten_futex_wake(addr,count){if(addr<=0||addr>GROWABLE_HEAP_I8().length||addr&3!=0||count<0)return-28;if(count==0)return 0;if(count>=2147483647)count=Infinity;var mainThreadWaitAddress=Atomics.load(GROWABLE_HEAP_I32(),__emscripten_main_thread_futex>>2);var mainThreadWoken=0;if(mainThreadWaitAddress==addr){var loadedAddr=Atomics.compareExchange(GROWABLE_HEAP_I32(),__emscripten_main_thread_futex>>2,mainThreadWaitAddress,0);if(loadedAddr==mainThreadWaitAddress){--count;mainThreadWoken=1;if(count<=0)return 1}}var ret=Atomics.notify(GROWABLE_HEAP_I32(),addr>>2,count);if(ret>=0)return ret+mainThreadWoken;throw\"Atomics.notify returned an unexpected value \"+ret}Module[\"_emscripten_futex_wake\"]=_emscripten_futex_wake;function killThread(pthread_ptr){if(ENVIRONMENT_IS_PTHREAD)throw\"Internal Error! killThread() can only ever be called from main application thread!\";if(!pthread_ptr)throw\"Internal Error! Null pthread_ptr in killThread!\";GROWABLE_HEAP_I32()[pthread_ptr+12>>2]=0;var pthread=PThread.pthreads[pthread_ptr];pthread.worker.terminate();PThread.freeThreadData(pthread);PThread.runningWorkers.splice(PThread.runningWorkers.indexOf(pthread.worker),1);pthread.worker.pthread=undefined}function cancelThread(pthread_ptr){if(ENVIRONMENT_IS_PTHREAD)throw\"Internal Error! cancelThread() can only ever be called from main application thread!\";if(!pthread_ptr)throw\"Internal Error! Null pthread_ptr in cancelThread!\";var pthread=PThread.pthreads[pthread_ptr];pthread.worker.postMessage({\"cmd\":\"cancel\"})}function cleanupThread(pthread_ptr){if(ENVIRONMENT_IS_PTHREAD)throw\"Internal Error! cleanupThread() can only ever be called from main application thread!\";if(!pthread_ptr)throw\"Internal Error! Null pthread_ptr in cleanupThread!\";var pthread=PThread.pthreads[pthread_ptr];if(pthread){GROWABLE_HEAP_I32()[pthread_ptr+12>>2]=0;var worker=pthread.worker;PThread.returnWorkerToPool(worker)}}var PThread={unusedWorkers:[],runningWorkers:[],initMainThreadBlock:function(){var pthreadPoolSize=8;for(var i=0;i>2]=tb;var headPtr=tb+152;GROWABLE_HEAP_I32()[headPtr>>2]=headPtr;var tlsMemory=_malloc(512);for(var i=0;i<128;++i)GROWABLE_HEAP_U32()[tlsMemory/4+i]=0;Atomics.store(GROWABLE_HEAP_U32(),tb+100>>2,tlsMemory);Atomics.store(GROWABLE_HEAP_U32(),tb+40>>2,tb);__emscripten_thread_init(tb,!ENVIRONMENT_IS_WORKER,1);_emscripten_register_main_browser_thread_id(tb)},initWorker:function(){},pthreads:{},threadExitHandlers:[],setThreadStatus:function(){},runExitHandlers:function(){while(PThread.threadExitHandlers.length>0){PThread.threadExitHandlers.pop()()}if(ENVIRONMENT_IS_PTHREAD&&_pthread_self())___pthread_tsd_run_dtors()},runExitHandlersAndDeinitThread:function(tb,exitCode){Atomics.store(GROWABLE_HEAP_U32(),tb+56>>2,1);Atomics.store(GROWABLE_HEAP_U32(),tb+60>>2,0);PThread.runExitHandlers();Atomics.store(GROWABLE_HEAP_U32(),tb+4>>2,exitCode);Atomics.store(GROWABLE_HEAP_U32(),tb+0>>2,1);_emscripten_futex_wake(tb+0,2147483647);__emscripten_thread_init(0,0,0)},threadExit:function(exitCode){var tb=_pthread_self();if(tb){PThread.runExitHandlersAndDeinitThread(tb,exitCode);if(ENVIRONMENT_IS_PTHREAD){postMessage({\"cmd\":\"exit\"})}}},threadCancel:function(){PThread.runExitHandlersAndDeinitThread(_pthread_self(),-1);postMessage({\"cmd\":\"cancelDone\"})},terminateAllThreads:function(){for(var t in PThread.pthreads){var pthread=PThread.pthreads[t];if(pthread&&pthread.worker){PThread.returnWorkerToPool(pthread.worker)}}PThread.pthreads={};for(var i=0;i>2];GROWABLE_HEAP_I32()[pthread.threadInfoStruct+100>>2]=0;_free(tlsMemory);_free(pthread.threadInfoStruct)}pthread.threadInfoStruct=0;if(pthread.allocatedOwnStack&&pthread.stackBase)_free(pthread.stackBase);pthread.stackBase=0;if(pthread.worker)pthread.worker.pthread=null},returnWorkerToPool:function(worker){PThread.runWithoutMainThreadQueuedCalls(function(){delete PThread.pthreads[worker.pthread.threadInfoStruct];PThread.unusedWorkers.push(worker);PThread.runningWorkers.splice(PThread.runningWorkers.indexOf(worker),1);PThread.freeThreadData(worker.pthread);worker.pthread=undefined})},runWithoutMainThreadQueuedCalls:function(func){GROWABLE_HEAP_I32()[__emscripten_allow_main_runtime_queued_calls>>2]=0;try{func()}finally{GROWABLE_HEAP_I32()[__emscripten_allow_main_runtime_queued_calls>>2]=1}},receiveObjectTransfer:function(data){},loadWasmModuleToWorker:function(worker,onFinishedLoading){worker.onmessage=function(e){var d=e[\"data\"];var cmd=d[\"cmd\"];if(worker.pthread)PThread.currentProxiedOperationCallerThread=worker.pthread.threadInfoStruct;if(d[\"targetThread\"]&&d[\"targetThread\"]!=_pthread_self()){var thread=PThread.pthreads[d.targetThread];if(thread){thread.worker.postMessage(e.data,d[\"transferList\"])}else{console.error('Internal error! Worker sent a message \"'+cmd+'\" to target pthread '+d[\"targetThread\"]+\", but that thread no longer exists!\")}PThread.currentProxiedOperationCallerThread=undefined;return}if(cmd===\"processQueuedMainThreadWork\"){_emscripten_main_thread_process_queued_calls()}else if(cmd===\"spawnThread\"){spawnThread(e.data)}else if(cmd===\"cleanupThread\"){cleanupThread(d[\"thread\"])}else if(cmd===\"killThread\"){killThread(d[\"thread\"])}else if(cmd===\"cancelThread\"){cancelThread(d[\"thread\"])}else if(cmd===\"loaded\"){worker.loaded=true;if(onFinishedLoading)onFinishedLoading(worker);if(worker.runPthread){worker.runPthread();delete worker.runPthread}}else if(cmd===\"print\"){out(\"Thread \"+d[\"threadId\"]+\": \"+d[\"text\"])}else if(cmd===\"printErr\"){err(\"Thread \"+d[\"threadId\"]+\": \"+d[\"text\"])}else if(cmd===\"alert\"){alert(\"Thread \"+d[\"threadId\"]+\": \"+d[\"text\"])}else if(cmd===\"exit\"){var detached=worker.pthread&&Atomics.load(GROWABLE_HEAP_U32(),worker.pthread.threadInfoStruct+64>>2);if(detached){PThread.returnWorkerToPool(worker)}}else if(cmd===\"exitProcess\"){try{exit(d[\"returnCode\"])}catch(e){if(e instanceof ExitStatus)return;throw e}}else if(cmd===\"cancelDone\"){PThread.returnWorkerToPool(worker)}else if(cmd===\"objectTransfer\"){PThread.receiveObjectTransfer(e.data)}else if(e.data.target===\"setimmediate\"){worker.postMessage(e.data)}else{err(\"worker sent an unknown command \"+cmd)}PThread.currentProxiedOperationCallerThread=undefined};worker.onerror=function(e){err(\"pthread sent an error! \"+e.filename+\":\"+e.lineno+\": \"+e.message)};if(ENVIRONMENT_IS_NODE){worker.on(\"message\",function(data){worker.onmessage({data:data})});worker.on(\"error\",function(data){worker.onerror(data)});worker.on(\"exit\",function(data){})}worker.postMessage({\"cmd\":\"load\",\"urlOrBlob\":Module[\"mainScriptUrlOrBlob\"]||_scriptDir,\"wasmMemory\":wasmMemory,\"wasmModule\":wasmModule})},allocateUnusedWorker:function(){var pthreadMainJs=locateFile(\"tfjs-backend-wasm-threaded-simd.worker.js\");PThread.unusedWorkers.push(new Worker(pthreadMainJs))},getNewWorker:function(){if(PThread.unusedWorkers.length==0){PThread.allocateUnusedWorker();PThread.loadWasmModuleToWorker(PThread.unusedWorkers[0])}if(PThread.unusedWorkers.length>0)return PThread.unusedWorkers.pop();else return null},busySpinWait:function(msecs){var t=performance.now()+msecs;while(performance.now()>2]=value;return value}function _atexit(func,arg){if(ENVIRONMENT_IS_PTHREAD)return _emscripten_proxy_to_main_thread_js(1,1,func,arg)}function __emscripten_notify_thread_queue(targetThreadId,mainThreadId){if(targetThreadId==mainThreadId){postMessage({\"cmd\":\"processQueuedMainThreadWork\"})}else if(ENVIRONMENT_IS_PTHREAD){postMessage({\"targetThread\":targetThreadId,\"cmd\":\"processThreadQueue\"})}else{var pthread=PThread.pthreads[targetThreadId];var worker=pthread&&pthread.worker;if(!worker){return}worker.postMessage({\"cmd\":\"processThreadQueue\"})}return 1}function _abort(){abort()}function _emscripten_asm_const_int(code,sigPtr,argbuf){var args=readAsmConstArgs(sigPtr,argbuf);return ASM_CONSTS[code].apply(null,args)}function _emscripten_conditional_set_current_thread_status(expectedStatus,newStatus){}function _emscripten_futex_wait(addr,val,timeout){if(addr<=0||addr>GROWABLE_HEAP_I8().length||addr&3!=0)return-28;if(!ENVIRONMENT_IS_WEB){var ret=Atomics.wait(GROWABLE_HEAP_I32(),addr>>2,val,timeout);if(ret===\"timed-out\")return-73;if(ret===\"not-equal\")return-6;if(ret===\"ok\")return 0;throw\"Atomics.wait returned an unexpected value \"+ret}else{if(Atomics.load(GROWABLE_HEAP_I32(),addr>>2)!=val){return-6}var tNow=performance.now();var tEnd=tNow+timeout;var lastAddr=Atomics.exchange(GROWABLE_HEAP_I32(),__emscripten_main_thread_futex>>2,addr);while(1){tNow=performance.now();if(tNow>tEnd){lastAddr=Atomics.exchange(GROWABLE_HEAP_I32(),__emscripten_main_thread_futex>>2,0);return-73}lastAddr=Atomics.exchange(GROWABLE_HEAP_I32(),__emscripten_main_thread_futex>>2,0);if(lastAddr==0){break}_emscripten_main_thread_process_queued_calls();if(Atomics.load(GROWABLE_HEAP_I32(),addr>>2)!=val){return-6}lastAddr=Atomics.exchange(GROWABLE_HEAP_I32(),__emscripten_main_thread_futex>>2,addr)}return 0}}function _emscripten_memcpy_big(dest,src,num){GROWABLE_HEAP_U8().copyWithin(dest,src,src+num)}function _emscripten_num_logical_cores(){if(ENVIRONMENT_IS_NODE)return require(\"os\").cpus().length;return navigator[\"hardwareConcurrency\"]}function _emscripten_proxy_to_main_thread_js(index,sync){var numCallArgs=arguments.length-2;var stack=stackSave();var serializedNumCallArgs=numCallArgs;var args=stackAlloc(serializedNumCallArgs*8);var b=args>>3;for(var i=0;i>=2;while(ch=GROWABLE_HEAP_U8()[sigPtr++]){var double=ch<105;if(double&&buf&1)buf++;readAsmConstArgsArray.push(double?GROWABLE_HEAP_F64()[buf++>>1]:GROWABLE_HEAP_I32()[buf]);++buf}return readAsmConstArgsArray}function _emscripten_receive_on_main_thread_js(index,numCallArgs,args){_emscripten_receive_on_main_thread_js_callArgs.length=numCallArgs;var b=args>>3;for(var i=0;i>>16);updateGlobalBufferAndViews(wasmMemory.buffer);return 1}catch(e){}}function _emscripten_resize_heap(requestedSize){var oldSize=_emscripten_get_heap_size();if(requestedSize<=oldSize){return false}var maxHeapSize=2147483648;if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignUp(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=emscripten_realloc_buffer(newSize);if(replacement){return true}}return false}var JSEvents={inEventHandler:0,removeAllEventListeners:function(){for(var i=JSEvents.eventHandlers.length-1;i>=0;--i){JSEvents._removeHandler(i)}JSEvents.eventHandlers=[];JSEvents.deferredCalls=[]},registerRemoveEventListeners:function(){if(!JSEvents.removeEventListenersRegistered){__ATEXIT__.push(JSEvents.removeAllEventListeners);JSEvents.removeEventListenersRegistered=true}},deferredCalls:[],deferCall:function(targetFunction,precedence,argsList){function arraysHaveEqualContent(arrA,arrB){if(arrA.length!=arrB.length)return false;for(var i in arrA){if(arrA[i]!=arrB[i])return false}return true}for(var i in JSEvents.deferredCalls){var call=JSEvents.deferredCalls[i];if(call.targetFunction==targetFunction&&arraysHaveEqualContent(call.argsList,argsList)){return}}JSEvents.deferredCalls.push({targetFunction:targetFunction,precedence:precedence,argsList:argsList});JSEvents.deferredCalls.sort(function(x,y){return x.precedence>2]=eventTypeId;GROWABLE_HEAP_I32()[varargs+4>>2]=eventData;GROWABLE_HEAP_I32()[varargs+8>>2]=userData;__emscripten_call_on_thread(0,targetThread,637534208,eventHandlerFunc,eventData,varargs);stackRestore(stackTop)},getTargetThreadForEventCallback:function(targetThread){switch(targetThread){case 1:return 0;case 2:return PThread.currentProxiedOperationCallerThread;default:return targetThread}},getNodeNameForTarget:function(target){if(!target)return\"\";if(target==window)return\"#window\";if(target==screen)return\"#screen\";return target&&target.nodeName?target.nodeName:\"\"},fullscreenEnabled:function(){return document.fullscreenEnabled||document.webkitFullscreenEnabled}};function stringToNewUTF8(jsString){var length=lengthBytesUTF8(jsString)+1;var cString=_malloc(length);stringToUTF8(jsString,cString,length);return cString}function _emscripten_set_offscreencanvas_size_on_target_thread_js(targetThread,targetCanvas,width,height){var stackTop=stackSave();var varargs=stackAlloc(12);var targetCanvasPtr=0;if(targetCanvas){targetCanvasPtr=stringToNewUTF8(targetCanvas)}GROWABLE_HEAP_I32()[varargs>>2]=targetCanvasPtr;GROWABLE_HEAP_I32()[varargs+4>>2]=width;GROWABLE_HEAP_I32()[varargs+8>>2]=height;__emscripten_call_on_thread(0,targetThread,657457152,0,targetCanvasPtr,varargs);stackRestore(stackTop)}function _emscripten_set_offscreencanvas_size_on_target_thread(targetThread,targetCanvas,width,height){targetCanvas=targetCanvas?UTF8ToString(targetCanvas):\"\";_emscripten_set_offscreencanvas_size_on_target_thread_js(targetThread,targetCanvas,width,height)}function maybeCStringToJsString(cString){return cString>2?UTF8ToString(cString):cString}var specialHTMLTargets=[0,typeof document!==\"undefined\"?document:0,typeof window!==\"undefined\"?window:0];function findEventTarget(target){target=maybeCStringToJsString(target);var domElement=specialHTMLTargets[target]||(typeof document!==\"undefined\"?document.querySelector(target):undefined);return domElement}function findCanvasEventTarget(target){return findEventTarget(target)}function _emscripten_set_canvas_element_size_calling_thread(target,width,height){var canvas=findCanvasEventTarget(target);if(!canvas)return-4;if(canvas.canvasSharedPtr){GROWABLE_HEAP_I32()[canvas.canvasSharedPtr>>2]=width;GROWABLE_HEAP_I32()[canvas.canvasSharedPtr+4>>2]=height}if(canvas.offscreenCanvas||!canvas.controlTransferredOffscreen){if(canvas.offscreenCanvas)canvas=canvas.offscreenCanvas;var autoResizeViewport=false;if(canvas.GLctxObject&&canvas.GLctxObject.GLctx){var prevViewport=canvas.GLctxObject.GLctx.getParameter(2978);autoResizeViewport=prevViewport[0]===0&&prevViewport[1]===0&&prevViewport[2]===canvas.width&&prevViewport[3]===canvas.height}canvas.width=width;canvas.height=height;if(autoResizeViewport){canvas.GLctxObject.GLctx.viewport(0,0,width,height)}}else if(canvas.canvasSharedPtr){var targetThread=GROWABLE_HEAP_I32()[canvas.canvasSharedPtr+8>>2];_emscripten_set_offscreencanvas_size_on_target_thread(targetThread,target,width,height);return 1}else{return-4}return 0}function _emscripten_set_canvas_element_size_main_thread(target,width,height){if(ENVIRONMENT_IS_PTHREAD)return _emscripten_proxy_to_main_thread_js(2,1,target,width,height);return _emscripten_set_canvas_element_size_calling_thread(target,width,height)}function _emscripten_set_canvas_element_size(target,width,height){var canvas=findCanvasEventTarget(target);if(canvas){return _emscripten_set_canvas_element_size_calling_thread(target,width,height)}else{return _emscripten_set_canvas_element_size_main_thread(target,width,height)}}function _emscripten_set_current_thread_status(newStatus){}function _emscripten_set_thread_name(threadId,name){}function __webgl_enable_ANGLE_instanced_arrays(ctx){var ext=ctx.getExtension(\"ANGLE_instanced_arrays\");if(ext){ctx[\"vertexAttribDivisor\"]=function(index,divisor){ext[\"vertexAttribDivisorANGLE\"](index,divisor)};ctx[\"drawArraysInstanced\"]=function(mode,first,count,primcount){ext[\"drawArraysInstancedANGLE\"](mode,first,count,primcount)};ctx[\"drawElementsInstanced\"]=function(mode,count,type,indices,primcount){ext[\"drawElementsInstancedANGLE\"](mode,count,type,indices,primcount)};return 1}}function __webgl_enable_OES_vertex_array_object(ctx){var ext=ctx.getExtension(\"OES_vertex_array_object\");if(ext){ctx[\"createVertexArray\"]=function(){return ext[\"createVertexArrayOES\"]()};ctx[\"deleteVertexArray\"]=function(vao){ext[\"deleteVertexArrayOES\"](vao)};ctx[\"bindVertexArray\"]=function(vao){ext[\"bindVertexArrayOES\"](vao)};ctx[\"isVertexArray\"]=function(vao){return ext[\"isVertexArrayOES\"](vao)};return 1}}function __webgl_enable_WEBGL_draw_buffers(ctx){var ext=ctx.getExtension(\"WEBGL_draw_buffers\");if(ext){ctx[\"drawBuffers\"]=function(n,bufs){ext[\"drawBuffersWEBGL\"](n,bufs)};return 1}}function __webgl_enable_WEBGL_multi_draw(ctx){return!!(ctx.multiDrawWebgl=ctx.getExtension(\"WEBGL_multi_draw\"))}var GL={counter:1,buffers:[],programs:[],framebuffers:[],renderbuffers:[],textures:[],uniforms:[],shaders:[],vaos:[],contexts:{},offscreenCanvases:{},timerQueriesEXT:[],programInfos:{},stringCache:{},unpackAlignment:4,recordError:function recordError(errorCode){if(!GL.lastError){GL.lastError=errorCode}},getNewId:function(table){var ret=GL.counter++;for(var i=table.length;i>2]:-1;source+=UTF8ToString(GROWABLE_HEAP_I32()[string+i*4>>2],len<0?undefined:len)}return source},createContext:function(canvas,webGLContextAttributes){var ctx=canvas.getContext(\"webgl\",webGLContextAttributes);if(!ctx)return 0;var handle=GL.registerContext(ctx,webGLContextAttributes);return handle},registerContext:function(ctx,webGLContextAttributes){var handle=_malloc(8);GROWABLE_HEAP_I32()[handle+4>>2]=_pthread_self();var context={handle:handle,attributes:webGLContextAttributes,version:webGLContextAttributes.majorVersion,GLctx:ctx};if(ctx.canvas)ctx.canvas.GLctxObject=context;GL.contexts[handle]=context;if(typeof webGLContextAttributes.enableExtensionsByDefault===\"undefined\"||webGLContextAttributes.enableExtensionsByDefault){GL.initExtensions(context)}return handle},makeContextCurrent:function(contextHandle){GL.currentContext=GL.contexts[contextHandle];Module.ctx=GLctx=GL.currentContext&&GL.currentContext.GLctx;return!(contextHandle&&!GLctx)},getContext:function(contextHandle){return GL.contexts[contextHandle]},deleteContext:function(contextHandle){if(GL.currentContext===GL.contexts[contextHandle])GL.currentContext=null;if(typeof JSEvents===\"object\")JSEvents.removeAllHandlersOnTarget(GL.contexts[contextHandle].GLctx.canvas);if(GL.contexts[contextHandle]&&GL.contexts[contextHandle].GLctx.canvas)GL.contexts[contextHandle].GLctx.canvas.GLctxObject=undefined;_free(GL.contexts[contextHandle].handle);GL.contexts[contextHandle]=null},initExtensions:function(context){if(!context)context=GL.currentContext;if(context.initExtensionsDone)return;context.initExtensionsDone=true;var GLctx=context.GLctx;__webgl_enable_ANGLE_instanced_arrays(GLctx);__webgl_enable_OES_vertex_array_object(GLctx);__webgl_enable_WEBGL_draw_buffers(GLctx);GLctx.disjointTimerQueryExt=GLctx.getExtension(\"EXT_disjoint_timer_query\");__webgl_enable_WEBGL_multi_draw(GLctx);var exts=GLctx.getSupportedExtensions()||[];exts.forEach(function(ext){if(ext.indexOf(\"lose_context\")<0&&ext.indexOf(\"debug\")<0){GLctx.getExtension(ext)}})},populateUniformTable:function(program){var p=GL.programs[program];var ptable=GL.programInfos[program]={uniforms:{},maxUniformLength:0,maxAttributeLength:-1,maxUniformBlockNameLength:-1};var utable=ptable.uniforms;var numUniforms=GLctx.getProgramParameter(p,35718);for(var i=0;i>2;var powerPreference=GROWABLE_HEAP_I32()[a+(24>>2)];var contextAttributes={\"alpha\":!!GROWABLE_HEAP_I32()[a+(0>>2)],\"depth\":!!GROWABLE_HEAP_I32()[a+(4>>2)],\"stencil\":!!GROWABLE_HEAP_I32()[a+(8>>2)],\"antialias\":!!GROWABLE_HEAP_I32()[a+(12>>2)],\"premultipliedAlpha\":!!GROWABLE_HEAP_I32()[a+(16>>2)],\"preserveDrawingBuffer\":!!GROWABLE_HEAP_I32()[a+(20>>2)],\"powerPreference\":__emscripten_webgl_power_preferences[powerPreference],\"failIfMajorPerformanceCaveat\":!!GROWABLE_HEAP_I32()[a+(28>>2)],majorVersion:GROWABLE_HEAP_I32()[a+(32>>2)],minorVersion:GROWABLE_HEAP_I32()[a+(36>>2)],enableExtensionsByDefault:GROWABLE_HEAP_I32()[a+(40>>2)],explicitSwapControl:GROWABLE_HEAP_I32()[a+(44>>2)],proxyContextToMainThread:GROWABLE_HEAP_I32()[a+(48>>2)],renderViaOffscreenBackBuffer:GROWABLE_HEAP_I32()[a+(52>>2)]};var canvas=findCanvasEventTarget(target);if(!canvas){return 0}if(contextAttributes.explicitSwapControl){return 0}var contextHandle=GL.createContext(canvas,contextAttributes);return contextHandle}function _emscripten_webgl_create_context(a0,a1){return _emscripten_webgl_do_create_context(a0,a1)}var SYSCALLS={mappings:{},buffers:[null,[],[]],printChar:function(stream,curr){var buffer=SYSCALLS.buffers[stream];if(curr===0||curr===10){(stream===1?out:err)(UTF8ArrayToString(buffer,0));buffer.length=0}else{buffer.push(curr)}},varargs:undefined,get:function(){SYSCALLS.varargs+=4;var ret=GROWABLE_HEAP_I32()[SYSCALLS.varargs-4>>2];return ret},getStr:function(ptr){var ret=UTF8ToString(ptr);return ret},get64:function(low,high){return low}};function _fd_close(fd){if(ENVIRONMENT_IS_PTHREAD)return _emscripten_proxy_to_main_thread_js(3,1,fd);return 0}function _fd_seek(fd,offset_low,offset_high,whence,newOffset){if(ENVIRONMENT_IS_PTHREAD)return _emscripten_proxy_to_main_thread_js(4,1,fd,offset_low,offset_high,whence,newOffset)}function _fd_write(fd,iov,iovcnt,pnum){if(ENVIRONMENT_IS_PTHREAD)return _emscripten_proxy_to_main_thread_js(5,1,fd,iov,iovcnt,pnum);var num=0;for(var i=0;i>2];var len=GROWABLE_HEAP_I32()[iov+(i*8+4)>>2];for(var j=0;j>2]=num;return 0}function _pthread_cleanup_pop(execute){var routine=PThread.threadExitHandlers.pop();if(execute)routine()}function _pthread_cleanup_push(routine,arg){PThread.threadExitHandlers.push(function(){wasmTable.get(routine)(arg)})}function spawnThread(threadParams){if(ENVIRONMENT_IS_PTHREAD)throw\"Internal Error! spawnThread() can only ever be called from main application thread!\";var worker=PThread.getNewWorker();if(worker.pthread!==undefined)throw\"Internal error!\";if(!threadParams.pthread_ptr)throw\"Internal error, no pthread ptr!\";PThread.runningWorkers.push(worker);var tlsMemory=_malloc(128*4);for(var i=0;i<128;++i){GROWABLE_HEAP_I32()[tlsMemory+i*4>>2]=0}var stackHigh=threadParams.stackBase+threadParams.stackSize;var pthread=PThread.pthreads[threadParams.pthread_ptr]={worker:worker,stackBase:threadParams.stackBase,stackSize:threadParams.stackSize,allocatedOwnStack:threadParams.allocatedOwnStack,threadInfoStruct:threadParams.pthread_ptr};var tis=pthread.threadInfoStruct>>2;Atomics.store(GROWABLE_HEAP_U32(),tis+(64>>2),threadParams.detached);Atomics.store(GROWABLE_HEAP_U32(),tis+(100>>2),tlsMemory);Atomics.store(GROWABLE_HEAP_U32(),tis+(40>>2),pthread.threadInfoStruct);Atomics.store(GROWABLE_HEAP_U32(),tis+(80>>2),threadParams.stackSize);Atomics.store(GROWABLE_HEAP_U32(),tis+(76>>2),stackHigh);Atomics.store(GROWABLE_HEAP_U32(),tis+(104>>2),threadParams.stackSize);Atomics.store(GROWABLE_HEAP_U32(),tis+(104+8>>2),stackHigh);Atomics.store(GROWABLE_HEAP_U32(),tis+(104+12>>2),threadParams.detached);var global_libc=_emscripten_get_global_libc();var global_locale=global_libc+40;Atomics.store(GROWABLE_HEAP_U32(),tis+(172>>2),global_locale);worker.pthread=pthread;var msg={\"cmd\":\"run\",\"start_routine\":threadParams.startRoutine,\"arg\":threadParams.arg,\"threadInfoStruct\":threadParams.pthread_ptr,\"stackBase\":threadParams.stackBase,\"stackSize\":threadParams.stackSize};worker.runPthread=function(){msg.time=performance.now();worker.postMessage(msg,threadParams.transferList)};if(worker.loaded){worker.runPthread();delete worker.runPthread}}function _pthread_create(pthread_ptr,attr,start_routine,arg){if(typeof SharedArrayBuffer===\"undefined\"){err(\"Current environment does not support SharedArrayBuffer, pthreads are not available!\");return 6}if(!pthread_ptr){err(\"pthread_create called with a null thread pointer!\");return 28}var transferList=[];var error=0;if(ENVIRONMENT_IS_PTHREAD&&(transferList.length===0||error)){return _emscripten_sync_run_in_main_thread_4(687865856,pthread_ptr,attr,start_routine,arg)}if(error)return error;var stackSize=0;var stackBase=0;var detached=0;if(attr&&attr!=-1){stackSize=GROWABLE_HEAP_I32()[attr>>2];stackSize+=81920;stackBase=GROWABLE_HEAP_I32()[attr+8>>2];detached=GROWABLE_HEAP_I32()[attr+12>>2]!==0}else{stackSize=2097152}var allocatedOwnStack=stackBase==0;if(allocatedOwnStack){stackBase=_memalign(16,stackSize)}else{stackBase-=stackSize;assert(stackBase>0)}var threadInfoStruct=_malloc(228);for(var i=0;i<228>>2;++i)GROWABLE_HEAP_U32()[(threadInfoStruct>>2)+i]=0;GROWABLE_HEAP_I32()[pthread_ptr>>2]=threadInfoStruct;GROWABLE_HEAP_I32()[threadInfoStruct+12>>2]=threadInfoStruct;var headPtr=threadInfoStruct+152;GROWABLE_HEAP_I32()[headPtr>>2]=headPtr;var threadParams={stackBase:stackBase,stackSize:stackSize,allocatedOwnStack:allocatedOwnStack,detached:detached,startRoutine:start_routine,pthread_ptr:threadInfoStruct,arg:arg,transferList:transferList};if(ENVIRONMENT_IS_PTHREAD){threadParams.cmd=\"spawnThread\";postMessage(threadParams,transferList)}else{spawnThread(threadParams)}return 0}function __pthread_testcancel_js(){if(!ENVIRONMENT_IS_PTHREAD)return;var tb=_pthread_self();if(!tb)return;var cancelDisabled=Atomics.load(GROWABLE_HEAP_U32(),tb+56>>2);if(cancelDisabled)return;var canceled=Atomics.load(GROWABLE_HEAP_U32(),tb+0>>2);if(canceled==2)throw\"Canceled!\"}function _emscripten_check_blocking_allowed(){if(ENVIRONMENT_IS_NODE)return;if(ENVIRONMENT_IS_WORKER)return;warnOnce(\"Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread\")}function __emscripten_do_pthread_join(thread,status,block){if(!thread){err(\"pthread_join attempted on a null thread pointer!\");return ERRNO_CODES.ESRCH}if(ENVIRONMENT_IS_PTHREAD&&_pthread_self()==thread){err(\"PThread \"+thread+\" is attempting to join to itself!\");return ERRNO_CODES.EDEADLK}else if(!ENVIRONMENT_IS_PTHREAD&&_emscripten_main_browser_thread_id()==thread){err(\"Main thread \"+thread+\" is attempting to join to itself!\");return ERRNO_CODES.EDEADLK}var self=GROWABLE_HEAP_I32()[thread+12>>2];if(self!==thread){err(\"pthread_join attempted on thread \"+thread+\", which does not point to a valid thread, or does not exist anymore!\");return ERRNO_CODES.ESRCH}var detached=Atomics.load(GROWABLE_HEAP_U32(),thread+64>>2);if(detached){err(\"Attempted to join thread \"+thread+\", which was already detached!\");return ERRNO_CODES.EINVAL}if(block){_emscripten_check_blocking_allowed()}for(;;){var threadStatus=Atomics.load(GROWABLE_HEAP_U32(),thread+0>>2);if(threadStatus==1){var threadExitCode=Atomics.load(GROWABLE_HEAP_U32(),thread+4>>2);if(status)GROWABLE_HEAP_I32()[status>>2]=threadExitCode;Atomics.store(GROWABLE_HEAP_U32(),thread+64>>2,1);if(!ENVIRONMENT_IS_PTHREAD)cleanupThread(thread);else postMessage({\"cmd\":\"cleanupThread\",\"thread\":thread});return 0}if(!block){return ERRNO_CODES.EBUSY}__pthread_testcancel_js();if(!ENVIRONMENT_IS_PTHREAD)_emscripten_main_thread_process_queued_calls();_emscripten_futex_wait(thread+0,threadStatus,ENVIRONMENT_IS_PTHREAD?100:1)}}function _pthread_join(thread,status){return __emscripten_do_pthread_join(thread,status,true)}function _sysconf(name){if(ENVIRONMENT_IS_PTHREAD)return _emscripten_proxy_to_main_thread_js(6,1,name);switch(name){case 30:return 16384;case 85:var maxHeapSize=2147483648;return maxHeapSize/16384;case 132:case 133:case 12:case 137:case 138:case 15:case 235:case 16:case 17:case 18:case 19:case 20:case 149:case 13:case 10:case 236:case 153:case 9:case 21:case 22:case 159:case 154:case 14:case 77:case 78:case 139:case 82:case 68:case 67:case 164:case 11:case 29:case 47:case 48:case 95:case 52:case 51:case 46:return 200809;case 27:case 246:case 127:case 128:case 23:case 24:case 160:case 161:case 181:case 182:case 242:case 183:case 184:case 243:case 244:case 245:case 165:case 178:case 179:case 49:case 50:case 168:case 169:case 175:case 170:case 171:case 172:case 97:case 76:case 32:case 173:case 35:case 80:case 81:case 79:return-1;case 176:case 177:case 7:case 155:case 8:case 157:case 125:case 126:case 92:case 93:case 129:case 130:case 131:case 94:case 91:return 1;case 74:case 60:case 69:case 70:case 4:return 1024;case 31:case 42:case 72:return 32;case 87:case 26:case 33:return 2147483647;case 34:case 1:return 47839;case 38:case 36:return 99;case 43:case 37:return 2048;case 0:return 2097152;case 3:return 65536;case 28:return 32768;case 44:return 32767;case 75:return 16384;case 39:return 1e3;case 89:return 700;case 71:return 256;case 40:return 255;case 2:return 100;case 180:return 64;case 25:return 20;case 5:return 16;case 6:return 6;case 73:return 4;case 84:{if(typeof navigator===\"object\")return navigator[\"hardwareConcurrency\"]||1;return 1}}setErrNo(28);return-1}if(!ENVIRONMENT_IS_PTHREAD)PThread.initMainThreadBlock();var GLctx;var proxiedFunctionTable=[null,_atexit,_emscripten_set_canvas_element_size_main_thread,_fd_close,_fd_seek,_fd_write,_sysconf];var asmLibraryArg={\"e\":___assert_fail,\"r\":___call_main,\"x\":__emscripten_notify_thread_queue,\"b\":_abort,\"y\":_emscripten_asm_const_int,\"j\":_emscripten_conditional_set_current_thread_status,\"d\":_emscripten_futex_wait,\"c\":_emscripten_futex_wake,\"f\":_emscripten_get_now,\"p\":_emscripten_memcpy_big,\"A\":_emscripten_num_logical_cores,\"u\":_emscripten_receive_on_main_thread_js,\"q\":_emscripten_resize_heap,\"v\":_emscripten_set_canvas_element_size,\"i\":_emscripten_set_current_thread_status,\"s\":_emscripten_set_thread_name,\"w\":_emscripten_webgl_create_context,\"l\":_fd_close,\"n\":_fd_seek,\"g\":_fd_write,\"o\":initPthreadsJS,\"a\":wasmMemory||Module[\"wasmMemory\"],\"z\":_pthread_cleanup_pop,\"k\":_pthread_cleanup_push,\"h\":_pthread_create,\"m\":_pthread_join,\"t\":_sysconf};var asm=createWasm();var ___wasm_call_ctors=Module[\"___wasm_call_ctors\"]=function(){return(___wasm_call_ctors=Module[\"___wasm_call_ctors\"]=Module[\"asm\"][\"B\"]).apply(null,arguments)};var _init=Module[\"_init\"]=function(){return(_init=Module[\"_init\"]=Module[\"asm\"][\"C\"]).apply(null,arguments)};var _init_with_threads_count=Module[\"_init_with_threads_count\"]=function(){return(_init_with_threads_count=Module[\"_init_with_threads_count\"]=Module[\"asm\"][\"D\"]).apply(null,arguments)};var _get_threads_count=Module[\"_get_threads_count\"]=function(){return(_get_threads_count=Module[\"_get_threads_count\"]=Module[\"asm\"][\"E\"]).apply(null,arguments)};var _register_tensor=Module[\"_register_tensor\"]=function(){return(_register_tensor=Module[\"_register_tensor\"]=Module[\"asm\"][\"F\"]).apply(null,arguments)};var _dispose_data=Module[\"_dispose_data\"]=function(){return(_dispose_data=Module[\"_dispose_data\"]=Module[\"asm\"][\"G\"]).apply(null,arguments)};var _dispose=Module[\"_dispose\"]=function(){return(_dispose=Module[\"_dispose\"]=Module[\"asm\"][\"H\"]).apply(null,arguments)};var _Abs=Module[\"_Abs\"]=function(){return(_Abs=Module[\"_Abs\"]=Module[\"asm\"][\"I\"]).apply(null,arguments)};var _Add=Module[\"_Add\"]=function(){return(_Add=Module[\"_Add\"]=Module[\"asm\"][\"J\"]).apply(null,arguments)};var _AddN=Module[\"_AddN\"]=function(){return(_AddN=Module[\"_AddN\"]=Module[\"asm\"][\"K\"]).apply(null,arguments)};var _All=Module[\"_All\"]=function(){return(_All=Module[\"_All\"]=Module[\"asm\"][\"L\"]).apply(null,arguments)};var _Any=Module[\"_Any\"]=function(){return(_Any=Module[\"_Any\"]=Module[\"asm\"][\"M\"]).apply(null,arguments)};var _ArgMax=Module[\"_ArgMax\"]=function(){return(_ArgMax=Module[\"_ArgMax\"]=Module[\"asm\"][\"N\"]).apply(null,arguments)};var _AvgPool=Module[\"_AvgPool\"]=function(){return(_AvgPool=Module[\"_AvgPool\"]=Module[\"asm\"][\"O\"]).apply(null,arguments)};var _BatchMatMul=Module[\"_BatchMatMul\"]=function(){return(_BatchMatMul=Module[\"_BatchMatMul\"]=Module[\"asm\"][\"P\"]).apply(null,arguments)};var _Ceil=Module[\"_Ceil\"]=function(){return(_Ceil=Module[\"_Ceil\"]=Module[\"asm\"][\"Q\"]).apply(null,arguments)};var _ClipByValue=Module[\"_ClipByValue\"]=function(){return(_ClipByValue=Module[\"_ClipByValue\"]=Module[\"asm\"][\"R\"]).apply(null,arguments)};var _Conv2D=Module[\"_Conv2D\"]=function(){return(_Conv2D=Module[\"_Conv2D\"]=Module[\"asm\"][\"S\"]).apply(null,arguments)};var _Conv2DBackpropInput=Module[\"_Conv2DBackpropInput\"]=function(){return(_Conv2DBackpropInput=Module[\"_Conv2DBackpropInput\"]=Module[\"asm\"][\"T\"]).apply(null,arguments)};var _Cos=Module[\"_Cos\"]=function(){return(_Cos=Module[\"_Cos\"]=Module[\"asm\"][\"U\"]).apply(null,arguments)};var _Cosh=Module[\"_Cosh\"]=function(){return(_Cosh=Module[\"_Cosh\"]=Module[\"asm\"][\"V\"]).apply(null,arguments)};var _CropAndResize=Module[\"_CropAndResize\"]=function(){return(_CropAndResize=Module[\"_CropAndResize\"]=Module[\"asm\"][\"W\"]).apply(null,arguments)};var _Cumsum=Module[\"_Cumsum\"]=function(){return(_Cumsum=Module[\"_Cumsum\"]=Module[\"asm\"][\"X\"]).apply(null,arguments)};var _DepthToSpace=Module[\"_DepthToSpace\"]=function(){return(_DepthToSpace=Module[\"_DepthToSpace\"]=Module[\"asm\"][\"Y\"]).apply(null,arguments)};var _DepthwiseConv2dNative=Module[\"_DepthwiseConv2dNative\"]=function(){return(_DepthwiseConv2dNative=Module[\"_DepthwiseConv2dNative\"]=Module[\"asm\"][\"Z\"]).apply(null,arguments)};var _Elu=Module[\"_Elu\"]=function(){return(_Elu=Module[\"_Elu\"]=Module[\"asm\"][\"_\"]).apply(null,arguments)};var _Equal=Module[\"_Equal\"]=function(){return(_Equal=Module[\"_Equal\"]=Module[\"asm\"][\"$\"]).apply(null,arguments)};var _Exp=Module[\"_Exp\"]=function(){return(_Exp=Module[\"_Exp\"]=Module[\"asm\"][\"aa\"]).apply(null,arguments)};var _FlipLeftRight=Module[\"_FlipLeftRight\"]=function(){return(_FlipLeftRight=Module[\"_FlipLeftRight\"]=Module[\"asm\"][\"ba\"]).apply(null,arguments)};var _Floor=Module[\"_Floor\"]=function(){return(_Floor=Module[\"_Floor\"]=Module[\"asm\"][\"ca\"]).apply(null,arguments)};var _FloorDiv=Module[\"_FloorDiv\"]=function(){return(_FloorDiv=Module[\"_FloorDiv\"]=Module[\"asm\"][\"da\"]).apply(null,arguments)};var _FusedBatchNorm=Module[\"_FusedBatchNorm\"]=function(){return(_FusedBatchNorm=Module[\"_FusedBatchNorm\"]=Module[\"asm\"][\"ea\"]).apply(null,arguments)};var _FusedConv2D=Module[\"_FusedConv2D\"]=function(){return(_FusedConv2D=Module[\"_FusedConv2D\"]=Module[\"asm\"][\"fa\"]).apply(null,arguments)};var _FusedDepthwiseConv2D=Module[\"_FusedDepthwiseConv2D\"]=function(){return(_FusedDepthwiseConv2D=Module[\"_FusedDepthwiseConv2D\"]=Module[\"asm\"][\"ga\"]).apply(null,arguments)};var _Gather=Module[\"_Gather\"]=function(){return(_Gather=Module[\"_Gather\"]=Module[\"asm\"][\"ha\"]).apply(null,arguments)};var _GatherNd=Module[\"_GatherNd\"]=function(){return(_GatherNd=Module[\"_GatherNd\"]=Module[\"asm\"][\"ia\"]).apply(null,arguments)};var _Greater=Module[\"_Greater\"]=function(){return(_Greater=Module[\"_Greater\"]=Module[\"asm\"][\"ja\"]).apply(null,arguments)};var _GreaterEqual=Module[\"_GreaterEqual\"]=function(){return(_GreaterEqual=Module[\"_GreaterEqual\"]=Module[\"asm\"][\"ka\"]).apply(null,arguments)};var _LeakyRelu=Module[\"_LeakyRelu\"]=function(){return(_LeakyRelu=Module[\"_LeakyRelu\"]=Module[\"asm\"][\"la\"]).apply(null,arguments)};var _Less=Module[\"_Less\"]=function(){return(_Less=Module[\"_Less\"]=Module[\"asm\"][\"ma\"]).apply(null,arguments)};var _LessEqual=Module[\"_LessEqual\"]=function(){return(_LessEqual=Module[\"_LessEqual\"]=Module[\"asm\"][\"na\"]).apply(null,arguments)};var _Log=Module[\"_Log\"]=function(){return(_Log=Module[\"_Log\"]=Module[\"asm\"][\"oa\"]).apply(null,arguments)};var _LogicalAnd=Module[\"_LogicalAnd\"]=function(){return(_LogicalAnd=Module[\"_LogicalAnd\"]=Module[\"asm\"][\"pa\"]).apply(null,arguments)};var _Max=Module[\"_Max\"]=function(){return(_Max=Module[\"_Max\"]=Module[\"asm\"][\"qa\"]).apply(null,arguments)};var _MaxPool=Module[\"_MaxPool\"]=function(){return(_MaxPool=Module[\"_MaxPool\"]=Module[\"asm\"][\"ra\"]).apply(null,arguments)};var _Maximum=Module[\"_Maximum\"]=function(){return(_Maximum=Module[\"_Maximum\"]=Module[\"asm\"][\"sa\"]).apply(null,arguments)};var _Mean=Module[\"_Mean\"]=function(){return(_Mean=Module[\"_Mean\"]=Module[\"asm\"][\"ta\"]).apply(null,arguments)};var _Min=Module[\"_Min\"]=function(){return(_Min=Module[\"_Min\"]=Module[\"asm\"][\"ua\"]).apply(null,arguments)};var _Minimum=Module[\"_Minimum\"]=function(){return(_Minimum=Module[\"_Minimum\"]=Module[\"asm\"][\"va\"]).apply(null,arguments)};var _MirrorPad=Module[\"_MirrorPad\"]=function(){return(_MirrorPad=Module[\"_MirrorPad\"]=Module[\"asm\"][\"wa\"]).apply(null,arguments)};var _Multiply=Module[\"_Multiply\"]=function(){return(_Multiply=Module[\"_Multiply\"]=Module[\"asm\"][\"xa\"]).apply(null,arguments)};var _Neg=Module[\"_Neg\"]=function(){return(_Neg=Module[\"_Neg\"]=Module[\"asm\"][\"ya\"]).apply(null,arguments)};var _NonMaxSuppressionV3=Module[\"_NonMaxSuppressionV3\"]=function(){return(_NonMaxSuppressionV3=Module[\"_NonMaxSuppressionV3\"]=Module[\"asm\"][\"za\"]).apply(null,arguments)};var _NonMaxSuppressionV4=Module[\"_NonMaxSuppressionV4\"]=function(){return(_NonMaxSuppressionV4=Module[\"_NonMaxSuppressionV4\"]=Module[\"asm\"][\"Aa\"]).apply(null,arguments)};var _NonMaxSuppressionV5=Module[\"_NonMaxSuppressionV5\"]=function(){return(_NonMaxSuppressionV5=Module[\"_NonMaxSuppressionV5\"]=Module[\"asm\"][\"Ba\"]).apply(null,arguments)};var _NotEqual=Module[\"_NotEqual\"]=function(){return(_NotEqual=Module[\"_NotEqual\"]=Module[\"asm\"][\"Ca\"]).apply(null,arguments)};var _OneHot=Module[\"_OneHot\"]=function(){return(_OneHot=Module[\"_OneHot\"]=Module[\"asm\"][\"Da\"]).apply(null,arguments)};var _PadV2=Module[\"_PadV2\"]=function(){return(_PadV2=Module[\"_PadV2\"]=Module[\"asm\"][\"Ea\"]).apply(null,arguments)};var _Pow=Module[\"_Pow\"]=function(){return(_Pow=Module[\"_Pow\"]=Module[\"asm\"][\"Fa\"]).apply(null,arguments)};var _Prelu=Module[\"_Prelu\"]=function(){return(_Prelu=Module[\"_Prelu\"]=Module[\"asm\"][\"Ga\"]).apply(null,arguments)};var _Prod=Module[\"_Prod\"]=function(){return(_Prod=Module[\"_Prod\"]=Module[\"asm\"][\"Ha\"]).apply(null,arguments)};var _RealDiv=Module[\"_RealDiv\"]=function(){return(_RealDiv=Module[\"_RealDiv\"]=Module[\"asm\"][\"Ia\"]).apply(null,arguments)};var _Relu=Module[\"_Relu\"]=function(){return(_Relu=Module[\"_Relu\"]=Module[\"asm\"][\"Ja\"]).apply(null,arguments)};var _Relu6=Module[\"_Relu6\"]=function(){return(_Relu6=Module[\"_Relu6\"]=Module[\"asm\"][\"Ka\"]).apply(null,arguments)};var _ResizeBilinear=Module[\"_ResizeBilinear\"]=function(){return(_ResizeBilinear=Module[\"_ResizeBilinear\"]=Module[\"asm\"][\"La\"]).apply(null,arguments)};var _Reverse=Module[\"_Reverse\"]=function(){return(_Reverse=Module[\"_Reverse\"]=Module[\"asm\"][\"Ma\"]).apply(null,arguments)};var _RotateWithOffset=Module[\"_RotateWithOffset\"]=function(){return(_RotateWithOffset=Module[\"_RotateWithOffset\"]=Module[\"asm\"][\"Na\"]).apply(null,arguments)};var _Round=Module[\"_Round\"]=function(){return(_Round=Module[\"_Round\"]=Module[\"asm\"][\"Oa\"]).apply(null,arguments)};var _Rsqrt=Module[\"_Rsqrt\"]=function(){return(_Rsqrt=Module[\"_Rsqrt\"]=Module[\"asm\"][\"Pa\"]).apply(null,arguments)};var _ScatterNd=Module[\"_ScatterNd\"]=function(){return(_ScatterNd=Module[\"_ScatterNd\"]=Module[\"asm\"][\"Qa\"]).apply(null,arguments)};var _SelectV2=Module[\"_SelectV2\"]=function(){return(_SelectV2=Module[\"_SelectV2\"]=Module[\"asm\"][\"Ra\"]).apply(null,arguments)};var _Sigmoid=Module[\"_Sigmoid\"]=function(){return(_Sigmoid=Module[\"_Sigmoid\"]=Module[\"asm\"][\"Sa\"]).apply(null,arguments)};var _Sin=Module[\"_Sin\"]=function(){return(_Sin=Module[\"_Sin\"]=Module[\"asm\"][\"Ta\"]).apply(null,arguments)};var _Softmax=Module[\"_Softmax\"]=function(){return(_Softmax=Module[\"_Softmax\"]=Module[\"asm\"][\"Ua\"]).apply(null,arguments)};var _Sqrt=Module[\"_Sqrt\"]=function(){return(_Sqrt=Module[\"_Sqrt\"]=Module[\"asm\"][\"Va\"]).apply(null,arguments)};var _Square=Module[\"_Square\"]=function(){return(_Square=Module[\"_Square\"]=Module[\"asm\"][\"Wa\"]).apply(null,arguments)};var _SquaredDifference=Module[\"_SquaredDifference\"]=function(){return(_SquaredDifference=Module[\"_SquaredDifference\"]=Module[\"asm\"][\"Xa\"]).apply(null,arguments)};var _Step=Module[\"_Step\"]=function(){return(_Step=Module[\"_Step\"]=Module[\"asm\"][\"Ya\"]).apply(null,arguments)};var _StridedSlice=Module[\"_StridedSlice\"]=function(){return(_StridedSlice=Module[\"_StridedSlice\"]=Module[\"asm\"][\"Za\"]).apply(null,arguments)};var _Sub=Module[\"_Sub\"]=function(){return(_Sub=Module[\"_Sub\"]=Module[\"asm\"][\"_a\"]).apply(null,arguments)};var _Sum=Module[\"_Sum\"]=function(){return(_Sum=Module[\"_Sum\"]=Module[\"asm\"][\"$a\"]).apply(null,arguments)};var _Tan=Module[\"_Tan\"]=function(){return(_Tan=Module[\"_Tan\"]=Module[\"asm\"][\"ab\"]).apply(null,arguments)};var _Tanh=Module[\"_Tanh\"]=function(){return(_Tanh=Module[\"_Tanh\"]=Module[\"asm\"][\"bb\"]).apply(null,arguments)};var _Tile=Module[\"_Tile\"]=function(){return(_Tile=Module[\"_Tile\"]=Module[\"asm\"][\"cb\"]).apply(null,arguments)};var _TopK=Module[\"_TopK\"]=function(){return(_TopK=Module[\"_TopK\"]=Module[\"asm\"][\"db\"]).apply(null,arguments)};var _Transform=Module[\"_Transform\"]=function(){return(_Transform=Module[\"_Transform\"]=Module[\"asm\"][\"eb\"]).apply(null,arguments)};var _Transpose=Module[\"_Transpose\"]=function(){return(_Transpose=Module[\"_Transpose\"]=Module[\"asm\"][\"fb\"]).apply(null,arguments)};var __FusedMatMul=Module[\"__FusedMatMul\"]=function(){return(__FusedMatMul=Module[\"__FusedMatMul\"]=Module[\"asm\"][\"gb\"]).apply(null,arguments)};var _malloc=Module[\"_malloc\"]=function(){return(_malloc=Module[\"_malloc\"]=Module[\"asm\"][\"hb\"]).apply(null,arguments)};var _free=Module[\"_free\"]=function(){return(_free=Module[\"_free\"]=Module[\"asm\"][\"ib\"]).apply(null,arguments)};var ___errno_location=Module[\"___errno_location\"]=function(){return(___errno_location=Module[\"___errno_location\"]=Module[\"asm\"][\"jb\"]).apply(null,arguments)};var _emscripten_get_global_libc=Module[\"_emscripten_get_global_libc\"]=function(){return(_emscripten_get_global_libc=Module[\"_emscripten_get_global_libc\"]=Module[\"asm\"][\"lb\"]).apply(null,arguments)};var _pthread_self=Module[\"_pthread_self\"]=function(){return(_pthread_self=Module[\"_pthread_self\"]=Module[\"asm\"][\"mb\"]).apply(null,arguments)};var ___pthread_tsd_run_dtors=Module[\"___pthread_tsd_run_dtors\"]=function(){return(___pthread_tsd_run_dtors=Module[\"___pthread_tsd_run_dtors\"]=Module[\"asm\"][\"nb\"]).apply(null,arguments)};var _emscripten_main_thread_process_queued_calls=Module[\"_emscripten_main_thread_process_queued_calls\"]=function(){return(_emscripten_main_thread_process_queued_calls=Module[\"_emscripten_main_thread_process_queued_calls\"]=Module[\"asm\"][\"ob\"]).apply(null,arguments)};var _emscripten_current_thread_process_queued_calls=Module[\"_emscripten_current_thread_process_queued_calls\"]=function(){return(_emscripten_current_thread_process_queued_calls=Module[\"_emscripten_current_thread_process_queued_calls\"]=Module[\"asm\"][\"pb\"]).apply(null,arguments)};var _emscripten_register_main_browser_thread_id=Module[\"_emscripten_register_main_browser_thread_id\"]=function(){return(_emscripten_register_main_browser_thread_id=Module[\"_emscripten_register_main_browser_thread_id\"]=Module[\"asm\"][\"qb\"]).apply(null,arguments)};var _emscripten_main_browser_thread_id=Module[\"_emscripten_main_browser_thread_id\"]=function(){return(_emscripten_main_browser_thread_id=Module[\"_emscripten_main_browser_thread_id\"]=Module[\"asm\"][\"rb\"]).apply(null,arguments)};var __emscripten_do_dispatch_to_thread=Module[\"__emscripten_do_dispatch_to_thread\"]=function(){return(__emscripten_do_dispatch_to_thread=Module[\"__emscripten_do_dispatch_to_thread\"]=Module[\"asm\"][\"sb\"]).apply(null,arguments)};var _emscripten_sync_run_in_main_thread_4=Module[\"_emscripten_sync_run_in_main_thread_4\"]=function(){return(_emscripten_sync_run_in_main_thread_4=Module[\"_emscripten_sync_run_in_main_thread_4\"]=Module[\"asm\"][\"tb\"]).apply(null,arguments)};var _emscripten_run_in_main_runtime_thread_js=Module[\"_emscripten_run_in_main_runtime_thread_js\"]=function(){return(_emscripten_run_in_main_runtime_thread_js=Module[\"_emscripten_run_in_main_runtime_thread_js\"]=Module[\"asm\"][\"ub\"]).apply(null,arguments)};var __emscripten_call_on_thread=Module[\"__emscripten_call_on_thread\"]=function(){return(__emscripten_call_on_thread=Module[\"__emscripten_call_on_thread\"]=Module[\"asm\"][\"vb\"]).apply(null,arguments)};var _emscripten_tls_init=Module[\"_emscripten_tls_init\"]=function(){return(_emscripten_tls_init=Module[\"_emscripten_tls_init\"]=Module[\"asm\"][\"wb\"]).apply(null,arguments)};var __emscripten_thread_init=Module[\"__emscripten_thread_init\"]=function(){return(__emscripten_thread_init=Module[\"__emscripten_thread_init\"]=Module[\"asm\"][\"xb\"]).apply(null,arguments)};var stackSave=Module[\"stackSave\"]=function(){return(stackSave=Module[\"stackSave\"]=Module[\"asm\"][\"yb\"]).apply(null,arguments)};var stackRestore=Module[\"stackRestore\"]=function(){return(stackRestore=Module[\"stackRestore\"]=Module[\"asm\"][\"zb\"]).apply(null,arguments)};var stackAlloc=Module[\"stackAlloc\"]=function(){return(stackAlloc=Module[\"stackAlloc\"]=Module[\"asm\"][\"Ab\"]).apply(null,arguments)};var _emscripten_stack_set_limits=Module[\"_emscripten_stack_set_limits\"]=function(){return(_emscripten_stack_set_limits=Module[\"_emscripten_stack_set_limits\"]=Module[\"asm\"][\"Bb\"]).apply(null,arguments)};var _memalign=Module[\"_memalign\"]=function(){return(_memalign=Module[\"_memalign\"]=Module[\"asm\"][\"Cb\"]).apply(null,arguments)};var __emscripten_allow_main_runtime_queued_calls=Module[\"__emscripten_allow_main_runtime_queued_calls\"]=10064;var __emscripten_main_thread_futex=Module[\"__emscripten_main_thread_futex\"]=10268;Module[\"cwrap\"]=cwrap;Module[\"PThread\"]=PThread;Module[\"PThread\"]=PThread;Module[\"wasmMemory\"]=wasmMemory;Module[\"ExitStatus\"]=ExitStatus;var calledRun;function ExitStatus(status){this.name=\"ExitStatus\";this.message=\"Program terminated with exit(\"+status+\")\";this.status=status}dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function run(args){args=args||arguments_;if(runDependencies>0){return}if(ENVIRONMENT_IS_PTHREAD){readyPromiseResolve(Module);initRuntime();postMessage({\"cmd\":\"loaded\"});return}preRun();if(runDependencies>0){return}function doRun(){if(calledRun)return;calledRun=true;Module[\"calledRun\"]=true;if(ABORT)return;initRuntime();preMain();readyPromiseResolve(Module);if(Module[\"onRuntimeInitialized\"])Module[\"onRuntimeInitialized\"]();postRun()}if(Module[\"setStatus\"]){Module[\"setStatus\"](\"Running...\");setTimeout(function(){setTimeout(function(){Module[\"setStatus\"](\"\")},1);doRun()},1)}else{doRun()}}Module[\"run\"]=run;function exit(status,implicit){if(implicit&&noExitRuntime&&status===0){return}if(!implicit){if(ENVIRONMENT_IS_PTHREAD){postMessage({\"cmd\":\"exitProcess\",\"returnCode\":status});throw new ExitStatus(status)}else{}}if(noExitRuntime){}else{PThread.terminateAllThreads();EXITSTATUS=status;exitRuntime();if(Module[\"onExit\"])Module[\"onExit\"](status);ABORT=true}quit_(status,new ExitStatus(status))}if(Module[\"preInit\"]){if(typeof Module[\"preInit\"]==\"function\")Module[\"preInit\"]=[Module[\"preInit\"]];while(Module[\"preInit\"].length>0){Module[\"preInit\"].pop()()}}if(ENVIRONMENT_IS_PTHREAD){noExitRuntime=false;PThread.initWorker()}run();\n\n\n return WasmBackendModuleThreadedSimd.ready\n}\n);\n})();\nif (typeof exports === 'object' && typeof module === 'object')\n module.exports = WasmBackendModuleThreadedSimd;\nelse if (typeof define === 'function' && define['amd'])\n define([], function() { return WasmBackendModuleThreadedSimd; });\nelse if (typeof exports === 'object')\n exports[\"WasmBackendModuleThreadedSimd\"] = WasmBackendModuleThreadedSimd;\n", "\nvar WasmBackendModule = (function() {\n var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;\n if (typeof __filename !== 'undefined') _scriptDir = _scriptDir || __filename;\n return (\nfunction(WasmBackendModule) {\n WasmBackendModule = WasmBackendModule || {};\n\nvar Module=typeof WasmBackendModule!==\"undefined\"?WasmBackendModule:{};var readyPromiseResolve,readyPromiseReject;Module[\"ready\"]=new Promise(function(resolve,reject){readyPromiseResolve=resolve;readyPromiseReject=reject});var moduleOverrides={};var key;for(key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var arguments_=[];var thisProgram=\"./this.program\";var quit_=function(status,toThrow){throw toThrow};var ENVIRONMENT_IS_WEB=false;var ENVIRONMENT_IS_WORKER=false;var ENVIRONMENT_IS_NODE=false;var ENVIRONMENT_IS_SHELL=false;ENVIRONMENT_IS_WEB=typeof window===\"object\";ENVIRONMENT_IS_WORKER=typeof importScripts===\"function\";ENVIRONMENT_IS_NODE=typeof process===\"object\"&&typeof process.versions===\"object\"&&typeof process.versions.node===\"string\";ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;var scriptDirectory=\"\";function locateFile(path){if(Module[\"locateFile\"]){return Module[\"locateFile\"](path,scriptDirectory)}return scriptDirectory+path}var read_,readAsync,readBinary,setWindowTitle;var nodeFS;var nodePath;if(ENVIRONMENT_IS_NODE){if(ENVIRONMENT_IS_WORKER){scriptDirectory=require(\"path\").dirname(scriptDirectory)+\"/\"}else{scriptDirectory=__dirname+\"/\"}read_=function shell_read(filename,binary){if(!nodeFS)nodeFS=require(\"fs\");if(!nodePath)nodePath=require(\"path\");filename=nodePath[\"normalize\"](filename);return nodeFS[\"readFileSync\"](filename,binary?null:\"utf8\")};readBinary=function readBinary(filename){var ret=read_(filename,true);if(!ret.buffer){ret=new Uint8Array(ret)}assert(ret.buffer);return ret};if(process[\"argv\"].length>1){thisProgram=process[\"argv\"][1].replace(/\\\\/g,\"/\")}arguments_=process[\"argv\"].slice(2);process[\"on\"](\"uncaughtException\",function(ex){if(!(ex instanceof ExitStatus)){throw ex}});process[\"on\"](\"unhandledRejection\",abort);quit_=function(status){process[\"exit\"](status)};Module[\"inspect\"]=function(){return\"[Emscripten Module object]\"}}else if(ENVIRONMENT_IS_SHELL){if(typeof read!=\"undefined\"){read_=function shell_read(f){return read(f)}}readBinary=function readBinary(f){var data;if(typeof readbuffer===\"function\"){return new Uint8Array(readbuffer(f))}data=read(f,\"binary\");assert(typeof data===\"object\");return data};if(typeof scriptArgs!=\"undefined\"){arguments_=scriptArgs}else if(typeof arguments!=\"undefined\"){arguments_=arguments}if(typeof quit===\"function\"){quit_=function(status){quit(status)}}if(typeof print!==\"undefined\"){if(typeof console===\"undefined\")console={};console.log=print;console.warn=console.error=typeof printErr!==\"undefined\"?printErr:print}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(typeof document!==\"undefined\"&&document.currentScript){scriptDirectory=document.currentScript.src}if(_scriptDir){scriptDirectory=_scriptDir}if(scriptDirectory.indexOf(\"blob:\")!==0){scriptDirectory=scriptDirectory.substr(0,scriptDirectory.lastIndexOf(\"/\")+1)}else{scriptDirectory=\"\"}{read_=function(url){var xhr=new XMLHttpRequest;xhr.open(\"GET\",url,false);xhr.send(null);return xhr.responseText};if(ENVIRONMENT_IS_WORKER){readBinary=function(url){var xhr=new XMLHttpRequest;xhr.open(\"GET\",url,false);xhr.responseType=\"arraybuffer\";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=function(url,onload,onerror){var xhr=new XMLHttpRequest;xhr.open(\"GET\",url,true);xhr.responseType=\"arraybuffer\";xhr.onload=function(){if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}onerror()};xhr.onerror=onerror;xhr.send(null)}}setWindowTitle=function(title){document.title=title}}else{}var out=Module[\"print\"]||console.log.bind(console);var err=Module[\"printErr\"]||console.warn.bind(console);for(key in moduleOverrides){if(moduleOverrides.hasOwnProperty(key)){Module[key]=moduleOverrides[key]}}moduleOverrides=null;if(Module[\"arguments\"])arguments_=Module[\"arguments\"];if(Module[\"thisProgram\"])thisProgram=Module[\"thisProgram\"];if(Module[\"quit\"])quit_=Module[\"quit\"];var wasmBinary;if(Module[\"wasmBinary\"])wasmBinary=Module[\"wasmBinary\"];var noExitRuntime=Module[\"noExitRuntime\"]||true;if(typeof WebAssembly!==\"object\"){abort(\"no native wasm support detected\")}var wasmMemory;var ABORT=false;var EXITSTATUS;function assert(condition,text){if(!condition){abort(\"Assertion failed: \"+text)}}function getCFunc(ident){var func=Module[\"_\"+ident];assert(func,\"Cannot call unknown function \"+ident+\", make sure it is exported\");return func}function ccall(ident,returnType,argTypes,args,opts){var toC={\"string\":function(str){var ret=0;if(str!==null&&str!==undefined&&str!==0){var len=(str.length<<2)+1;ret=stackAlloc(len);stringToUTF8(str,ret,len)}return ret},\"array\":function(arr){var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType===\"string\")return UTF8ToString(ret);if(returnType===\"boolean\")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i=endIdx))++endPtr;if(endPtr-idx>16&&heap.subarray&&UTF8Decoder){return UTF8Decoder.decode(heap.subarray(idx,endPtr))}else{var str=\"\";while(idx>10,56320|ch&1023)}}}return str}function UTF8ToString(ptr,maxBytesToRead){return ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):\"\"}function stringToUTF8Array(str,heap,outIdx,maxBytesToWrite){if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}}heap[outIdx]=0;return outIdx-startIdx}function stringToUTF8(str,outPtr,maxBytesToWrite){return stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite)}function writeArrayToMemory(array,buffer){HEAP8.set(array,buffer)}function alignUp(x,multiple){if(x%multiple>0){x+=multiple-x%multiple}return x}var buffer,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateGlobalBufferAndViews(buf){buffer=buf;Module[\"HEAP8\"]=HEAP8=new Int8Array(buf);Module[\"HEAP16\"]=HEAP16=new Int16Array(buf);Module[\"HEAP32\"]=HEAP32=new Int32Array(buf);Module[\"HEAPU8\"]=HEAPU8=new Uint8Array(buf);Module[\"HEAPU16\"]=HEAPU16=new Uint16Array(buf);Module[\"HEAPU32\"]=HEAPU32=new Uint32Array(buf);Module[\"HEAPF32\"]=HEAPF32=new Float32Array(buf);Module[\"HEAPF64\"]=HEAPF64=new Float64Array(buf)}var INITIAL_MEMORY=Module[\"INITIAL_MEMORY\"]||16777216;var wasmTable;var __ATPRERUN__=[];var __ATINIT__=[];var __ATMAIN__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;__ATINIT__.push({func:function(){___wasm_call_ctors()}});function preRun(){if(Module[\"preRun\"]){if(typeof Module[\"preRun\"]==\"function\")Module[\"preRun\"]=[Module[\"preRun\"]];while(Module[\"preRun\"].length){addOnPreRun(Module[\"preRun\"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;callRuntimeCallbacks(__ATINIT__)}function preMain(){callRuntimeCallbacks(__ATMAIN__)}function postRun(){if(Module[\"postRun\"]){if(typeof Module[\"postRun\"]==\"function\")Module[\"postRun\"]=[Module[\"postRun\"]];while(Module[\"postRun\"].length){addOnPostRun(Module[\"postRun\"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function addRunDependency(id){runDependencies++;if(Module[\"monitorRunDependencies\"]){Module[\"monitorRunDependencies\"](runDependencies)}}function removeRunDependency(id){runDependencies--;if(Module[\"monitorRunDependencies\"]){Module[\"monitorRunDependencies\"](runDependencies)}if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}Module[\"preloadedImages\"]={};Module[\"preloadedAudios\"]={};function abort(what){if(Module[\"onAbort\"]){Module[\"onAbort\"](what)}what+=\"\";err(what);ABORT=true;EXITSTATUS=1;what=\"abort(\"+what+\"). Build with -s ASSERTIONS=1 for more info.\";var e=new WebAssembly.RuntimeError(what);readyPromiseReject(e);throw e}function hasPrefix(str,prefix){return String.prototype.startsWith?str.startsWith(prefix):str.indexOf(prefix)===0}var dataURIPrefix=\"data:application/octet-stream;base64,\";function isDataURI(filename){return hasPrefix(filename,dataURIPrefix)}var fileURIPrefix=\"file://\";function isFileURI(filename){return hasPrefix(filename,fileURIPrefix)}var wasmBinaryFile=\"tfjs-backend-wasm.wasm\";if(!isDataURI(wasmBinaryFile)){wasmBinaryFile=locateFile(wasmBinaryFile)}function getBinary(file){try{if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}else{throw\"both async and sync fetching of the wasm failed\"}}catch(err){abort(err)}}function getBinaryPromise(){if(!wasmBinary&&(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)){if(typeof fetch===\"function\"&&!isFileURI(wasmBinaryFile)){return fetch(wasmBinaryFile,{credentials:\"same-origin\"}).then(function(response){if(!response[\"ok\"]){throw\"failed to load wasm binary file at '\"+wasmBinaryFile+\"'\"}return response[\"arrayBuffer\"]()}).catch(function(){return getBinary(wasmBinaryFile)})}else{if(readAsync){return new Promise(function(resolve,reject){readAsync(wasmBinaryFile,function(response){resolve(new Uint8Array(response))},reject)})}}}return Promise.resolve().then(function(){return getBinary(wasmBinaryFile)})}function createWasm(){var info={\"a\":asmLibraryArg};function receiveInstance(instance,module){var exports=instance.exports;Module[\"asm\"]=exports;wasmMemory=Module[\"asm\"][\"h\"];updateGlobalBufferAndViews(wasmMemory.buffer);wasmTable=Module[\"asm\"][\"Sa\"];removeRunDependency(\"wasm-instantiate\")}addRunDependency(\"wasm-instantiate\");function receiveInstantiatedSource(output){receiveInstance(output[\"instance\"])}function instantiateArrayBuffer(receiver){return getBinaryPromise().then(function(binary){return WebAssembly.instantiate(binary,info)}).then(receiver,function(reason){err(\"failed to asynchronously prepare wasm: \"+reason);abort(reason)})}function instantiateAsync(){if(!wasmBinary&&typeof WebAssembly.instantiateStreaming===\"function\"&&!isDataURI(wasmBinaryFile)&&!isFileURI(wasmBinaryFile)&&typeof fetch===\"function\"){return fetch(wasmBinaryFile,{credentials:\"same-origin\"}).then(function(response){var result=WebAssembly.instantiateStreaming(response,info);return result.then(receiveInstantiatedSource,function(reason){err(\"wasm streaming compile failed: \"+reason);err(\"falling back to ArrayBuffer instantiation\");return instantiateArrayBuffer(receiveInstantiatedSource)})})}else{return instantiateArrayBuffer(receiveInstantiatedSource)}}if(Module[\"instantiateWasm\"]){try{var exports=Module[\"instantiateWasm\"](info,receiveInstance);return exports}catch(e){err(\"Module.instantiateWasm callback failed with error: \"+e);return false}}instantiateAsync().catch(readyPromiseReject);return{}}function callRuntimeCallbacks(callbacks){while(callbacks.length>0){var callback=callbacks.shift();if(typeof callback==\"function\"){callback(Module);continue}var func=callback.func;if(typeof func===\"number\"){if(callback.arg===undefined){wasmTable.get(func)()}else{wasmTable.get(func)(callback.arg)}}else{func(callback.arg===undefined?null:callback.arg)}}}function _abort(){abort()}function _emscripten_memcpy_big(dest,src,num){HEAPU8.copyWithin(dest,src,src+num)}function _emscripten_get_heap_size(){return HEAPU8.length}function emscripten_realloc_buffer(size){try{wasmMemory.grow(size-buffer.byteLength+65535>>>16);updateGlobalBufferAndViews(wasmMemory.buffer);return 1}catch(e){}}function _emscripten_resize_heap(requestedSize){var oldSize=_emscripten_get_heap_size();var maxHeapSize=2147483648;if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignUp(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=emscripten_realloc_buffer(newSize);if(replacement){return true}}return false}var SYSCALLS={mappings:{},buffers:[null,[],[]],printChar:function(stream,curr){var buffer=SYSCALLS.buffers[stream];if(curr===0||curr===10){(stream===1?out:err)(UTF8ArrayToString(buffer,0));buffer.length=0}else{buffer.push(curr)}},varargs:undefined,get:function(){SYSCALLS.varargs+=4;var ret=HEAP32[SYSCALLS.varargs-4>>2];return ret},getStr:function(ptr){var ret=UTF8ToString(ptr);return ret},get64:function(low,high){return low}};function _fd_close(fd){return 0}function _fd_seek(fd,offset_low,offset_high,whence,newOffset){}function _fd_write(fd,iov,iovcnt,pnum){var num=0;for(var i=0;i>2];var len=HEAP32[iov+(i*8+4)>>2];for(var j=0;j>2]=num;return 0}function _pthread_join(){return 28}var asmLibraryArg={\"a\":_abort,\"d\":_emscripten_memcpy_big,\"e\":_emscripten_resize_heap,\"f\":_fd_close,\"c\":_fd_seek,\"b\":_fd_write,\"g\":_pthread_join};var asm=createWasm();var ___wasm_call_ctors=Module[\"___wasm_call_ctors\"]=function(){return(___wasm_call_ctors=Module[\"___wasm_call_ctors\"]=Module[\"asm\"][\"i\"]).apply(null,arguments)};var _init=Module[\"_init\"]=function(){return(_init=Module[\"_init\"]=Module[\"asm\"][\"j\"]).apply(null,arguments)};var _init_with_threads_count=Module[\"_init_with_threads_count\"]=function(){return(_init_with_threads_count=Module[\"_init_with_threads_count\"]=Module[\"asm\"][\"k\"]).apply(null,arguments)};var _get_threads_count=Module[\"_get_threads_count\"]=function(){return(_get_threads_count=Module[\"_get_threads_count\"]=Module[\"asm\"][\"l\"]).apply(null,arguments)};var _register_tensor=Module[\"_register_tensor\"]=function(){return(_register_tensor=Module[\"_register_tensor\"]=Module[\"asm\"][\"m\"]).apply(null,arguments)};var _dispose_data=Module[\"_dispose_data\"]=function(){return(_dispose_data=Module[\"_dispose_data\"]=Module[\"asm\"][\"n\"]).apply(null,arguments)};var _dispose=Module[\"_dispose\"]=function(){return(_dispose=Module[\"_dispose\"]=Module[\"asm\"][\"o\"]).apply(null,arguments)};var _Abs=Module[\"_Abs\"]=function(){return(_Abs=Module[\"_Abs\"]=Module[\"asm\"][\"p\"]).apply(null,arguments)};var _Add=Module[\"_Add\"]=function(){return(_Add=Module[\"_Add\"]=Module[\"asm\"][\"q\"]).apply(null,arguments)};var _AddN=Module[\"_AddN\"]=function(){return(_AddN=Module[\"_AddN\"]=Module[\"asm\"][\"r\"]).apply(null,arguments)};var _All=Module[\"_All\"]=function(){return(_All=Module[\"_All\"]=Module[\"asm\"][\"s\"]).apply(null,arguments)};var _Any=Module[\"_Any\"]=function(){return(_Any=Module[\"_Any\"]=Module[\"asm\"][\"t\"]).apply(null,arguments)};var _ArgMax=Module[\"_ArgMax\"]=function(){return(_ArgMax=Module[\"_ArgMax\"]=Module[\"asm\"][\"u\"]).apply(null,arguments)};var _AvgPool=Module[\"_AvgPool\"]=function(){return(_AvgPool=Module[\"_AvgPool\"]=Module[\"asm\"][\"v\"]).apply(null,arguments)};var _BatchMatMul=Module[\"_BatchMatMul\"]=function(){return(_BatchMatMul=Module[\"_BatchMatMul\"]=Module[\"asm\"][\"w\"]).apply(null,arguments)};var _Ceil=Module[\"_Ceil\"]=function(){return(_Ceil=Module[\"_Ceil\"]=Module[\"asm\"][\"x\"]).apply(null,arguments)};var _ClipByValue=Module[\"_ClipByValue\"]=function(){return(_ClipByValue=Module[\"_ClipByValue\"]=Module[\"asm\"][\"y\"]).apply(null,arguments)};var _Conv2D=Module[\"_Conv2D\"]=function(){return(_Conv2D=Module[\"_Conv2D\"]=Module[\"asm\"][\"z\"]).apply(null,arguments)};var _Conv2DBackpropInput=Module[\"_Conv2DBackpropInput\"]=function(){return(_Conv2DBackpropInput=Module[\"_Conv2DBackpropInput\"]=Module[\"asm\"][\"A\"]).apply(null,arguments)};var _Cos=Module[\"_Cos\"]=function(){return(_Cos=Module[\"_Cos\"]=Module[\"asm\"][\"B\"]).apply(null,arguments)};var _Cosh=Module[\"_Cosh\"]=function(){return(_Cosh=Module[\"_Cosh\"]=Module[\"asm\"][\"C\"]).apply(null,arguments)};var _CropAndResize=Module[\"_CropAndResize\"]=function(){return(_CropAndResize=Module[\"_CropAndResize\"]=Module[\"asm\"][\"D\"]).apply(null,arguments)};var _Cumsum=Module[\"_Cumsum\"]=function(){return(_Cumsum=Module[\"_Cumsum\"]=Module[\"asm\"][\"E\"]).apply(null,arguments)};var _DepthToSpace=Module[\"_DepthToSpace\"]=function(){return(_DepthToSpace=Module[\"_DepthToSpace\"]=Module[\"asm\"][\"F\"]).apply(null,arguments)};var _DepthwiseConv2dNative=Module[\"_DepthwiseConv2dNative\"]=function(){return(_DepthwiseConv2dNative=Module[\"_DepthwiseConv2dNative\"]=Module[\"asm\"][\"G\"]).apply(null,arguments)};var _Elu=Module[\"_Elu\"]=function(){return(_Elu=Module[\"_Elu\"]=Module[\"asm\"][\"H\"]).apply(null,arguments)};var _Equal=Module[\"_Equal\"]=function(){return(_Equal=Module[\"_Equal\"]=Module[\"asm\"][\"I\"]).apply(null,arguments)};var _Exp=Module[\"_Exp\"]=function(){return(_Exp=Module[\"_Exp\"]=Module[\"asm\"][\"J\"]).apply(null,arguments)};var _FlipLeftRight=Module[\"_FlipLeftRight\"]=function(){return(_FlipLeftRight=Module[\"_FlipLeftRight\"]=Module[\"asm\"][\"K\"]).apply(null,arguments)};var _Floor=Module[\"_Floor\"]=function(){return(_Floor=Module[\"_Floor\"]=Module[\"asm\"][\"L\"]).apply(null,arguments)};var _FloorDiv=Module[\"_FloorDiv\"]=function(){return(_FloorDiv=Module[\"_FloorDiv\"]=Module[\"asm\"][\"M\"]).apply(null,arguments)};var _FusedBatchNorm=Module[\"_FusedBatchNorm\"]=function(){return(_FusedBatchNorm=Module[\"_FusedBatchNorm\"]=Module[\"asm\"][\"N\"]).apply(null,arguments)};var _FusedConv2D=Module[\"_FusedConv2D\"]=function(){return(_FusedConv2D=Module[\"_FusedConv2D\"]=Module[\"asm\"][\"O\"]).apply(null,arguments)};var _FusedDepthwiseConv2D=Module[\"_FusedDepthwiseConv2D\"]=function(){return(_FusedDepthwiseConv2D=Module[\"_FusedDepthwiseConv2D\"]=Module[\"asm\"][\"P\"]).apply(null,arguments)};var _Gather=Module[\"_Gather\"]=function(){return(_Gather=Module[\"_Gather\"]=Module[\"asm\"][\"Q\"]).apply(null,arguments)};var _GatherNd=Module[\"_GatherNd\"]=function(){return(_GatherNd=Module[\"_GatherNd\"]=Module[\"asm\"][\"R\"]).apply(null,arguments)};var _Greater=Module[\"_Greater\"]=function(){return(_Greater=Module[\"_Greater\"]=Module[\"asm\"][\"S\"]).apply(null,arguments)};var _GreaterEqual=Module[\"_GreaterEqual\"]=function(){return(_GreaterEqual=Module[\"_GreaterEqual\"]=Module[\"asm\"][\"T\"]).apply(null,arguments)};var _LeakyRelu=Module[\"_LeakyRelu\"]=function(){return(_LeakyRelu=Module[\"_LeakyRelu\"]=Module[\"asm\"][\"U\"]).apply(null,arguments)};var _Less=Module[\"_Less\"]=function(){return(_Less=Module[\"_Less\"]=Module[\"asm\"][\"V\"]).apply(null,arguments)};var _LessEqual=Module[\"_LessEqual\"]=function(){return(_LessEqual=Module[\"_LessEqual\"]=Module[\"asm\"][\"W\"]).apply(null,arguments)};var _Log=Module[\"_Log\"]=function(){return(_Log=Module[\"_Log\"]=Module[\"asm\"][\"X\"]).apply(null,arguments)};var _LogicalAnd=Module[\"_LogicalAnd\"]=function(){return(_LogicalAnd=Module[\"_LogicalAnd\"]=Module[\"asm\"][\"Y\"]).apply(null,arguments)};var _Max=Module[\"_Max\"]=function(){return(_Max=Module[\"_Max\"]=Module[\"asm\"][\"Z\"]).apply(null,arguments)};var _MaxPool=Module[\"_MaxPool\"]=function(){return(_MaxPool=Module[\"_MaxPool\"]=Module[\"asm\"][\"_\"]).apply(null,arguments)};var _Maximum=Module[\"_Maximum\"]=function(){return(_Maximum=Module[\"_Maximum\"]=Module[\"asm\"][\"$\"]).apply(null,arguments)};var _Mean=Module[\"_Mean\"]=function(){return(_Mean=Module[\"_Mean\"]=Module[\"asm\"][\"aa\"]).apply(null,arguments)};var _Min=Module[\"_Min\"]=function(){return(_Min=Module[\"_Min\"]=Module[\"asm\"][\"ba\"]).apply(null,arguments)};var _Minimum=Module[\"_Minimum\"]=function(){return(_Minimum=Module[\"_Minimum\"]=Module[\"asm\"][\"ca\"]).apply(null,arguments)};var _MirrorPad=Module[\"_MirrorPad\"]=function(){return(_MirrorPad=Module[\"_MirrorPad\"]=Module[\"asm\"][\"da\"]).apply(null,arguments)};var _Multiply=Module[\"_Multiply\"]=function(){return(_Multiply=Module[\"_Multiply\"]=Module[\"asm\"][\"ea\"]).apply(null,arguments)};var _Neg=Module[\"_Neg\"]=function(){return(_Neg=Module[\"_Neg\"]=Module[\"asm\"][\"fa\"]).apply(null,arguments)};var _NonMaxSuppressionV3=Module[\"_NonMaxSuppressionV3\"]=function(){return(_NonMaxSuppressionV3=Module[\"_NonMaxSuppressionV3\"]=Module[\"asm\"][\"ga\"]).apply(null,arguments)};var _NonMaxSuppressionV4=Module[\"_NonMaxSuppressionV4\"]=function(){return(_NonMaxSuppressionV4=Module[\"_NonMaxSuppressionV4\"]=Module[\"asm\"][\"ha\"]).apply(null,arguments)};var _NonMaxSuppressionV5=Module[\"_NonMaxSuppressionV5\"]=function(){return(_NonMaxSuppressionV5=Module[\"_NonMaxSuppressionV5\"]=Module[\"asm\"][\"ia\"]).apply(null,arguments)};var _NotEqual=Module[\"_NotEqual\"]=function(){return(_NotEqual=Module[\"_NotEqual\"]=Module[\"asm\"][\"ja\"]).apply(null,arguments)};var _OneHot=Module[\"_OneHot\"]=function(){return(_OneHot=Module[\"_OneHot\"]=Module[\"asm\"][\"ka\"]).apply(null,arguments)};var _PadV2=Module[\"_PadV2\"]=function(){return(_PadV2=Module[\"_PadV2\"]=Module[\"asm\"][\"la\"]).apply(null,arguments)};var _Pow=Module[\"_Pow\"]=function(){return(_Pow=Module[\"_Pow\"]=Module[\"asm\"][\"ma\"]).apply(null,arguments)};var _Prelu=Module[\"_Prelu\"]=function(){return(_Prelu=Module[\"_Prelu\"]=Module[\"asm\"][\"na\"]).apply(null,arguments)};var _Prod=Module[\"_Prod\"]=function(){return(_Prod=Module[\"_Prod\"]=Module[\"asm\"][\"oa\"]).apply(null,arguments)};var _RealDiv=Module[\"_RealDiv\"]=function(){return(_RealDiv=Module[\"_RealDiv\"]=Module[\"asm\"][\"pa\"]).apply(null,arguments)};var _Relu=Module[\"_Relu\"]=function(){return(_Relu=Module[\"_Relu\"]=Module[\"asm\"][\"qa\"]).apply(null,arguments)};var _Relu6=Module[\"_Relu6\"]=function(){return(_Relu6=Module[\"_Relu6\"]=Module[\"asm\"][\"ra\"]).apply(null,arguments)};var _ResizeBilinear=Module[\"_ResizeBilinear\"]=function(){return(_ResizeBilinear=Module[\"_ResizeBilinear\"]=Module[\"asm\"][\"sa\"]).apply(null,arguments)};var _Reverse=Module[\"_Reverse\"]=function(){return(_Reverse=Module[\"_Reverse\"]=Module[\"asm\"][\"ta\"]).apply(null,arguments)};var _RotateWithOffset=Module[\"_RotateWithOffset\"]=function(){return(_RotateWithOffset=Module[\"_RotateWithOffset\"]=Module[\"asm\"][\"ua\"]).apply(null,arguments)};var _Round=Module[\"_Round\"]=function(){return(_Round=Module[\"_Round\"]=Module[\"asm\"][\"va\"]).apply(null,arguments)};var _Rsqrt=Module[\"_Rsqrt\"]=function(){return(_Rsqrt=Module[\"_Rsqrt\"]=Module[\"asm\"][\"wa\"]).apply(null,arguments)};var _ScatterNd=Module[\"_ScatterNd\"]=function(){return(_ScatterNd=Module[\"_ScatterNd\"]=Module[\"asm\"][\"xa\"]).apply(null,arguments)};var _SelectV2=Module[\"_SelectV2\"]=function(){return(_SelectV2=Module[\"_SelectV2\"]=Module[\"asm\"][\"ya\"]).apply(null,arguments)};var _Sigmoid=Module[\"_Sigmoid\"]=function(){return(_Sigmoid=Module[\"_Sigmoid\"]=Module[\"asm\"][\"za\"]).apply(null,arguments)};var _Sin=Module[\"_Sin\"]=function(){return(_Sin=Module[\"_Sin\"]=Module[\"asm\"][\"Aa\"]).apply(null,arguments)};var _Softmax=Module[\"_Softmax\"]=function(){return(_Softmax=Module[\"_Softmax\"]=Module[\"asm\"][\"Ba\"]).apply(null,arguments)};var _Sqrt=Module[\"_Sqrt\"]=function(){return(_Sqrt=Module[\"_Sqrt\"]=Module[\"asm\"][\"Ca\"]).apply(null,arguments)};var _Square=Module[\"_Square\"]=function(){return(_Square=Module[\"_Square\"]=Module[\"asm\"][\"Da\"]).apply(null,arguments)};var _SquaredDifference=Module[\"_SquaredDifference\"]=function(){return(_SquaredDifference=Module[\"_SquaredDifference\"]=Module[\"asm\"][\"Ea\"]).apply(null,arguments)};var _Step=Module[\"_Step\"]=function(){return(_Step=Module[\"_Step\"]=Module[\"asm\"][\"Fa\"]).apply(null,arguments)};var _StridedSlice=Module[\"_StridedSlice\"]=function(){return(_StridedSlice=Module[\"_StridedSlice\"]=Module[\"asm\"][\"Ga\"]).apply(null,arguments)};var _Sub=Module[\"_Sub\"]=function(){return(_Sub=Module[\"_Sub\"]=Module[\"asm\"][\"Ha\"]).apply(null,arguments)};var _Sum=Module[\"_Sum\"]=function(){return(_Sum=Module[\"_Sum\"]=Module[\"asm\"][\"Ia\"]).apply(null,arguments)};var _Tan=Module[\"_Tan\"]=function(){return(_Tan=Module[\"_Tan\"]=Module[\"asm\"][\"Ja\"]).apply(null,arguments)};var _Tanh=Module[\"_Tanh\"]=function(){return(_Tanh=Module[\"_Tanh\"]=Module[\"asm\"][\"Ka\"]).apply(null,arguments)};var _Tile=Module[\"_Tile\"]=function(){return(_Tile=Module[\"_Tile\"]=Module[\"asm\"][\"La\"]).apply(null,arguments)};var _TopK=Module[\"_TopK\"]=function(){return(_TopK=Module[\"_TopK\"]=Module[\"asm\"][\"Ma\"]).apply(null,arguments)};var _Transform=Module[\"_Transform\"]=function(){return(_Transform=Module[\"_Transform\"]=Module[\"asm\"][\"Na\"]).apply(null,arguments)};var _Transpose=Module[\"_Transpose\"]=function(){return(_Transpose=Module[\"_Transpose\"]=Module[\"asm\"][\"Oa\"]).apply(null,arguments)};var __FusedMatMul=Module[\"__FusedMatMul\"]=function(){return(__FusedMatMul=Module[\"__FusedMatMul\"]=Module[\"asm\"][\"Pa\"]).apply(null,arguments)};var _malloc=Module[\"_malloc\"]=function(){return(_malloc=Module[\"_malloc\"]=Module[\"asm\"][\"Qa\"]).apply(null,arguments)};var _free=Module[\"_free\"]=function(){return(_free=Module[\"_free\"]=Module[\"asm\"][\"Ra\"]).apply(null,arguments)};var stackSave=Module[\"stackSave\"]=function(){return(stackSave=Module[\"stackSave\"]=Module[\"asm\"][\"Ta\"]).apply(null,arguments)};var stackRestore=Module[\"stackRestore\"]=function(){return(stackRestore=Module[\"stackRestore\"]=Module[\"asm\"][\"Ua\"]).apply(null,arguments)};var stackAlloc=Module[\"stackAlloc\"]=function(){return(stackAlloc=Module[\"stackAlloc\"]=Module[\"asm\"][\"Va\"]).apply(null,arguments)};Module[\"cwrap\"]=cwrap;var calledRun;function ExitStatus(status){this.name=\"ExitStatus\";this.message=\"Program terminated with exit(\"+status+\")\";this.status=status}dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function run(args){args=args||arguments_;if(runDependencies>0){return}preRun();if(runDependencies>0){return}function doRun(){if(calledRun)return;calledRun=true;Module[\"calledRun\"]=true;if(ABORT)return;initRuntime();preMain();readyPromiseResolve(Module);if(Module[\"onRuntimeInitialized\"])Module[\"onRuntimeInitialized\"]();postRun()}if(Module[\"setStatus\"]){Module[\"setStatus\"](\"Running...\");setTimeout(function(){setTimeout(function(){Module[\"setStatus\"](\"\")},1);doRun()},1)}else{doRun()}}Module[\"run\"]=run;if(Module[\"preInit\"]){if(typeof Module[\"preInit\"]==\"function\")Module[\"preInit\"]=[Module[\"preInit\"]];while(Module[\"preInit\"].length>0){Module[\"preInit\"].pop()()}}run();\n\n\n return WasmBackendModule.ready\n}\n);\n})();\nif (typeof exports === 'object' && typeof module === 'object')\n module.exports = WasmBackendModule;\nelse if (typeof define === 'function' && define['amd'])\n define([], function() { return WasmBackendModule; });\nelse if (typeof exports === 'object')\n exports[\"WasmBackendModule\"] = WasmBackendModule;\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Backend, DataId} from '../tensor';\nimport {BackendValues, DataType} from '../types';\n\nexport const EPSILON_FLOAT32 = 1e-7;\nexport const EPSILON_FLOAT16 = 1e-4;\n\n// Required information for all backends.\nexport interface BackendTimingInfo {\n kernelMs: number|{error: string};\n getExtraProfileInfo?(): string; // a field for additional timing information\n // e.g. packing / unpacking for WebGL backend\n}\n\nexport interface TensorStorage {\n read(dataId: DataId): Promise;\n readSync(dataId: DataId): BackendValues;\n disposeData(dataId: DataId, force?: boolean): boolean;\n write(values: BackendValues, shape: number[], dtype: DataType): DataId;\n move(\n dataId: DataId, values: BackendValues, shape: number[], dtype: DataType,\n refCount: number): void;\n memory(): {unreliable: boolean;}; // Backend-specific information.\n /** Returns number of data ids currently in the storage. */\n numDataIds(): number;\n refCount(dataId: DataId): number;\n}\n\n/** Convenient class for storing tensor-related data. */\nexport class DataStorage {\n private data = new WeakMap();\n private dataIdsCount = 0;\n\n constructor(private backend: KernelBackend, private dataMover: DataMover) {}\n\n get(dataId: DataId) {\n if (!this.data.has(dataId)) {\n this.dataMover.moveData(this.backend, dataId);\n }\n return this.data.get(dataId);\n }\n\n set(dataId: DataId, value: T): void {\n this.dataIdsCount++;\n this.data.set(dataId, value);\n }\n\n has(dataId: DataId): boolean {\n return this.data.has(dataId);\n }\n\n delete(dataId: DataId): boolean {\n this.dataIdsCount--;\n return this.data.delete(dataId);\n }\n\n numDataIds(): number {\n return this.dataIdsCount;\n }\n}\n\nexport interface DataMover {\n /**\n * To be called by backends whenever they see a dataId that they don't own.\n * Upon calling this method, the mover will fetch the tensor from another\n * backend and register it with the current active backend.\n */\n moveData(backend: KernelBackend, dataId: DataId): void;\n}\n\nexport interface BackendTimer {\n // check if backend timer is available\n timerAvailable(): boolean;\n time(f: () => void): Promise;\n}\n\n/**\n * The interface that defines the kernels that should be implemented when\n * adding a new backend. New backends don't need to implement every one of the\n * methods, this can be done gradually (throw an error for unimplemented\n * methods).\n */\nexport class KernelBackend implements TensorStorage, Backend, BackendTimer {\n refCount(dataId: DataId): number {\n return notYetImplemented('refCount');\n }\n incRef(dataId: DataId): void {\n return notYetImplemented('incRef');\n }\n timerAvailable(): boolean {\n return true;\n }\n time(f: () => void): Promise {\n return notYetImplemented('time');\n }\n read(dataId: object): Promise {\n return notYetImplemented('read');\n }\n readSync(dataId: object): BackendValues {\n return notYetImplemented('readSync');\n }\n numDataIds(): number {\n return notYetImplemented('numDataIds');\n }\n disposeData(dataId: object, force?: boolean): boolean {\n return notYetImplemented('disposeData');\n }\n write(values: BackendValues, shape: number[], dtype: DataType): DataId {\n return notYetImplemented('write');\n }\n move(\n dataId: DataId, values: BackendValues, shape: number[], dtype: DataType,\n refCount: number): void {\n return notYetImplemented('move');\n }\n memory(): {unreliable: boolean; reasons?: string[]} {\n return notYetImplemented('memory');\n }\n /** Returns the highest precision for floats in bits (e.g. 16 or 32) */\n floatPrecision(): 16|32 {\n return notYetImplemented('floatPrecision');\n }\n /** Returns the smallest representable number. */\n epsilon(): number {\n return this.floatPrecision() === 32 ? EPSILON_FLOAT32 : EPSILON_FLOAT16;\n }\n dispose(): void {\n return notYetImplemented('dispose');\n }\n}\n\nfunction notYetImplemented(kernelName: string): never {\n throw new Error(\n `'${kernelName}' not yet implemented or not found in the registry. ` +\n `This kernel may not be supported by the tfjs backend you have chosen`);\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, DataTypeMap, FlatVector, NumericDataType, RecursiveArray, TensorLike, TypedArray} from './types';\n\n/**\n * Shuffles the array in-place using Fisher-Yates algorithm.\n *\n * ```js\n * const a = [1, 2, 3, 4, 5];\n * tf.util.shuffle(a);\n * console.log(a);\n * ```\n *\n * @param array The array to shuffle in-place.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\n// tslint:disable-next-line:no-any\nexport function shuffle(array: any[]|Uint32Array|Int32Array|\n Float32Array): void {\n let counter = array.length;\n let index = 0;\n // While there are elements in the array\n while (counter > 0) {\n // Pick a random index\n index = (Math.random() * counter) | 0;\n // Decrease counter by 1\n counter--;\n // And swap the last element with it\n swap(array, counter, index);\n }\n}\n\n/**\n * Shuffles two arrays in-place the same way using Fisher-Yates algorithm.\n *\n * ```js\n * const a = [1,2,3,4,5];\n * const b = [11,22,33,44,55];\n * tf.util.shuffleCombo(a, b);\n * console.log(a, b);\n * ```\n *\n * @param array The first array to shuffle in-place.\n * @param array2 The second array to shuffle in-place with the same permutation\n * as the first array.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function shuffleCombo(\n // tslint:disable-next-line:no-any\n array: any[]|Uint32Array|Int32Array|Float32Array,\n // tslint:disable-next-line:no-any\n array2: any[]|Uint32Array|Int32Array|Float32Array): void {\n if (array.length !== array2.length) {\n throw new Error(\n `Array sizes must match to be shuffled together ` +\n `First array length was ${array.length}` +\n `Second array length was ${array2.length}`);\n }\n let counter = array.length;\n let index = 0;\n // While there are elements in the array\n while (counter > 0) {\n // Pick a random index\n index = (Math.random() * counter) | 0;\n // Decrease counter by 1\n counter--;\n // And swap the last element of each array with it\n swap(array, counter, index);\n swap(array2, counter, index);\n }\n}\n\n/** Clamps a value to a specified range. */\nexport function clamp(min: number, x: number, max: number): number {\n return Math.max(min, Math.min(x, max));\n}\n\nexport function nearestLargerEven(val: number): number {\n return val % 2 === 0 ? val : val + 1;\n}\n\nexport function swap(\n object: {[index: number]: T}, left: number, right: number) {\n const temp = object[left];\n object[left] = object[right];\n object[right] = temp;\n}\n\nexport function sum(arr: number[]): number {\n let sum = 0;\n for (let i = 0; i < arr.length; i++) {\n sum += arr[i];\n }\n return sum;\n}\n\n/**\n * Returns a sample from a uniform [a, b) distribution.\n *\n * @param a The minimum support (inclusive).\n * @param b The maximum support (exclusive).\n * @return A pseudorandom number on the half-open interval [a,b).\n */\nexport function randUniform(a: number, b: number) {\n const r = Math.random();\n return (b * r) + (1 - r) * a;\n}\n\n/** Returns the squared Euclidean distance between two vectors. */\nexport function distSquared(a: FlatVector, b: FlatVector): number {\n let result = 0;\n for (let i = 0; i < a.length; i++) {\n const diff = Number(a[i]) - Number(b[i]);\n result += diff * diff;\n }\n return result;\n}\n\n/**\n * Asserts that the expression is true. Otherwise throws an error with the\n * provided message.\n *\n * ```js\n * const x = 2;\n * tf.util.assert(x === 2, 'x is not 2');\n * ```\n *\n * @param expr The expression to assert (as a boolean).\n * @param msg A function that returns the message to report when throwing an\n * error. We use a function for performance reasons.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function assert(expr: boolean, msg: () => string) {\n if (!expr) {\n throw new Error(typeof msg === 'string' ? msg : msg());\n }\n}\n\nexport function assertShapesMatch(\n shapeA: number[], shapeB: number[], errorMessagePrefix = ''): void {\n assert(\n arraysEqual(shapeA, shapeB),\n () => errorMessagePrefix + ` Shapes ${shapeA} and ${shapeB} must match`);\n}\n\nexport function assertNonNull(a: TensorLike): void {\n assert(\n a != null,\n () => `The input to the tensor constructor must be a non-null value.`);\n}\n\n// NOTE: We explicitly type out what T extends instead of any so that\n// util.flatten on a nested array of number doesn't try to infer T as a\n// number[][], causing us to explicitly type util.flatten().\n/**\n * Flattens an arbitrarily nested array.\n *\n * ```js\n * const a = [[1, 2], [3, 4], [5, [6, [7]]]];\n * const flat = tf.util.flatten(a);\n * console.log(flat);\n * ```\n *\n * @param arr The nested array to flatten.\n * @param result The destination array which holds the elements.\n * @param skipTypedArray If true, avoids flattening the typed arrays. Defaults\n * to false.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function\nflatten|TypedArray>(\n arr: T|RecursiveArray, result: T[] = [], skipTypedArray = false): T[] {\n if (result == null) {\n result = [];\n }\n if (Array.isArray(arr) || isTypedArray(arr) && !skipTypedArray) {\n for (let i = 0; i < arr.length; ++i) {\n flatten(arr[i], result, skipTypedArray);\n }\n } else {\n result.push(arr as T);\n }\n return result;\n}\n\n/**\n * Returns the size (number of elements) of the tensor given its shape.\n *\n * ```js\n * const shape = [3, 4, 2];\n * const size = tf.util.sizeFromShape(shape);\n * console.log(size);\n * ```\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function sizeFromShape(shape: number[]): number {\n if (shape.length === 0) {\n // Scalar.\n return 1;\n }\n let size = shape[0];\n for (let i = 1; i < shape.length; i++) {\n size *= shape[i];\n }\n return size;\n}\n\nexport function isScalarShape(shape: number[]): boolean {\n return shape.length === 0;\n}\n\nexport function arraysEqual(n1: FlatVector, n2: FlatVector) {\n if (n1 === n2) {\n return true;\n }\n if (n1 == null || n2 == null) {\n return false;\n }\n\n if (n1.length !== n2.length) {\n return false;\n }\n for (let i = 0; i < n1.length; i++) {\n if (n1[i] !== n2[i]) {\n return false;\n }\n }\n return true;\n}\n\nexport function isInt(a: number): boolean {\n return a % 1 === 0;\n}\n\nexport function tanh(x: number): number {\n // tslint:disable-next-line:no-any\n if ((Math as any).tanh != null) {\n // tslint:disable-next-line:no-any\n return (Math as any).tanh(x);\n }\n if (x === Infinity) {\n return 1;\n } else if (x === -Infinity) {\n return -1;\n } else {\n const e2x = Math.exp(2 * x);\n return (e2x - 1) / (e2x + 1);\n }\n}\n\nexport function sizeToSquarishShape(size: number): [number, number] {\n const width = Math.ceil(Math.sqrt(size));\n return [width, Math.ceil(size / width)];\n}\n\n/**\n * Creates a new array with randomized indicies to a given quantity.\n *\n * ```js\n * const randomTen = tf.util.createShuffledIndices(10);\n * console.log(randomTen);\n * ```\n *\n * @param number Quantity of how many shuffled indicies to create.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function createShuffledIndices(n: number): Uint32Array {\n const shuffledIndices = new Uint32Array(n);\n for (let i = 0; i < n; ++i) {\n shuffledIndices[i] = i;\n }\n shuffle(shuffledIndices);\n return shuffledIndices;\n}\n\nexport function rightPad(a: string, size: number): string {\n if (size <= a.length) {\n return a;\n }\n return a + ' '.repeat(size - a.length);\n}\n\nexport function repeatedTry(\n checkFn: () => boolean, delayFn = (counter: number) => 0,\n maxCounter?: number): Promise {\n return new Promise((resolve, reject) => {\n let tryCount = 0;\n\n const tryFn = () => {\n if (checkFn()) {\n resolve();\n return;\n }\n\n tryCount++;\n\n const nextBackoff = delayFn(tryCount);\n\n if (maxCounter != null && tryCount >= maxCounter) {\n reject();\n return;\n }\n setTimeout(tryFn, nextBackoff);\n };\n\n tryFn();\n });\n}\n\n/**\n * Given the full size of the array and a shape that may contain -1 as the\n * implicit dimension, returns the inferred shape where -1 is replaced.\n * E.g. For shape=[2, -1, 3] and size=24, it will return [2, 4, 3].\n *\n * @param shape The shape, which may contain -1 in some dimension.\n * @param size The full size (number of elements) of the array.\n * @return The inferred shape where -1 is replaced with the inferred size.\n */\nexport function inferFromImplicitShape(\n shape: number[], size: number): number[] {\n let shapeProd = 1;\n let implicitIdx = -1;\n\n for (let i = 0; i < shape.length; ++i) {\n if (shape[i] >= 0) {\n shapeProd *= shape[i];\n } else if (shape[i] === -1) {\n if (implicitIdx !== -1) {\n throw Error(\n `Shapes can only have 1 implicit size. ` +\n `Found -1 at dim ${implicitIdx} and dim ${i}`);\n }\n implicitIdx = i;\n } else if (shape[i] < 0) {\n throw Error(`Shapes can not be < 0. Found ${shape[i]} at dim ${i}`);\n }\n }\n\n if (implicitIdx === -1) {\n if (size > 0 && size !== shapeProd) {\n throw Error(`Size(${size}) must match the product of shape ${shape}`);\n }\n return shape;\n }\n\n if (shapeProd === 0) {\n throw Error(\n `Cannot infer the missing size in [${shape}] when ` +\n `there are 0 elements`);\n }\n if (size % shapeProd !== 0) {\n throw Error(\n `The implicit shape can't be a fractional number. ` +\n `Got ${size} / ${shapeProd}`);\n }\n\n const newShape = shape.slice();\n newShape[implicitIdx] = size / shapeProd;\n return newShape;\n}\n\nexport function parseAxisParam(\n axis: number|number[], shape: number[]): number[] {\n const rank = shape.length;\n\n // Normalize input\n axis = axis == null ? shape.map((s, i) => i) : [].concat(axis);\n\n // Check for valid range\n assert(\n axis.every(ax => ax >= -rank && ax < rank),\n () =>\n `All values in axis param must be in range [-${rank}, ${rank}) but ` +\n `got axis ${axis}`);\n\n // Check for only integers\n assert(\n axis.every(ax => isInt(ax)),\n () => `All values in axis param must be integers but ` +\n `got axis ${axis}`);\n\n // Handle negative axis.\n return axis.map(a => a < 0 ? rank + a : a);\n}\n\n/** Reduces the shape by removing all dimensions of shape 1. */\nexport function squeezeShape(shape: number[], axis?: number[]):\n {newShape: number[], keptDims: number[]} {\n const newShape: number[] = [];\n const keptDims: number[] = [];\n const isEmptyArray = axis != null && Array.isArray(axis) && axis.length === 0;\n const axes = (axis == null || isEmptyArray) ?\n null :\n parseAxisParam(axis, shape).sort();\n let j = 0;\n for (let i = 0; i < shape.length; ++i) {\n if (axes != null) {\n if (axes[j] === i && shape[i] !== 1) {\n throw new Error(\n `Can't squeeze axis ${i} since its dim '${shape[i]}' is not 1`);\n }\n if ((axes[j] == null || axes[j] > i) && shape[i] === 1) {\n newShape.push(shape[i]);\n keptDims.push(i);\n }\n if (axes[j] <= i) {\n j++;\n }\n }\n if (shape[i] !== 1) {\n newShape.push(shape[i]);\n keptDims.push(i);\n }\n }\n return {newShape, keptDims};\n}\n\nexport function getTypedArrayFromDType(\n dtype: D, size: number): DataTypeMap[D] {\n let values = null;\n if (dtype == null || dtype === 'float32') {\n values = new Float32Array(size);\n } else if (dtype === 'int32') {\n values = new Int32Array(size);\n } else if (dtype === 'bool') {\n values = new Uint8Array(size);\n } else {\n throw new Error(`Unknown data type ${dtype}`);\n }\n return values as DataTypeMap[D];\n}\n\nexport function getArrayFromDType(\n dtype: D, size: number): DataTypeMap[D] {\n let values = null;\n if (dtype == null || dtype === 'float32') {\n values = new Float32Array(size);\n } else if (dtype === 'int32') {\n values = new Int32Array(size);\n } else if (dtype === 'bool') {\n values = new Uint8Array(size);\n } else if (dtype === 'string') {\n values = new Array<'string'>(size);\n } else {\n throw new Error(`Unknown data type ${dtype}`);\n }\n return values as DataTypeMap[D];\n}\n\nexport function checkConversionForErrors(\n vals: DataTypeMap[D]|number[], dtype: D): void {\n for (let i = 0; i < vals.length; i++) {\n const num = vals[i] as number;\n if (isNaN(num) || !isFinite(num)) {\n throw Error(`A tensor of type ${dtype} being uploaded contains ${num}.`);\n }\n }\n}\n\n/** Returns true if the dtype is valid. */\nexport function isValidDtype(dtype: DataType): boolean {\n return dtype === 'bool' || dtype === 'complex64' || dtype === 'float32' ||\n dtype === 'int32' || dtype === 'string';\n}\n\n/**\n * Returns true if the new type can't encode the old type without loss of\n * precision.\n */\nexport function hasEncodingLoss(oldType: DataType, newType: DataType): boolean {\n if (newType === 'complex64') {\n return false;\n }\n if (newType === 'float32' && oldType !== 'complex64') {\n return false;\n }\n if (newType === 'int32' && oldType !== 'float32' && oldType !== 'complex64') {\n return false;\n }\n if (newType === 'bool' && oldType === 'bool') {\n return false;\n }\n return true;\n}\n\nexport function isTypedArray(a: {}):\n a is Float32Array|Int32Array|Uint8Array|Uint8ClampedArray {\n return a instanceof Float32Array || a instanceof Int32Array ||\n a instanceof Uint8Array || a instanceof Uint8ClampedArray;\n}\n\nexport function bytesPerElement(dtype: DataType): number {\n if (dtype === 'float32' || dtype === 'int32') {\n return 4;\n } else if (dtype === 'complex64') {\n return 8;\n } else if (dtype === 'bool') {\n return 1;\n } else {\n throw new Error(`Unknown dtype ${dtype}`);\n }\n}\n\n/**\n * Returns the approximate number of bytes allocated in the string array - 2\n * bytes per character. Computing the exact bytes for a native string in JS is\n * not possible since it depends on the encoding of the html page that serves\n * the website.\n */\nexport function bytesFromStringArray(arr: Uint8Array[]): number {\n if (arr == null) {\n return 0;\n }\n let bytes = 0;\n arr.forEach(x => bytes += x.length);\n return bytes;\n}\n\n/** Returns true if the value is a string. */\nexport function isString(value: {}): value is string {\n return typeof value === 'string' || value instanceof String;\n}\n\nexport function isBoolean(value: {}): boolean {\n return typeof value === 'boolean';\n}\n\nexport function isNumber(value: {}): boolean {\n return typeof value === 'number';\n}\n\nexport function inferDtype(values: TensorLike): DataType {\n if (Array.isArray(values)) {\n return inferDtype(values[0]);\n }\n if (values instanceof Float32Array) {\n return 'float32';\n } else if (values instanceof Int32Array\n || values instanceof Uint8Array\n || values instanceof Uint8ClampedArray) {\n return 'int32';\n } else if (isNumber(values)) {\n return 'float32';\n } else if (isString(values)) {\n return 'string';\n } else if (isBoolean(values)) {\n return 'bool';\n }\n return 'float32';\n}\n\nexport function isFunction(f: Function) {\n return !!(f && f.constructor && f.call && f.apply);\n}\n\nexport function nearestDivisor(size: number, start: number): number {\n for (let i = start; i < size; ++i) {\n if (size % i === 0) {\n return i;\n }\n }\n return size;\n}\n\nexport function computeStrides(shape: number[]): number[] {\n const rank = shape.length;\n if (rank < 2) {\n return [];\n }\n\n // Last dimension has implicit stride of 1, thus having D-1 (instead of D)\n // strides.\n const strides = new Array(rank - 1);\n strides[rank - 2] = shape[rank - 1];\n for (let i = rank - 3; i >= 0; --i) {\n strides[i] = strides[i + 1] * shape[i + 1];\n }\n return strides;\n}\n\nfunction createNestedArray(\n offset: number, shape: number[], a: TypedArray, isComplex = false) {\n const ret = new Array();\n if (shape.length === 1) {\n const d = shape[0] * (isComplex ? 2 : 1);\n for (let i = 0; i < d; i++) {\n ret[i] = a[offset + i];\n }\n } else {\n const d = shape[0];\n const rest = shape.slice(1);\n const len = rest.reduce((acc, c) => acc * c) * (isComplex ? 2 : 1);\n for (let i = 0; i < d; i++) {\n ret[i] = createNestedArray(offset + i * len, rest, a, isComplex);\n }\n }\n return ret;\n}\n\n// Provide a nested array of TypedArray in given shape.\nexport function toNestedArray(\n shape: number[], a: TypedArray, isComplex = false) {\n if (shape.length === 0) {\n // Scalar type should return a single number.\n return a[0];\n }\n const size = shape.reduce((acc, c) => acc * c) * (isComplex ? 2 : 1);\n if (size === 0) {\n // A tensor with shape zero should be turned into empty list.\n return [];\n }\n if (size !== a.length) {\n throw new Error(`[${shape}] does not match the input size ${a.length}${\n isComplex ? ' for a complex tensor' : ''}.`);\n }\n\n return createNestedArray(0, shape, a, isComplex);\n}\n\nexport function makeOnesTypedArray(\n size: number, dtype: D): DataTypeMap[D] {\n const array = makeZerosTypedArray(size, dtype);\n for (let i = 0; i < array.length; i++) {\n array[i] = 1;\n }\n return array;\n}\n\nexport function makeZerosTypedArray(\n size: number, dtype: D): DataTypeMap[D] {\n if (dtype == null || dtype === 'float32' || dtype === 'complex64') {\n return new Float32Array(size) as DataTypeMap[D];\n } else if (dtype === 'int32') {\n return new Int32Array(size) as DataTypeMap[D];\n } else if (dtype === 'bool') {\n return new Uint8Array(size) as DataTypeMap[D];\n } else {\n throw new Error(`Unknown data type ${dtype}`);\n }\n}\n\n/**\n * Make nested `TypedArray` filled with zeros.\n * @param shape The shape information for the nested array.\n * @param dtype dtype of the array element.\n */\nexport function makeZerosNestedTypedArray(\n shape: number[], dtype: D) {\n const size = shape.reduce((prev, curr) => prev * curr, 1);\n if (dtype == null || dtype === 'float32') {\n return toNestedArray(shape, new Float32Array(size));\n } else if (dtype === 'int32') {\n return toNestedArray(shape, new Int32Array(size));\n } else if (dtype === 'bool') {\n return toNestedArray(shape, new Uint8Array(size));\n } else {\n throw new Error(`Unknown data type ${dtype}`);\n }\n}\n\nexport function assertNonNegativeIntegerDimensions(shape: number[]) {\n shape.forEach(dimSize => {\n assert(\n Number.isInteger(dimSize) && dimSize >= 0,\n () =>\n `Tensor must have a shape comprised of positive integers but got ` +\n `shape [${shape}].`);\n });\n}\n\n/**\n * Computes flat index for a given location (multidimentionsal index) in a\n * Tensor/multidimensional array.\n *\n * @param locs Location in the tensor.\n * @param rank Rank of the tensor.\n * @param strides Tensor strides.\n */\nexport function locToIndex(\n locs: number[], rank: number, strides: number[]): number {\n if (rank === 0) {\n return 0;\n } else if (rank === 1) {\n return locs[0];\n }\n let index = locs[locs.length - 1];\n for (let i = 0; i < locs.length - 1; ++i) {\n index += strides[i] * locs[i];\n }\n return index;\n}\n\n/**\n * Computes the location (multidimensional index) in a tensor/multidimentional\n * array for a given flat index.\n *\n * @param index Index in flat array.\n * @param rank Rank of tensor.\n * @param strides Strides of tensor.\n */\nexport function indexToLoc(\n index: number, rank: number, strides: number[]): number[] {\n if (rank === 0) {\n return [];\n } else if (rank === 1) {\n return [index];\n }\n const locs: number[] = new Array(rank);\n for (let i = 0; i < locs.length - 1; ++i) {\n locs[i] = Math.floor(index / strides[i]);\n index -= locs[i] * strides[i];\n }\n locs[locs.length - 1] = index;\n return locs;\n}\n\n/**\n * This method asserts whether an object is a Promise instance.\n * @param object\n */\n// tslint:disable-next-line: no-any\nexport function isPromise(object: any): object is Promise {\n // We chose to not use 'obj instanceOf Promise' for two reasons:\n // 1. It only reliably works for es6 Promise, not other Promise\n // implementations.\n // 2. It doesn't work with framework that uses zone.js. zone.js monkey patch\n // the async calls, so it is possible the obj (patched) is comparing to a\n // pre-patched Promise.\n return object && object.then && typeof object.then === 'function';\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env} from './environment';\n\nexport function warn(...msg: Array<{}>): void {\n if (!(env().getBool('IS_TEST') || env().getBool('PROD'))) {\n console.warn(...msg);\n }\n}\n\nexport function log(...msg: Array<{}>): void {\n if (!(env().getBool('IS_TEST') || env().getBool('PROD'))) {\n console.log(...msg);\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Platform} from './platforms/platform';\nimport {isPromise} from './util_base';\nimport * as log from './log';\n\n// Expects flags from URL in the format ?tfjsflags=FLAG1:1,FLAG2:true.\nconst TENSORFLOWJS_FLAGS_PREFIX = 'tfjsflags';\n\ntype FlagValue = number|boolean;\ntype FlagEvaluationFn = (() => FlagValue)|(() => Promise);\nexport type Flags = {\n [featureName: string]: FlagValue\n};\nexport type FlagRegistryEntry = {\n evaluationFn: FlagEvaluationFn;\n setHook?: (value: FlagValue) => void;\n};\n\n/**\n * The environment contains evaluated flags as well as the registered platform.\n * This is always used as a global singleton and can be retrieved with\n * `tf.env()`.\n *\n * @doc {heading: 'Environment'}\n */\nexport class Environment {\n private flags: Flags = {};\n private flagRegistry: {[flagName: string]: FlagRegistryEntry} = {};\n\n private urlFlags: Flags = {};\n\n platformName: string;\n platform: Platform;\n\n // Jasmine spies on this in 'environment_test.ts'\n getQueryParams = getQueryParams;\n\n // tslint:disable-next-line: no-any\n constructor(public global: any) {\n this.populateURLFlags();\n }\n\n setPlatform(platformName: string, platform: Platform) {\n if (this.platform != null) {\n log.warn(\n `Platform ${this.platformName} has already been set. ` +\n `Overwriting the platform with ${platform}.`);\n }\n this.platformName = platformName;\n this.platform = platform;\n }\n\n registerFlag(\n flagName: string, evaluationFn: FlagEvaluationFn,\n setHook?: (value: FlagValue) => void) {\n this.flagRegistry[flagName] = {evaluationFn, setHook};\n\n // Override the flag value from the URL. This has to happen here because the\n // environment is initialized before flags get registered.\n if (this.urlFlags[flagName] != null) {\n const flagValue = this.urlFlags[flagName];\n log.warn(\n `Setting feature override from URL ${flagName}: ${flagValue}.`);\n this.set(flagName, flagValue);\n }\n }\n\n async getAsync(flagName: string): Promise {\n if (flagName in this.flags) {\n return this.flags[flagName];\n }\n\n this.flags[flagName] = await this.evaluateFlag(flagName);\n return this.flags[flagName];\n }\n\n get(flagName: string): FlagValue {\n if (flagName in this.flags) {\n return this.flags[flagName];\n }\n\n const flagValue = this.evaluateFlag(flagName);\n if (isPromise(flagValue)) {\n throw new Error(\n `Flag ${flagName} cannot be synchronously evaluated. ` +\n `Please use getAsync() instead.`);\n }\n\n this.flags[flagName] = flagValue as number | boolean;\n\n return this.flags[flagName];\n }\n\n getNumber(flagName: string): number {\n return this.get(flagName) as number;\n }\n\n getBool(flagName: string): boolean {\n return this.get(flagName) as boolean;\n }\n\n getFlags(): Flags {\n return this.flags;\n }\n // For backwards compatibility.\n get features(): Flags {\n return this.flags;\n }\n\n set(flagName: string, value: FlagValue): void {\n if (this.flagRegistry[flagName] == null) {\n throw new Error(\n `Cannot set flag ${flagName} as it has not been registered.`);\n }\n this.flags[flagName] = value;\n if (this.flagRegistry[flagName].setHook != null) {\n this.flagRegistry[flagName].setHook(value);\n }\n }\n\n private evaluateFlag(flagName: string): FlagValue|Promise {\n if (this.flagRegistry[flagName] == null) {\n throw new Error(\n `Cannot evaluate flag '${flagName}': no evaluation function found.`);\n }\n return this.flagRegistry[flagName].evaluationFn();\n }\n\n setFlags(flags: Flags) {\n this.flags = Object.assign({}, flags);\n }\n\n reset() {\n this.flags = {};\n this.urlFlags = {};\n this.populateURLFlags();\n }\n\n private populateURLFlags(): void {\n if (typeof this.global === 'undefined' ||\n typeof this.global.location === 'undefined' ||\n typeof this.global.location.search === 'undefined') {\n return;\n }\n\n const urlParams = this.getQueryParams(this.global.location.search);\n if (TENSORFLOWJS_FLAGS_PREFIX in urlParams) {\n const keyValues = urlParams[TENSORFLOWJS_FLAGS_PREFIX].split(',');\n keyValues.forEach(keyValue => {\n const [key, value] = keyValue.split(':') as [string, string];\n this.urlFlags[key] = parseValue(key, value);\n });\n }\n }\n}\n\nexport function getQueryParams(queryString: string): {[key: string]: string} {\n const params = {};\n queryString.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g, (s, ...t) => {\n decodeParam(params, t[0], t[1]);\n return t.join('=');\n });\n return params;\n}\n\nfunction decodeParam(\n params: {[key: string]: string}, name: string, value?: string) {\n params[decodeURIComponent(name)] = decodeURIComponent(value || '');\n}\n\nfunction parseValue(flagName: string, value: string): FlagValue {\n value = value.toLowerCase();\n if (value === 'true' || value === 'false') {\n return value === 'true';\n } else if (`${+ value}` === value) {\n return +value;\n }\n throw new Error(\n `Could not parse value flag value ${value} for flag ${flagName}.`);\n}\n\n/**\n * Returns the current environment (a global singleton).\n *\n * The environment object contains the evaluated feature values as well as the\n * active platform.\n *\n * @doc {heading: 'Environment'}\n */\nexport function env() {\n return ENV;\n}\n\nexport let ENV: Environment = null;\nexport function setEnvironmentGlobal(environment: Environment) {\n ENV = environment;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Note that the identifier globalNameSpace is scoped to this module, but will\n// always resolve to the same global object regardless of how the module is\n// resolved.\n// tslint:disable-next-line:no-any\nlet globalNameSpace: {_tfGlobals: Map};\n// tslint:disable-next-line:no-any\nexport function getGlobalNamespace(): {_tfGlobals: Map} {\n if (globalNameSpace == null) {\n // tslint:disable-next-line:no-any\n let ns: any;\n if (typeof (window) !== 'undefined') {\n ns = window;\n } else if (typeof (global) !== 'undefined') {\n ns = global;\n } else if (typeof (process) !== 'undefined') {\n ns = process;\n } else if (typeof (self) !== 'undefined') {\n ns = self;\n } else {\n throw new Error('Could not find a global object');\n }\n globalNameSpace = ns;\n }\n return globalNameSpace;\n}\n\n// tslint:disable-next-line:no-any\nfunction getGlobalMap(): Map {\n const ns = getGlobalNamespace();\n if (ns._tfGlobals == null) {\n ns._tfGlobals = new Map();\n }\n return ns._tfGlobals;\n}\n\n/**\n * Returns a globally accessible 'singleton' object.\n *\n * @param key the name of the object\n * @param init a function to initialize to initialize this object\n * the first time it is fetched.\n */\nexport function getGlobal(key: string, init: () => T): T {\n const globalMap = getGlobalMap();\n if (globalMap.has(key)) {\n return globalMap.get(key);\n } else {\n const singleton = init();\n globalMap.set(key, singleton);\n return globalMap.get(key);\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n// Allow UpperCamelCase variable names\n// tslint:disable: variable-name\n// Unfortunately just enabling PascalCase per file (tslint:enable:\n// allow-pascal-case) doesn't work.\nimport {NamedTensorInfoMap, TensorInfo} from './kernel_registry';\nimport {ExplicitPadding} from './ops/conv_util';\nimport {Activation} from './ops/fused_types';\nimport {DataType, PixelData} from './types';\n\nexport const Abs = 'Abs';\nexport type AbsInputs = UnaryInputs;\n\nexport const Acos = 'Acos';\nexport type AcosInputs = UnaryInputs;\n\nexport const Acosh = 'Acosh';\nexport type AcoshInputs = UnaryInputs;\n\nexport const Add = 'Add';\nexport type AddInputs = BinaryInputs;\n\nexport const AddN = 'AddN';\nexport type AddNInputs = TensorInfo[];\n\nexport const All = 'All';\nexport type AllInputs = Pick;\nexport interface AllAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const Any = 'Any';\nexport type AnyInputs = Pick;\nexport interface AnyAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const ArgMax = 'ArgMax';\nexport type ArgMaxInputs = Pick;\nexport interface ArgMaxAttrs {\n axis: number;\n}\n\nexport const ArgMin = 'ArgMin';\nexport type ArgMinInputs = Pick;\nexport interface ArgMinAttrs {\n axis: number;\n}\n\nexport const Asin = 'Asin';\nexport type AsinInputs = UnaryInputs;\n\nexport const Asinh = 'Asinh';\nexport type AsinhInputs = UnaryInputs;\n\nexport const Atan = 'Atan';\nexport type AtanInputs = UnaryInputs;\n\nexport const Atanh = 'Atanh';\nexport type AtanhInputs = UnaryInputs;\n\nexport const Atan2 = 'Atan2';\nexport type Atan2Inputs = BinaryInputs;\n\nexport const AvgPool = 'AvgPool';\nexport type AvgPoolInputs = Pick;\nexport interface AvgPoolAttrs {\n filterSize: [number, number]|number;\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const AvgPoolGrad = 'AvgPoolGrad';\nexport type AvgPoolGradInputs = Pick;\nexport interface AvgPoolGradAttrs {\n filterSize: [number, number]|number;\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n}\n\nexport const AvgPool3D = 'AvgPool3D';\nexport type AvgPool3DInputs = Pick;\nexport interface AvgPool3DAttrs {\n filterSize: [number, number, number]|number;\n strides: [number, number, number]|number;\n pad: 'valid'|'same'|number;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n dataFormat: 'NDHWC'|'NCDHW';\n}\n\nexport const AvgPool3DGrad = 'AvgPool3DGrad';\nexport type AvgPool3DGradInputs = Pick;\nexport interface AvgPool3DGradAttrs {\n filterSize: [number, number, number]|number;\n strides: [number, number, number]|number;\n pad: 'valid'|'same'|number;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const BatchMatMul = 'BatchMatMul';\nexport type BatchMatMulInputs = Pick;\nexport interface BatchMatMulAttrs {\n transposeA: boolean;\n transposeB: boolean;\n}\n\nexport const BatchToSpaceND = 'BatchToSpaceND';\nexport type BatchToSpaceNDInputs = Pick;\nexport interface BatchToSpaceNDAttrs {\n blockShape: number[];\n crops: number[][];\n}\n\nexport type BinaryInputs = Pick;\n\nexport const Bincount = 'Bincount';\nexport type BincountInputs = Pick;\nexport interface BincountAttrs {\n size: number;\n}\n\nexport const BroadcastTo = 'BroadcastTo';\nexport type BroadcastToInputs = Pick;\nexport interface BroadCastToAttrs {\n shape: number[];\n inputShape: number[]; // for gradient\n}\n\nexport const BroadcastArgs = 'BroadcastArgs';\nexport type BroadcastArgsInputs = Pick;\n\nexport const Cast = 'Cast';\nexport type CastInputs = UnaryInputs;\nexport interface CastAttrs {\n dtype: DataType;\n}\n\nexport const Ceil = 'Ceil';\nexport type CeilInputs = UnaryInputs;\n\nexport const ClipByValue = 'ClipByValue';\nexport type ClipByValueInputs = UnaryInputs;\nexport interface ClipByValueAttrs {\n clipValueMin: number;\n clipValueMax: number;\n}\n\nexport const Complex = 'Complex';\nexport type ComplexInputs = Pick;\n\nexport const ComplexAbs = 'ComplexAbs';\nexport type ComplexAbsInputs = UnaryInputs;\n\nexport const Concat = 'Concat';\nexport type ConcatInputs = TensorInfo[];\nexport interface ConcatAttrs {\n axis: number;\n}\n\nexport const Conv2D = 'Conv2D';\nexport type Conv2DInputs = Pick;\nexport interface Conv2DAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dataFormat: 'NHWC'|'NCHW';\n dilations: [number, number]|number;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const Conv2DBackpropFilter = 'Conv2DBackpropFilter';\nexport type Conv2DBackpropFilterInputs = Pick;\nexport interface Conv2DBackpropFilterAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dataFormat: 'NHWC'|'NCHW';\n dimRoundingMode?: 'floor'|'round'|'ceil';\n filterShape: [number, number, number, number];\n}\n\nexport const Conv2DBackpropInput = 'Conv2DBackpropInput';\nexport type Conv2DBackpropInputInputs = Pick;\nexport interface Conv2DBackpropInputAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dataFormat: 'NHWC'|'NCHW';\n dimRoundingMode?: 'floor'|'round'|'ceil';\n inputShape: [number, number, number, number];\n}\n\nexport const Conv3D = 'Conv3D';\nexport type Conv3DInputs = Pick;\nexport interface Conv3DAttrs {\n strides: [number, number, number]|number;\n pad: 'valid'|'same';\n dataFormat: 'NDHWC'|'NCDHW';\n dilations: [number, number, number]|number;\n}\n\nexport const Conv3DBackpropFilterV2 = 'Conv3DBackpropFilterV2';\nexport type Conv3DBackpropFilterV2Inputs = Pick;\n\nexport interface Conv3DBackpropFilterV2Attrs {\n strides: [number, number, number]|number;\n pad: 'valid'|'same';\n filterShape: [number, number, number, number, number];\n}\n\nexport const Conv3DBackpropInputV2 = 'Conv3DBackpropInputV2';\nexport type Conv3DBackpropInputV2Inputs =\n Pick;\nexport interface Conv3DBackpropInputV2Attrs {\n strides: [number, number, number]|number;\n pad: 'valid'|'same';\n inputShape: [number, number, number, number, number];\n}\n\nexport const Cos = 'Cos';\nexport type CosInputs = UnaryInputs;\n\nexport const Cosh = 'Cosh';\nexport type CoshInputs = UnaryInputs;\n\nexport const Cumsum = 'Cumsum';\nexport type CumsumInputs = Pick;\nexport interface CumsumAttrs {\n axis: number;\n exclusive: boolean;\n reverse: boolean;\n}\n\nexport const CropAndResize = 'CropAndResize';\nexport type CropAndResizeInputs =\n Pick;\nexport interface CropAndResizeAttrs {\n cropSize: [number, number];\n method: 'bilinear'|'nearest';\n extrapolationValue: number;\n}\n\nexport const DenseBincount = 'DenseBincount';\nexport type DenseBincountInputs = Pick;\nexport interface DenseBincountAttrs {\n size: number;\n binaryOutput?: boolean;\n}\n\nexport const DepthToSpace = 'DepthToSpace';\nexport type DepthToSpaceInputs = Pick;\nexport interface DepthToSpaceAttrs {\n blockSize: number;\n dataFormat: 'NHWC'|'NCHW';\n}\n\nexport const DepthwiseConv2dNative = 'DepthwiseConv2dNative';\nexport type DepthwiseConv2dNativeInputs =\n Pick;\nexport interface DepthwiseConv2dNativeAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dataFormat: 'NHWC'|'NCHW';\n dilations: [number, number]|number;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const DepthwiseConv2dNativeBackpropFilter =\n 'DepthwiseConv2dNativeBackpropFilter';\nexport type DepthwiseConv2dNativeBackpropFilterInputs =\n Pick;\nexport interface DepthwiseConv2dNativeBackpropFilterAttrs {\n strides: [number, number]|number;\n dilations: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n filterShape: [number, number, number, number];\n}\n\nexport const DepthwiseConv2dNativeBackpropInput =\n 'DepthwiseConv2dNativeBackpropInput';\nexport type DepthwiseConv2dNativeBackpropInputInputs =\n Pick;\nexport interface DepthwiseConv2dNativeBackpropInputAttrs {\n strides: [number, number]|number;\n dilations: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n inputShape: [number, number, number, number];\n}\n\nexport const Diag = 'Diag';\nexport type DiagInputs = Pick;\n\nexport const Dilation2D = 'Dilation2D';\nexport type Dilation2DInputs = Pick;\nexport interface Dilation2DAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number;\n dilations: [number, number]|number;\n}\n\nexport const Dilation2DBackpropInput = 'Dilation2DBackpropInput';\nexport type Dilation2DBackpropInputInputs =\n Pick;\n\nexport const Dilation2DBackpropFilter = 'Dilation2DBackpropFilter';\nexport type Dilation2DBackpropFilterInputs =\n Pick;\n\nexport const RealDiv = 'RealDiv';\nexport type RealDivInputs = BinaryInputs;\n\nexport const Einsum = 'Einsum';\nexport type EinsumInputs = TensorInfo[];\nexport interface EinsumAttrs {\n equation: string;\n}\n\nexport const Elu = 'Elu';\nexport type EluInputs = Pick;\n\nexport const EluGrad = 'EluGrad';\nexport type EluGradInputs = Pick;\n\nexport const Erf = 'Erf';\nexport type ErfInputs = UnaryInputs;\n\nexport const Equal = 'Equal';\nexport type EqualInputs = BinaryInputs;\n\nexport const Exp = 'Exp';\nexport type ExpInputs = UnaryInputs;\n\nexport const ExpandDims = 'ExpandDims';\nexport type ExpandDimsInputs = Pick;\nexport interface ExpandDimsAttrs {\n dim: number;\n}\n\nexport const Expm1 = 'Expm1';\nexport type Expm1Inputs = UnaryInputs;\n\nexport const FFT = 'FFT';\nexport type FFTInputs = Pick;\n\nexport const Fill = 'Fill';\nexport interface FillAttrs {\n shape: number[];\n value: number|string;\n dtype: DataType;\n}\n\nexport const FlipLeftRight = 'FlipLeftRight';\nexport type FlipLeftRightInputs = Pick;\n\nexport const Floor = 'Floor';\nexport type FloorInputs = UnaryInputs;\n\nexport const FloorDiv = 'FloorDiv';\nexport type FloorDivInputs = BinaryInputs;\n\nexport const FusedBatchNorm = 'FusedBatchNorm';\nexport type FusedBatchNormInputs =\n Pick;\nexport interface FusedBatchNormAttrs {\n varianceEpsilon: number;\n}\n\nexport const GatherV2 = 'GatherV2';\nexport type GatherV2Inputs = Pick;\nexport interface GatherV2Attrs {\n axis: number;\n batchDims: number;\n}\n\nexport const GatherNd = 'GatherNd';\nexport type GatherNdInputs = Pick;\n\nexport const Greater = 'Greater';\nexport type GreaterInputs = BinaryInputs;\n\nexport const GreaterEqual = 'GreaterEqual';\nexport type GreaterEqualInputs = BinaryInputs;\n\nexport const Identity = 'Identity';\nexport type IdentityInputs = Pick;\n\nexport const IFFT = 'IFFT';\nexport type IFFTInputs = Pick;\n\nexport const Imag = 'Imag';\nexport type ImagInputs = Pick;\n\nexport const IsFinite = 'IsFinite';\nexport type IsFiniteInputs = UnaryInputs;\n\nexport const IsInf = 'IsInf';\nexport type IsInfInputs = UnaryInputs;\n\nexport const IsNan = 'IsNan';\nexport type IsNanInputs = UnaryInputs;\n\nexport const LeakyRelu = 'LeakyRelu';\nexport type LeakyReluInputs = Pick;\nexport interface LeakyReluAttrs {\n alpha: number;\n}\n\nexport const Less = 'Less';\nexport type LessInputs = BinaryInputs;\n\nexport const LessEqual = 'LessEqual';\nexport type LessEqualInputs = BinaryInputs;\n\nexport const LinSpace = 'LinSpace';\nexport interface LinSpaceAttrs {\n start: number;\n stop: number;\n num: number;\n}\nexport const Log = 'Log';\nexport type LogInputs = UnaryInputs;\n\nexport const Log1p = 'Log1p';\nexport type Log1pInputs = UnaryInputs;\n\nexport const LogicalAnd = 'LogicalAnd';\nexport type LogicalAndInputs = BinaryInputs;\n\nexport const LogicalNot = 'LogicalNot';\nexport type LogicalNotInputs = Pick;\n\nexport const LogicalOr = 'LogicalOr';\nexport type LogicalOrInputs = BinaryInputs;\n\nexport const LogSoftmax = 'LogSoftmax';\nexport type LogSoftmaxInputs = Pick;\nexport interface LogSoftmaxAttrs {\n axis: number;\n}\n\nexport const LRN = 'LRN';\nexport type LRNInputs = Pick;\nexport interface LRNAttrs {\n depthRadius: number;\n bias: number;\n alpha: number;\n beta: number;\n}\n\nexport const LRNGrad = 'LRNGrad';\nexport type LRNGradInputs = Pick;\nexport interface LRNGradAttrs {\n depthRadius: number;\n bias: number;\n alpha: number;\n beta: number;\n}\n\nexport const Max = 'Max';\nexport type MaxInputs = Pick;\nexport interface MaxAttrs {\n reductionIndices: number|number[];\n keepDims: boolean;\n}\n\nexport const Maximum = 'Maximum';\nexport type MaximumInputs = BinaryInputs;\n\nexport const MaxPool = 'MaxPool';\nexport type MaxPoolInputs = Pick;\nexport interface MaxPoolAttrs {\n filterSize: [number, number]|number;\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const MaxPoolGrad = 'MaxPoolGrad';\nexport type MaxPoolGradInputs = Pick;\nexport interface MaxPoolGradAttrs {\n filterSize: [number, number]|number;\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const MaxPool3D = 'MaxPool3D';\nexport type MaxPool3DInputs = Pick;\nexport interface MaxPool3DAttrs {\n filterSize: [number, number, number]|number;\n strides: [number, number, number]|number;\n pad: 'valid'|'same'|number;\n dataFormat: 'NDHWC'|'NCDHW';\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const MaxPool3DGrad = 'MaxPool3DGrad';\nexport type MaxPool3DGradInputs =\n Pick;\nexport interface MaxPool3DGradAttrs {\n filterSize: [number, number, number]|number;\n strides: [number, number, number]|number;\n pad: 'valid'|'same'|number;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const MaxPoolWithArgmax = 'MaxPoolWithArgmax';\nexport type MaxPoolWithArgmaxInputs = Pick;\nexport interface MaxPoolWithArgmaxAttrs {\n filterSize: [number, number]|number;\n strides: [number, number]|number;\n pad: 'valid'|'same'|number;\n includeBatchInIndex: boolean;\n}\n\nexport const Mean = 'Mean';\nexport type MeanInputs = Pick;\nexport interface MeanAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const Min = 'Min';\nexport type MinInputs = Pick;\nexport interface MinAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const Minimum = 'Minimum';\nexport type MinimumInputs = BinaryInputs;\n\nexport const MirrorPad = 'MirrorPad';\nexport type MirrorPadInputs = Pick;\nexport interface MirrorPadAttrs {\n paddings: Array<[number, number]>;\n mode: 'reflect'|'symmetric';\n}\n\nexport const Mod = 'Mod';\nexport type ModInputs = BinaryInputs;\n\nexport const Multinomial = 'Multinomial';\nexport type MultinomialInputs = Pick;\nexport interface MultinomialAttrs {\n numSamples: number;\n seed: number;\n normalized: boolean;\n}\n\nexport const Multiply = 'Multiply';\nexport type MultiplyInputs = BinaryInputs;\n\nexport const Neg = 'Neg';\nexport type NegInputs = UnaryInputs;\n\nexport const NotEqual = 'NotEqual';\nexport type NotEqualInputs = BinaryInputs;\n\nexport const NonMaxSuppressionV3 = 'NonMaxSuppressionV3';\nexport type NonMaxSuppressionV3Inputs =\n Pick;\nexport interface NonMaxSuppressionV3Attrs {\n maxOutputSize: number;\n iouThreshold: number;\n scoreThreshold: number;\n}\n\nexport const NonMaxSuppressionV4 = 'NonMaxSuppressionV4';\nexport type NonMaxSuppressionV4Inputs =\n Pick;\nexport interface NonMaxSuppressionV4Attrs {\n maxOutputSize: number;\n iouThreshold: number;\n scoreThreshold: number;\n padToMaxOutputSize: boolean;\n}\n\nexport const NonMaxSuppressionV5 = 'NonMaxSuppressionV5';\nexport type NonMaxSuppressionV5Inputs =\n Pick;\nexport interface NonMaxSuppressionV5Attrs {\n maxOutputSize: number;\n iouThreshold: number;\n scoreThreshold: number;\n softNmsSigma: number;\n}\n\nexport const OnesLike = 'OnesLike';\nexport type OnesLikeInputs = UnaryInputs;\n\nexport const OneHot = 'OneHot';\nexport type OneHotInputs = Pick;\nexport interface OneHotAttrs {\n depth: number;\n onValue: number;\n offValue: number;\n}\n\nexport const Pack = 'Pack';\nexport type PackInputs = TensorInfo[];\nexport interface PackAttrs {\n axis: number;\n}\n\nexport const PadV2 = 'PadV2';\nexport type PadV2Inputs = Pick;\nexport interface PadV2Attrs {\n paddings: Array<[number, number]>;\n constantValue: number;\n}\n\nexport const Pool = 'Pool';\nexport type PoolInputs = Pick;\n\nexport const Pow = 'Pow';\nexport type PowInputs = BinaryInputs;\n\nexport const Prelu = 'Prelu';\nexport type PreluInputs = Pick;\n\nexport const Prod = 'Prod';\nexport type ProdInputs = Pick;\nexport interface ProdAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const Range = 'Range';\nexport interface RangeAttrs {\n start: number;\n stop: number;\n step: number;\n dtype: 'float32'|'int32';\n}\n\nexport const Real = 'Real';\nexport type RealInputs = Pick;\n\nexport const Reciprocal = 'Reciprocal';\nexport type ReciprocalInputs = UnaryInputs;\n\nexport const Relu = 'Relu';\nexport type ReluInputs = Pick;\n\nexport const Reshape = 'Reshape';\nexport type ReshapeInputs = Pick;\nexport interface ReshapeAttrs {\n shape: number[];\n}\n\nexport const ResizeNearestNeighbor = 'ResizeNearestNeighbor';\nexport type ResizeNearestNeighborInputs = Pick;\nexport interface ResizeNearestNeighborAttrs {\n alignCorners: boolean;\n halfPixelCenters: boolean;\n size: [number, number];\n}\n\nexport const ResizeNearestNeighborGrad = 'ResizeNearestNeighborGrad';\nexport type ResizeNearestNeighborGradInputs =\n Pick;\nexport type ResizeNearestNeighborGradAttrs = ResizeNearestNeighborAttrs;\n\nexport const ResizeBilinear = 'ResizeBilinear';\nexport type ResizeBilinearInputs = Pick;\nexport interface ResizeBilinearAttrs {\n alignCorners: boolean;\n halfPixelCenters: boolean;\n size: [number, number];\n}\n\nexport const ResizeBilinearGrad = 'ResizeBilinearGrad';\nexport type ResizeBilinearGradInputs = Pick;\nexport type ResizeBilinearGradAttrs = ResizeBilinearAttrs;\n\nexport const Relu6 = 'Relu6';\nexport type Relu6Inputs = Pick;\n\nexport const Reverse = 'Reverse';\nexport type ReverseInputs = Pick;\nexport interface ReverseAttrs {\n dims: number|number[];\n}\n\nexport const Round = 'Round';\nexport type RoundInputs = UnaryInputs;\n\nexport const Rsqrt = 'Rsqrt';\nexport type RsqrtInputs = UnaryInputs;\n\nexport const ScatterNd = 'ScatterNd';\nexport type ScatterNdInputs = Pick;\nexport interface ScatterNdAttrs {\n shape: number[];\n}\n\nexport const Select = 'Select';\nexport type SelectInputs = Pick;\n\nexport const Selu = 'Selu';\nexport type SeluInputs = Pick;\n\nexport const Slice = 'Slice';\nexport type SliceInputs = Pick;\nexport interface SliceAttrs {\n begin: number|number[];\n size: number|number[];\n}\nexport const Sin = 'Sin';\nexport type SinInputs = UnaryInputs;\n\nexport const Sinh = 'Sinh';\nexport type SinhInputs = UnaryInputs;\n\nexport const Sign = 'Sign';\nexport type SignInputs = UnaryInputs;\n\nexport const Sigmoid = 'Sigmoid';\nexport type SigmoidInputs = UnaryInputs;\n\nexport const Softplus = 'Softplus';\nexport type SoftplusInputs = UnaryInputs;\n\nexport const Sqrt = 'Sqrt';\nexport type SqrtInputs = UnaryInputs;\n\nexport const Sum = 'Sum';\nexport type SumInputs = Pick;\nexport interface SumAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const SpaceToBatchND = 'SpaceToBatchND';\nexport type SpaceToBatchNDInputs = Pick;\nexport interface SpaceToBatchNDAttrs {\n blockShape: number[];\n paddings: number[][];\n}\n\nexport const SplitV = 'SplitV';\nexport type SplitVInputs = Pick;\nexport interface SplitVAttrs {\n numOrSizeSplits: number[]|number;\n axis: number;\n}\n\nexport const Softmax = 'Softmax';\nexport type SoftmaxInputs = Pick;\nexport interface SoftmaxAttrs {\n dim: number;\n}\n\nexport const SparseFillEmptyRows = 'SparseFillEmptyRows';\nexport type SparseFillEmptyRowsInputs =\n Pick;\n\nexport const SparseReshape = 'SparseReshape';\nexport type SparseReshapeInputs =\n Pick;\n\nexport const SparseSegmentMean = 'SparseSegmentMean';\nexport type SparseSegmentMeanInputs =\n Pick;\n\nexport const SparseSegmentSum = 'SparseSegmentSum';\nexport type SparseSegmentSumInputs =\n Pick;\n\nexport const SparseToDense = 'SparseToDense';\nexport type SparseToDenseInputs =\n Pick;\nexport interface SparseToDenseAttrs {\n outputShape: number[];\n}\n\nexport const SquaredDifference = 'SquaredDifference';\nexport type SquaredDifferenceInputs = BinaryInputs;\n\nexport const Square = 'Square';\nexport type SquareInputs = Pick;\n\nexport const StridedSlice = 'StridedSlice';\nexport type StridedSliceInputs = Pick;\nexport interface StridedSliceAttrs {\n begin: number[];\n end: number[];\n strides: number[];\n beginMask: number;\n endMask: number;\n ellipsisMask: number;\n newAxisMask: number;\n shrinkAxisMask: number;\n}\n\nexport const StringNGrams = 'StringNGrams';\nexport type StringNGramsInputs = Pick;\nexport interface StringNGramsAttrs {\n separator: string;\n nGramWidths: number[];\n leftPad: string;\n rightPad: string;\n padWidth: number;\n preserveShortSequences: boolean;\n}\n\nexport const StringSplit = 'StringSplit';\nexport type StringSplitInputs = Pick;\nexport interface StringSplitAttrs {\n skipEmpty: boolean;\n}\n\nexport const StringToHashBucketFast = 'StringToHashBucketFast';\nexport type StringToHashBucketFastInputs = Pick;\nexport interface StringToHashBucketFastAttrs {\n numBuckets: number;\n}\n\nexport const Sub = 'Sub';\nexport type SubInputs = BinaryInputs;\n\nexport const Tan = 'Tan';\nexport type TanInputs = UnaryInputs;\n\nexport const Tanh = 'Tanh';\nexport type TanhInputs = UnaryInputs;\n\nexport const Tile = 'Tile';\nexport type TileInputs = Pick;\nexport interface TileAttrs {\n reps: number[];\n}\n\nexport const TopK = 'TopK';\nexport type TopKInputs = Pick;\nexport interface TopKAttrs {\n k: number;\n sorted: boolean;\n}\n\nexport const Transform = 'Transform';\nexport type TransformInputs = Pick;\nexport interface TransformAttrs {\n interpolation: 'nearest'|'bilinear';\n fillMode: 'constant'|'reflect'|'wrap'|'nearest';\n fillValue: number;\n outputShape?: [number, number];\n}\n\nexport const Transpose = 'Transpose';\nexport type TransposeInputs = Pick;\nexport interface TransposeAttrs {\n perm: number[];\n}\n\nexport const Unique = 'Unique';\nexport type UniqueInputs = Pick;\nexport interface UniqueAttrs {\n axis: number;\n}\n\nexport type UnaryInputs = Pick;\n\nexport const Unpack = 'Unpack';\nexport type UnpackInputs = Pick;\nexport interface UnpackAttrs {\n axis: number;\n}\n\nexport const UnsortedSegmentSum = 'UnsortedSegmentSum';\nexport type UnsortedSegmentSumInputs =\n Pick;\nexport interface UnsortedSegmentSumAttrs {\n numSegments: number;\n}\n\nexport const ZerosLike = 'ZerosLike';\nexport type ZerosLikeInputs = UnaryInputs;\n\n/**\n * TensorFlow.js-only kernels\n */\nexport const Step = 'Step';\nexport type StepInputs = UnaryInputs;\nexport interface StepAttrs {\n alpha: number;\n}\n\nexport const FromPixels = 'FromPixels';\nexport interface FromPixelsInputs {\n pixels: PixelData|ImageData|HTMLImageElement|HTMLCanvasElement|\n HTMLVideoElement|ImageBitmap;\n}\nexport interface FromPixelsAttrs {\n numChannels: number;\n}\n\nexport const RotateWithOffset = 'RotateWithOffset';\nexport type RotateWithOffsetInputs = Pick;\nexport interface RotateWithOffsetAttrs {\n radians: number;\n fillValue: number|[number, number, number];\n center: number|[number, number];\n}\n\nexport const _FusedMatMul = '_FusedMatMul';\n// tslint:disable-next-line: class-name\nexport interface _FusedMatMulInputs extends NamedTensorInfoMap {\n a: TensorInfo;\n b: TensorInfo;\n bias?: TensorInfo;\n preluActivationWeights?: TensorInfo;\n}\n// tslint:disable-next-line: class-name\nexport interface _FusedMatMulAttrs {\n transposeA: boolean;\n transposeB: boolean;\n activation: Activation;\n leakyreluAlpha?: number;\n}\n\nexport const FusedConv2D = 'FusedConv2D';\nexport interface FusedConv2DInputs extends NamedTensorInfoMap {\n x: TensorInfo;\n filter: TensorInfo;\n bias?: TensorInfo;\n preluActivationWeights?: TensorInfo;\n}\nexport interface FusedConv2DAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dataFormat: 'NHWC'|'NCHW';\n dilations: [number, number]|number;\n dimRoundingMode: 'floor'|'round'|'ceil';\n activation: Activation;\n leakyreluAlpha?: number;\n}\n\nexport const FusedDepthwiseConv2D = 'FusedDepthwiseConv2D';\nexport interface FusedDepthwiseConv2DInputs extends NamedTensorInfoMap {\n x: TensorInfo;\n filter: TensorInfo;\n bias?: TensorInfo;\n preluActivationWeights?: TensorInfo;\n}\nexport interface FusedDepthwiseConv2DAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dataFormat: 'NHWC'|'NCHW';\n dilations: [number, number]|number;\n dimRoundingMode: 'floor'|'round'|'ceil';\n activation: Activation;\n leakyreluAlpha?: number;\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {env} from './environment';\nimport {getGlobal} from './global_util';\nimport * as log from './log';\nimport {NamedGradientMap} from './tape';\nimport {Tensor} from './tensor';\nimport {DataType, RecursiveArray} from './types';\n\nconst kernelRegistry =\n getGlobal('kernelRegistry', () => new Map());\nconst gradRegistry =\n getGlobal('gradRegistry', () => new Map());\n\nexport type DataId = object;\n\ntype AttributeValue =\n number|number[]|boolean|boolean[]|string|string[]|NamedAttrMap;\n\n/** These are extra non-tensor/primitive params passed to kernel functions. */\nexport type Attribute = AttributeValue|RecursiveArray;\n\n/** Specifies the code to run when executing a kernel. */\nexport type KernelFunc = (params: {\n inputs: NamedTensorInfoMap,\n backend: {},\n attrs?: NamedAttrMap,\n}) => TensorInfo|TensorInfo[];\n\n/** The function to run when computing a gradient during backprop. */\nexport type GradFunc =\n (dy: Tensor|Tensor[], saved: Tensor[], attrs: NamedAttrMap) =>\n NamedGradientMap;\n\n/** Function that gets called after the backend initializes. */\nexport type KernelSetupFunc = (backend: {}) => void;\n/** Function that gets called right before the backend is disposed. */\nexport type KernelDisposeFunc = KernelSetupFunc;\n\n/** Config object for registering a kernel in the global registry. */\nexport interface KernelConfig {\n kernelName: string;\n backendName: string;\n kernelFunc: KernelFunc;\n setupFunc?: KernelSetupFunc;\n disposeFunc?: KernelDisposeFunc;\n}\n\n/** Config object for registering a gradient in the global registry. */\nexport interface GradConfig {\n kernelName: string;\n inputsToSave?: string[];\n // When saveAllInputs is true, all inputs will be saved. Only use this flag\n // if inputs is an array of Tensors.\n saveAllInputs?: boolean;\n outputsToSave?: boolean[];\n gradFunc: GradFunc;\n}\n\n/** Holds metadata for a given tensor. */\nexport interface TensorInfo {\n dataId: DataId;\n shape: number[];\n dtype: DataType;\n}\n\nexport interface NamedTensorInfoMap {\n [name: string]: TensorInfo|undefined;\n}\n\nexport interface NamedAttrMap {\n [name: string]: Attribute;\n}\n\n/**\n * Returns the kernel function (code) associated with the provided names.\n *\n * @param kernelName The official name of the kernel.\n * @param backendName The official name of the backend.\n */\nexport function getKernel(\n kernelName: string, backendName: string): KernelConfig {\n const key = makeKey(kernelName, backendName);\n return kernelRegistry.get(key);\n}\n\n/**\n * Returns the registered gradient info associated with the provided kernel.\n * @param kernelName The official TF kernel name.\n */\nexport function getGradient(kernelName: string): GradConfig {\n return gradRegistry.get(kernelName);\n}\n\nexport function getKernelsForBackend(backendName: string): KernelConfig[] {\n const it = kernelRegistry.entries();\n const result: KernelConfig[] = [];\n\n while (true) {\n const {done, value} = it.next();\n if (done) {\n break;\n }\n const [key, config] = value;\n const [backend, ] = key.split('_');\n if (backend === backendName) {\n result.push(config);\n }\n }\n return result;\n}\n\n/**\n * Registers the function (forward pass) for the kernel in a global registry.\n *\n * @param config A config object with the following properties:\n * - `kernelName` The official name of the kernel.\n * - `backendName` The official name of the backend.\n * - `kernelFunc` The function to run during the forward pass of the kernel.\n * - `setupFunc` Optional. Gets called once, after the backend initializes.\n * - `disposeFunc` Optional. Gets called once, right before the backend is\n * disposed.\n */\nexport function registerKernel(config: KernelConfig) {\n const {kernelName, backendName} = config;\n const key = makeKey(kernelName, backendName);\n if (kernelRegistry.has(key)) {\n log.warn(\n `The kernel '${kernelName}' for backend ` +\n `'${backendName}' is already registered`);\n }\n kernelRegistry.set(key, config);\n}\n\n/**\n * Registers a gradient function for a given kernel in the global registry,\n * to be used during the back-propagation of that kernel.\n *\n * @param config An object with the following properties:\n * - `kernelName` The name of the kernel that the gradient function is for.\n * - `gradFunc` The function to run during back-propagation.\n */\nexport function registerGradient(config: GradConfig) {\n const {kernelName} = config;\n\n if (gradRegistry.has(kernelName)) {\n // TODO (yassogba) after 3.0 assess whether we need to keep this gated\n // to debug mode.\n if (env().getBool('DEBUG')) {\n log.warn(`Overriding the gradient for '${kernelName}'`);\n }\n }\n gradRegistry.set(kernelName, config);\n}\n\n/**\n * Removes the kernel function from the registry.\n *\n * @param kernelName The official name of the kernel.\n * @param backendName The official name of the backend.\n *\n */\nexport function unregisterKernel(\n kernelName: string, backendName: string): void {\n const key = makeKey(kernelName, backendName);\n if (!kernelRegistry.has(key)) {\n throw new Error(\n `The kernel '${kernelName}' for backend ` +\n `'${backendName}' is not registered`);\n }\n kernelRegistry.delete(key);\n}\n\n/** Removes the registered gradient from the global registry. */\nexport function unregisterGradient(kernelName: string): void {\n if (!gradRegistry.has(kernelName)) {\n throw new Error(\n `The gradient '${kernelName}' for backend is not registered`);\n }\n gradRegistry.delete(kernelName);\n}\n\n/**\n * Finds kernels that have already been registered to a backend and re-registers\n * them for a new backend. Useful for registering custom backends.\n * @param registeredBackendName Already registered backend.\n * @param newBackendName New backend.\n */\nexport function copyRegisteredKernels(\n registeredBackendName: string, newBackendName: string): void {\n const kernels = getKernelsForBackend(registeredBackendName);\n kernels.forEach(kernelConfig => {\n const newKernelConfig =\n Object.assign({}, kernelConfig, {backendName: newBackendName});\n registerKernel(newKernelConfig);\n });\n}\n\nfunction makeKey(kernelName: string, backendName: string) {\n return `${backendName}_${kernelName}`;\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env} from './environment';\nimport {BackendValues, DataType, TensorLike, TypedArray} from './types';\nimport * as base from './util_base';\nexport * from './util_base';\nexport * from './hash_util';\n\n/**\n * Create typed array for scalar value. Used for storing in `DataStorage`.\n */\nexport function createScalarValue(\n value: DataType, dtype: DataType): BackendValues {\n if (dtype === 'string') {\n return encodeString(value);\n }\n\n return toTypedArray([value], dtype);\n}\n\nfunction noConversionNeeded(a: TensorLike, dtype: DataType): boolean {\n return (a instanceof Float32Array && dtype === 'float32') ||\n (a instanceof Int32Array && dtype === 'int32') ||\n (a instanceof Uint8Array && dtype === 'bool');\n}\n\nexport function toTypedArray(a: TensorLike, dtype: DataType): TypedArray {\n if (dtype === 'string') {\n throw new Error('Cannot convert a string[] to a TypedArray');\n }\n if (Array.isArray(a)) {\n a = base.flatten(a);\n }\n\n if (env().getBool('DEBUG')) {\n base.checkConversionForErrors(a as number[], dtype);\n }\n if (noConversionNeeded(a, dtype)) {\n return a as TypedArray;\n }\n if (dtype == null || dtype === 'float32' || dtype === 'complex64') {\n return new Float32Array(a as number[]);\n } else if (dtype === 'int32') {\n return new Int32Array(a as number[]);\n } else if (dtype === 'bool') {\n const bool = new Uint8Array((a as number[]).length);\n for (let i = 0; i < bool.length; ++i) {\n if (Math.round((a as number[])[i]) !== 0) {\n bool[i] = 1;\n }\n }\n return bool;\n } else {\n throw new Error(`Unknown data type ${dtype}`);\n }\n}\n\n/**\n * Returns the current high-resolution time in milliseconds relative to an\n * arbitrary time in the past. It works across different platforms (node.js,\n * browsers).\n *\n * ```js\n * console.log(tf.util.now());\n * ```\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function now(): number {\n return env().platform.now();\n}\n\n/**\n * Returns a platform-specific implementation of\n * [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).\n *\n * If `fetch` is defined on the global object (`window`, `process`, etc.),\n * `tf.util.fetch` returns that function.\n *\n * If not, `tf.util.fetch` returns a platform-specific solution.\n *\n * ```js\n * const resource = await tf.util.fetch('https://unpkg.com/@tensorflow/tfjs');\n * // handle response\n * ```\n *\n * @doc {heading: 'Util'}\n */\nexport function fetch(\n path: string, requestInits?: RequestInit): Promise {\n return env().platform.fetch(path, requestInits);\n}\n\n/**\n * Encodes the provided string into bytes using the provided encoding scheme.\n *\n * @param s The string to encode.\n * @param encoding The encoding scheme. Defaults to utf-8.\n *\n * @doc {heading: 'Util'}\n */\nexport function encodeString(s: string, encoding = 'utf-8'): Uint8Array {\n encoding = encoding || 'utf-8';\n return env().platform.encode(s, encoding);\n}\n\n/**\n * Decodes the provided bytes into a string using the provided encoding scheme.\n * @param bytes The bytes to decode.\n *\n * @param encoding The encoding scheme. Defaults to utf-8.\n *\n * @doc {heading: 'Util'}\n */\nexport function decodeString(bytes: Uint8Array, encoding = 'utf-8'): string {\n encoding = encoding || 'utf-8';\n return env().platform.decode(bytes, encoding);\n}\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n// Workaround for allowing cjs module to be included in bundle created by\n// rollup.\nimport * as LongExports from 'long';\n// tslint:disable-next-line\nconst Long: LongExports.LongConstructor =\n // tslint:disable-next-line\n (LongExports as any).default || LongExports;\n\nexport function hexToLong(hex: string): Long {\n return Long.fromString(hex, true, 16);\n}\n\n// Some primes between 2^63 and 2^64 for various uses.\n// Hex 0xc3a5c85c97cb3127\nconst k0: Long = hexToLong('c3a5c85c97cb3127');\n// Hex 0xb492b66fbe98f273\nconst k1: Long = hexToLong('b492b66fbe98f273');\n// Hex 0x9ae16a3b2f90404f\nconst k2: Long = hexToLong('9ae16a3b2f90404f');\n\nfunction shiftMix(val: Long): Long {\n return val.xor(val.shru(47));\n}\n\nfunction fetch(s: Uint8Array, offset: number, numBytes: number): Long {\n const bytes = s.slice(offset, offset + numBytes);\n return Long.fromBytes(Array.from(bytes), true, true);\n}\n\nfunction fetch64(s: Uint8Array, offset: number): Long {\n return fetch(s, offset, 8);\n}\n\nfunction fetch32(s: Uint8Array, offset: number): Long {\n return fetch(s, offset, 4);\n}\n\nfunction rotate64(val: Long, shift: number): Long {\n // Avoid shifting by 64: doing so yields an undefined result.\n return shift === 0 ? val : val.shru(shift).or(val.shl(64 - shift));\n}\n\nfunction hashLen16(u: Long, v: Long, mul = hexToLong('9ddfea08eb382d69')) {\n // Murmur-inspired hashing.\n let a = u.xor(v).mul(mul);\n a = a.xor(a.shru(47));\n let b = v.xor(a).mul(mul);\n b = b.xor(b.shru(47));\n b = b.mul(mul);\n return b;\n}\n\n// Return a 16-byte hash for 48 bytes. Quick and dirty.\n// Callers do best to use \"random-looking\" values for a and b.\nfunction weakHashLen32WithSeeds(\n w: Long, x: Long, y: Long, z: Long, a: Long, b: Long) {\n a = a.add(w);\n b = rotate64(b.add(a).add(z), 21);\n const c = a;\n a = a.add(x);\n a = a.add(y);\n b = b.add(rotate64(a, 44));\n return [a.add(z), b.add(c)];\n}\n\nfunction weakHashLen32WithSeedsStr(\n s: Uint8Array, offset: number, a: Long, b: Long) {\n return weakHashLen32WithSeeds(\n fetch64(s, offset), fetch64(s, offset + 8), fetch64(s, offset + 16),\n fetch64(s, offset + 24), a, b);\n}\n\nfunction hashLen0to16(s: Uint8Array, len = s.length): Long {\n if (len >= 8) {\n const mul = k2.add(len * 2);\n const a = fetch64(s, 0).add(k2);\n const b = fetch64(s, len - 8);\n const c = rotate64(b, 37).mul(mul).add(a);\n const d = rotate64(a, 25).add(b).mul(mul);\n return hashLen16(c, d, mul);\n }\n if (len >= 4) {\n const mul = k2.add(len * 2);\n const a = fetch32(s, 0);\n return hashLen16(a.shl(3).add(len), fetch32(s, len - 4), mul);\n }\n if (len > 0) {\n const a = s[0];\n const b = s[len >> 1];\n const c = s[len - 1];\n const y = a + (b << 8);\n const z = len + (c << 2);\n return shiftMix(k2.mul(y).xor(k0.mul(z))).mul(k2);\n }\n return k2;\n}\n\nfunction hashLen17to32(s: Uint8Array, len = s.length): Long {\n const mul = k2.add(len * 2);\n const a = fetch64(s, 0).mul(k1);\n const b = fetch64(s, 8);\n const c = fetch64(s, len - 8).mul(mul);\n const d = fetch64(s, len - 16).mul(k2);\n return hashLen16(\n rotate64(a.add(b), 43).add(rotate64(c, 30)).add(d),\n a.add(rotate64(b.add(k2), 18)).add(c), mul);\n}\n\nfunction hashLen33to64(s: Uint8Array, len = s.length): Long {\n const mul = k2.add(len * 2);\n const a = fetch64(s, 0).mul(k2);\n const b = fetch64(s, 8);\n const c = fetch64(s, len - 8).mul(mul);\n const d = fetch64(s, len - 16).mul(k2);\n const y = rotate64(a.add(b), 43).add(rotate64(c, 30)).add(d);\n const z = hashLen16(y, a.add(rotate64(b.add(k2), 18)).add(c), mul);\n const e = fetch64(s, 16).mul(mul);\n const f = fetch64(s, 24);\n const g = y.add(fetch64(s, len - 32)).mul(mul);\n const h = z.add(fetch64(s, len - 24)).mul(mul);\n return hashLen16(\n rotate64(e.add(f), 43).add(rotate64(g, 30)).add(h),\n e.add(rotate64(f.add(a), 18)).add(g), mul);\n}\n\nexport function fingerPrint64(s: Uint8Array, len = s.length): Long {\n const seed: Long = Long.fromNumber(81, true);\n if (len <= 32) {\n if (len <= 16) {\n return hashLen0to16(s, len);\n } else {\n return hashLen17to32(s, len);\n }\n } else if (len <= 64) {\n return hashLen33to64(s, len);\n }\n\n // For strings over 64 bytes we loop. Internal state consists of\n // 56 bytes: v, w, x, y, and z.\n let x = seed;\n let y = seed.mul(k1).add(113);\n\n let z = shiftMix(y.mul(k2).add(113)).mul(k2);\n let v = [Long.UZERO, Long.UZERO];\n let w = [Long.UZERO, Long.UZERO];\n x = x.mul(k2).add(fetch64(s, 0));\n\n let offset = 0;\n // Set end so that after the loop we have 1 to 64 bytes left to process.\n const end = ((len - 1) >> 6) * 64;\n const last64 = end + ((len - 1) & 63) - 63;\n\n do {\n x = rotate64(x.add(y).add(v[0]).add(fetch64(s, offset + 8)), 37).mul(k1);\n y = rotate64(y.add(v[1]).add(fetch64(s, offset + 48)), 42).mul(k1);\n x = x.xor(w[1]);\n y = y.add(v[0]).add(fetch64(s, offset + 40));\n z = rotate64(z.add(w[0]), 33).mul(k1);\n v = weakHashLen32WithSeedsStr(s, offset, v[1].mul(k1), x.add(w[0]));\n w = weakHashLen32WithSeedsStr(\n s, offset + 32, z.add(w[1]), y.add(fetch64(s, offset + 16)));\n\n [z, x] = [x, z];\n offset += 64;\n } while (offset !== end);\n const mul = k1.add(z.and(0xff).shl(1));\n // Point to the last 64 bytes of input.\n offset = last64;\n\n w[0] = w[0].add((len - 1) & 63);\n v[0] = v[0].add(w[0]);\n w[0] = w[0].add(v[0]);\n\n x = rotate64(x.add(y).add(v[0]).add(fetch64(s, offset + 8)), 37).mul(mul);\n y = rotate64(y.add(v[1]).add(fetch64(s, offset + 48)), 42).mul(mul);\n x = x.xor(w[1].mul(9));\n y = y.add(v[0].mul(9).add(fetch64(s, offset + 40)));\n z = rotate64(z.add(w[0]), 33).mul(mul);\n v = weakHashLen32WithSeedsStr(s, offset, v[1].mul(mul), x.add(w[0]));\n w = weakHashLen32WithSeedsStr(\n s, offset + 32, z.add(w[1]), y.add(fetch64(s, offset + 16)));\n\n [z, x] = [x, z];\n\n return hashLen16(\n hashLen16(v[0], w[0], mul).add(shiftMix(y).mul(k0)).add(z),\n hashLen16(v[1], w[1], mul).add(x), mul);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {BackendTimer, BackendTimingInfo} from './backends/backend';\nimport {env} from './environment';\nimport {Tensor} from './tensor';\nimport {NamedTensorMap} from './tensor_types';\nimport {DataType, DataTypeMap, TypedArray} from './types';\nimport * as util from './util';\n\nexport type KernelProfile = {\n kernelName: string,\n outputs: Tensor[],\n inputs: NamedTensorMap,\n timeMs: Promise,\n extraInfo: Promise\n};\n\nexport class Profiler {\n constructor(private backendTimer: BackendTimer, private logger?: Logger) {\n if (logger == null) {\n this.logger = new Logger();\n }\n }\n\n profileKernel(kernelName: string, inputs: NamedTensorMap, f: () => Tensor[]):\n KernelProfile {\n let outputs: Tensor[];\n const holdResultWrapperFn = () => {\n outputs = f();\n };\n let timer: Promise;\n const start = util.now();\n if (this.backendTimer.timerAvailable()) {\n timer = this.backendTimer.time(holdResultWrapperFn);\n } else {\n holdResultWrapperFn();\n for (const output of outputs) {\n output.dataSync();\n }\n timer = Promise.resolve({kernelMs: util.now() - start});\n }\n if (env().getBool('CHECK_COMPUTATION_FOR_ERRORS')) {\n for (let i = 0; i < outputs.length; i++) {\n const output = outputs[i];\n // Dangling promise here because we don't want to propagate up\n // asynchronicity.\n output.data().then(tensorVals => {\n checkComputationForErrors(tensorVals, output.dtype, kernelName);\n });\n }\n }\n\n const kernelProfile = {\n kernelName,\n outputs,\n inputs,\n timeMs: timer.then(timing => timing.kernelMs),\n extraInfo: timer.then(\n timing => timing.getExtraProfileInfo != null ?\n timing.getExtraProfileInfo() :\n '')\n };\n return kernelProfile;\n }\n\n logKernelProfile(kernelProfile: KernelProfile): void {\n const {kernelName, outputs, timeMs, inputs, extraInfo} = kernelProfile;\n\n outputs.forEach(result => {\n Promise.all([result.data(), timeMs, extraInfo]).then(valueContainer => {\n this.logger.logKernelProfile(\n kernelName, result, valueContainer[0], valueContainer[1], inputs,\n valueContainer[2]);\n });\n });\n }\n}\n\nexport function checkComputationForErrors(\n vals: DataTypeMap[D], dtype: D, kernelName: string): boolean {\n if (dtype !== 'float32') {\n // Only floating point computations will generate NaN values\n return false;\n }\n for (let i = 0; i < vals.length; i++) {\n const num = vals[i] as number;\n if (isNaN(num) || !isFinite(num)) {\n // Throwing custom exception so behavior is testable.\n console.warn(`Found ${num} in the result of '${kernelName}'`);\n return true;\n }\n }\n return false;\n}\n\nexport class Logger {\n logKernelProfile(\n name: string, result: Tensor, vals: TypedArray,\n timeMs: number|{error: string}, inputs: NamedTensorMap,\n extraInfo?: string) {\n const time = typeof timeMs === 'number' ? util.rightPad(`${timeMs}ms`, 9) :\n timeMs['error'];\n const paddedName = util.rightPad(name, 25);\n const rank = result.rank;\n const size = result.size;\n const shape = util.rightPad(result.shape.toString(), 14);\n let inputShapesDescription = '';\n\n for (const name in inputs) {\n const input = inputs[name];\n if (input != null) {\n // The input might be a non-tensor (e.g HTMLImageElement), in which case\n // we claim the output shape as input shape.\n const inputShape = input.shape || result.shape;\n const inputRank = inputShape.length;\n inputShapesDescription +=\n `${name}: ${inputRank}D ${inputRank > 0 ? inputShape : ''} `;\n }\n }\n\n console.log(\n `%c${paddedName}\\t%c${time}\\t%c${rank}D ${shape}\\t%c${size}\\t%c${\n inputShapesDescription}\\t%c${extraInfo}`,\n 'font-weight:bold', 'color:red', 'color:blue', 'color: orange',\n 'color: green', 'color: steelblue');\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from './tensor';\nimport {NamedTensorMap} from './tensor_types';\nimport * as util from './util';\n\nexport interface TapeNode {\n id: number;\n kernelName: string;\n outputs: Tensor[];\n inputs: NamedTensorMap;\n // Optional params, defined only for ops with gradient impl.\n gradient?: (dys: Tensor[]) => NamedGradientMap;\n saved?: Tensor[];\n}\n\nexport type NamedGradientMap = {\n [inputName: string]: () => Tensor;\n};\n\n/**\n * Computes a list of TapeNodes that connect x to y, filtering everything else\n * out and preserving the order of the original tape elements.\n *\n * @param tape The tape elements to filter.\n * @param xs The input Tensors.\n * @param y The output Tensor.\n */\nexport function getFilteredNodesXToY(\n tape: TapeNode[], xs: Tensor[], y: Tensor): TapeNode[] {\n // Forward pass to compute all the nodes and Tensors that are transitively a\n // function of x.\n const tensorsFromX: {[tensorId: number]: boolean} = {};\n const nodesFromX: {[nodeId: number]: boolean} = {};\n for (let i = 0; i < xs.length; i++) {\n tensorsFromX[xs[i].id] = true;\n }\n\n for (let i = 0; i < tape.length; i++) {\n const node = tape[i];\n const nodeInputs = node.inputs;\n for (const inputName in nodeInputs) {\n const input = nodeInputs[inputName];\n\n let anyInputFromX = false;\n for (let j = 0; j < xs.length; j++) {\n if (tensorsFromX[input.id]) {\n node.outputs.forEach(output => tensorsFromX[output.id] = true);\n anyInputFromX = true;\n nodesFromX[node.id] = true;\n break;\n }\n }\n\n if (anyInputFromX) {\n break;\n }\n }\n }\n\n // Backward pass to find all of the nodes and Tensors that lead to y.\n const tensorsLeadToY: {[tensorId: number]: boolean} = {};\n tensorsLeadToY[y.id] = true;\n const nodesToY: {[nodeId: number]: boolean} = {};\n\n for (let i = tape.length - 1; i >= 0; i--) {\n const node = tape[i];\n const nodeInputs = node.inputs;\n\n // If any of the outputs lead to y, mark all of the inputs as leading to y.\n for (let j = 0; j < node.outputs.length; j++) {\n if (tensorsLeadToY[node.outputs[j].id]) {\n for (const inputName in nodeInputs) {\n tensorsLeadToY[nodeInputs[inputName].id] = true;\n nodesToY[node.id] = true;\n }\n break;\n }\n }\n }\n\n // Return the paths that come from x and lead to y.\n const filteredTape: TapeNode[] = [];\n for (let i = 0; i < tape.length; i++) {\n const node = tape[i];\n\n if (nodesFromX[node.id] && nodesToY[node.id]) {\n // Prune the inputs from the node that aren't a function of x.\n const prunedInputs: {[inputName: string]: Tensor} = {};\n for (const inputName in node.inputs) {\n const nodeInput = node.inputs[inputName];\n if (tensorsFromX[nodeInput.id]) {\n prunedInputs[inputName] = nodeInput;\n }\n }\n\n // Copy the node and overwrite inputsAndArgs to the pruned version.\n const prunedNode = Object.assign({}, node);\n prunedNode.inputs = prunedInputs;\n prunedNode.outputs = node.outputs;\n\n filteredTape.push(prunedNode);\n }\n }\n\n return filteredTape;\n}\n\n/**\n * Backpropagate gradients through the filtered TapeNodes.\n *\n * @param tensorAccumulatedGradientMap A map of Tensor to its gradient. This map\n * is mutated by this method.\n * @param filteredTape The filtered TapeNodes to backprop through.\n */\nexport function backpropagateGradients(\n tensorAccumulatedGradientMap: {[tensorId: number]: Tensor},\n filteredTape: TapeNode[], tidy: (f: Function) => Tensor,\n add: (a: Tensor, b: Tensor) => Tensor) {\n // Walk the tape backward and keep a map of Tensor to its gradient.\n for (let i = filteredTape.length - 1; i >= 0; i--) {\n const node = filteredTape[i];\n\n const dys: Tensor[] = [];\n node.outputs.forEach(o => {\n const gradTensor = tensorAccumulatedGradientMap[o.id];\n if (gradTensor != null) {\n dys.push(gradTensor);\n } else {\n // This particular output is not in the back-propagation subgraph, so it\n // does not affect the final output, thus we put null for its dy.\n dys.push(null);\n }\n });\n\n if (node.gradient == null) {\n throw new Error(\n `Cannot compute gradient: gradient function not found ` +\n `for ${node.kernelName}.`);\n }\n\n // Backprop dy through this node and accumulate gradients over the inputs.\n const inputGradients = node.gradient(dys);\n\n for (const inputName in node.inputs) {\n if (!(inputName in inputGradients)) {\n throw new Error(\n `Cannot backprop through input ${inputName}. ` +\n `Available gradients found: ${Object.keys(inputGradients)}.`);\n }\n\n // Call the gradient function.\n const dx = tidy(() => inputGradients[inputName]());\n if (dx.dtype !== 'float32') {\n throw new Error(\n `Error in gradient for op ${\n node.kernelName}. The gradient of input ` +\n `${inputName} must have 'float32' dtype, but has '${dx.dtype}'`);\n }\n const x = node.inputs[inputName];\n if (!util.arraysEqual(dx.shape, x.shape)) {\n throw new Error(\n `Error in gradient for op ${\n node.kernelName}. The gradient of input ` +\n `'${inputName}' has shape '${dx.shape}', which does not match ` +\n `the shape of the input '${x.shape}'`);\n }\n\n if (tensorAccumulatedGradientMap[x.id] == null) {\n tensorAccumulatedGradientMap[x.id] = dx;\n } else {\n const curGradient = tensorAccumulatedGradientMap[x.id];\n tensorAccumulatedGradientMap[x.id] = add(curGradient, dx);\n curGradient.dispose();\n }\n }\n }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, TypedArray} from './types';\nimport {computeStrides, isString, rightPad, sizeFromShape} from './util';\n\n// Maximum number of values before we decide to show ellipsis.\nconst FORMAT_LIMIT_NUM_VALS = 20;\n// Number of first and last values to show when displaying a, b,...,y, z.\nconst FORMAT_NUM_FIRST_LAST_VALS = 3;\n// Number of significant digits to show.\nconst FORMAT_NUM_SIG_DIGITS = 7;\n\nexport function tensorToString(\n vals: TypedArray|string[], shape: number[], dtype: DataType,\n verbose: boolean) {\n const strides = computeStrides(shape);\n const padPerCol = computeMaxSizePerColumn(vals, shape, dtype, strides);\n const rank = shape.length;\n const valsLines = subTensorToString(vals, shape, dtype, strides, padPerCol);\n const lines = ['Tensor'];\n if (verbose) {\n lines.push(` dtype: ${dtype}`);\n lines.push(` rank: ${rank}`);\n lines.push(` shape: [${shape}]`);\n lines.push(` values:`);\n }\n lines.push(valsLines.map(l => ' ' + l).join('\\n'));\n return lines.join('\\n');\n}\n\nfunction computeMaxSizePerColumn(\n vals: TypedArray|string[], shape: number[], dtype: DataType,\n strides: number[]): number[] {\n const n = sizeFromShape(shape);\n const numCols = strides[strides.length - 1];\n const padPerCol = new Array(numCols).fill(0);\n const rank = shape.length;\n const valuesOrTuples =\n dtype === 'complex64' ? createComplexTuples(vals) : vals;\n\n if (rank > 1) {\n for (let row = 0; row < n / numCols; row++) {\n const offset = row * numCols;\n for (let j = 0; j < numCols; j++) {\n padPerCol[j] = Math.max(\n padPerCol[j],\n valToString(valuesOrTuples[offset + j], 0, dtype).length);\n }\n }\n }\n return padPerCol;\n}\n\nfunction valToString(\n val: number|string|[number, number], pad: number, dtype: DataType) {\n let valStr: string;\n if (Array.isArray(val)) {\n valStr = `${parseFloat(val[0].toFixed(FORMAT_NUM_SIG_DIGITS))} + ` +\n `${parseFloat(val[1].toFixed(FORMAT_NUM_SIG_DIGITS))}j`;\n } else if (isString(val)) {\n valStr = `'${val}'`;\n } else if (dtype === 'bool') {\n valStr = boolNumToString(val);\n } else {\n valStr = parseFloat(val.toFixed(FORMAT_NUM_SIG_DIGITS)).toString();\n }\n\n return rightPad(valStr, pad);\n}\n\nfunction boolNumToString(v: number): string {\n return v === 0 ? 'false' : 'true';\n}\n\nfunction subTensorToString(\n vals: TypedArray|string[], shape: number[], dtype: DataType,\n strides: number[], padPerCol: number[], isLast = true): string[] {\n const storagePerElement = dtype === 'complex64' ? 2 : 1;\n\n const size = shape[0];\n const rank = shape.length;\n if (rank === 0) {\n if (dtype === 'complex64') {\n const complexTuple = createComplexTuples(vals);\n return [valToString(complexTuple[0], 0, dtype)];\n }\n if (dtype === 'bool') {\n return [boolNumToString(vals[0] as number)];\n }\n return [vals[0].toString()];\n }\n\n if (rank === 1) {\n if (size > FORMAT_LIMIT_NUM_VALS) {\n const firstValsSize = FORMAT_NUM_FIRST_LAST_VALS * storagePerElement;\n\n let firstVals = Array.from(\n vals.slice(0, firstValsSize));\n let lastVals = Array.from(vals.slice(\n (size - FORMAT_NUM_FIRST_LAST_VALS) * storagePerElement,\n size * storagePerElement));\n if (dtype === 'complex64') {\n firstVals = createComplexTuples(firstVals);\n lastVals = createComplexTuples(lastVals);\n }\n return [\n '[' +\n firstVals.map((x, i) => valToString(x, padPerCol[i], dtype))\n .join(', ') +\n ', ..., ' +\n lastVals\n .map(\n (x, i) => valToString(\n x, padPerCol[size - FORMAT_NUM_FIRST_LAST_VALS + i], dtype))\n .join(', ') +\n ']'\n ];\n }\n const displayVals: Array =\n dtype === 'complex64' ? createComplexTuples(vals) :\n Array.from(vals);\n\n return [\n '[' +\n displayVals.map((x, i) => valToString(x, padPerCol[i], dtype))\n .join(', ') +\n ']'\n ];\n }\n\n // The array is rank 2 or more.\n const subshape = shape.slice(1);\n const substrides = strides.slice(1);\n const stride = strides[0] * storagePerElement;\n const lines: string[] = [];\n if (size > FORMAT_LIMIT_NUM_VALS) {\n for (let i = 0; i < FORMAT_NUM_FIRST_LAST_VALS; i++) {\n const start = i * stride;\n const end = start + stride;\n lines.push(...subTensorToString(\n vals.slice(start, end), subshape, dtype, substrides, padPerCol,\n false /* isLast */));\n }\n lines.push('...');\n for (let i = size - FORMAT_NUM_FIRST_LAST_VALS; i < size; i++) {\n const start = i * stride;\n const end = start + stride;\n lines.push(...subTensorToString(\n vals.slice(start, end), subshape, dtype, substrides, padPerCol,\n i === size - 1 /* isLast */));\n }\n } else {\n for (let i = 0; i < size; i++) {\n const start = i * stride;\n const end = start + stride;\n lines.push(...subTensorToString(\n vals.slice(start, end), subshape, dtype, substrides, padPerCol,\n i === size - 1 /* isLast */));\n }\n }\n const sep = rank === 2 ? ',' : '';\n lines[0] = '[' + lines[0] + sep;\n for (let i = 1; i < lines.length - 1; i++) {\n lines[i] = ' ' + lines[i] + sep;\n }\n let newLineSep = ',\\n';\n for (let i = 2; i < rank; i++) {\n newLineSep += '\\n';\n }\n lines[lines.length - 1] =\n ' ' + lines[lines.length - 1] + ']' + (isLast ? '' : newLineSep);\n return lines;\n}\n\nfunction createComplexTuples(vals: Array<{}>|\n TypedArray): Array<[number, number]> {\n const complexTuples: Array<[number, number]> = [];\n for (let i = 0; i < vals.length; i += 2) {\n complexTuples.push([vals[i], vals[i + 1]] as [number, number]);\n }\n return complexTuples;\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {getGlobal} from './global_util';\nimport {tensorToString} from './tensor_format';\nimport {ArrayMap, BackendValues, DataType, DataTypeMap, DataValues, NumericDataType, Rank, ShapeMap, SingleValueMap, TypedArray} from './types';\nimport * as util from './util';\nimport {computeStrides, toNestedArray} from './util';\n\nexport interface TensorData {\n dataId?: DataId;\n values?: DataTypeMap[D];\n}\n\n// This interface mimics KernelBackend (in backend.ts), which would create a\n// circular dependency if imported.\nexport interface Backend {}\n\n/**\n * A mutable object, similar to `tf.Tensor`, that allows users to set values\n * at locations before converting to an immutable `tf.Tensor`.\n *\n * See `tf.buffer` for creating a tensor buffer.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\nexport class TensorBuffer {\n size: number;\n shape: ShapeMap[R];\n strides: number[];\n values: DataTypeMap[D];\n\n constructor(shape: ShapeMap[R], public dtype: D, values?: DataTypeMap[D]) {\n this.shape = shape.slice() as ShapeMap[R];\n this.size = util.sizeFromShape(shape);\n\n if (values != null) {\n const n = values.length;\n util.assert(\n n === this.size,\n () => `Length of values '${n}' does not match the size ` +\n `inferred by the shape '${this.size}'.`);\n }\n if (dtype === 'complex64') {\n throw new Error(\n `complex64 dtype TensorBuffers are not supported. Please create ` +\n `a TensorBuffer for the real and imaginary parts separately and ` +\n `call tf.complex(real, imag).`);\n }\n this.values = values || util.getArrayFromDType(dtype, this.size);\n this.strides = computeStrides(shape);\n }\n\n /**\n * Sets a value in the buffer at a given location.\n *\n * @param value The value to set.\n * @param locs The location indices.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\n set(value: SingleValueMap[D], ...locs: number[]): void {\n if (locs.length === 0) {\n locs = [0];\n }\n util.assert(\n locs.length === this.rank,\n () => `The number of provided coordinates (${locs.length}) must ` +\n `match the rank (${this.rank})`);\n\n const index = this.locToIndex(locs);\n this.values[index] = value as number;\n }\n\n /**\n * Returns the value in the buffer at the provided location.\n *\n * @param locs The location indices.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\n get(...locs: number[]): SingleValueMap[D] {\n if (locs.length === 0) {\n locs = [0];\n }\n let i = 0;\n for (const loc of locs) {\n if (loc < 0 || loc >= this.shape[i]) {\n const msg = `Requested out of range element at ${locs}. ` +\n ` Buffer shape=${this.shape}`;\n throw new Error(msg);\n }\n i++;\n }\n let index = locs[locs.length - 1];\n for (let i = 0; i < locs.length - 1; ++i) {\n index += this.strides[i] * locs[i];\n }\n return this.values[index] as SingleValueMap[D];\n }\n\n locToIndex(locs: number[]): number {\n if (this.rank === 0) {\n return 0;\n } else if (this.rank === 1) {\n return locs[0];\n }\n let index = locs[locs.length - 1];\n for (let i = 0; i < locs.length - 1; ++i) {\n index += this.strides[i] * locs[i];\n }\n return index;\n }\n\n indexToLoc(index: number): number[] {\n if (this.rank === 0) {\n return [];\n } else if (this.rank === 1) {\n return [index];\n }\n const locs: number[] = new Array(this.shape.length);\n for (let i = 0; i < locs.length - 1; ++i) {\n locs[i] = Math.floor(index / this.strides[i]);\n index -= locs[i] * this.strides[i];\n }\n locs[locs.length - 1] = index;\n return locs;\n }\n\n get rank() {\n return this.shape.length;\n }\n\n /**\n * Creates an immutable `tf.Tensor` object from the buffer.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\n toTensor(): Tensor {\n return trackerFn().makeTensor(this.values, this.shape, this.dtype) as\n Tensor;\n }\n}\n\nexport interface TensorTracker {\n makeTensor(\n values: DataValues, shape: number[], dtype: DataType,\n backend?: Backend): Tensor;\n makeVariable(\n initialValue: Tensor, trainable?: boolean, name?: string,\n dtype?: DataType): Variable;\n incRef(a: Tensor, backend: Backend): void;\n disposeTensor(t: Tensor): void;\n disposeVariable(v: Variable): void;\n read(dataId: DataId): Promise;\n readSync(dataId: DataId): BackendValues;\n}\n\n/**\n * The Tensor class calls into this handler to delegate chaining operations.\n */\nexport interface OpHandler {\n cast(x: T, dtype: DataType): T;\n buffer(\n shape: ShapeMap[R], dtype: D,\n values?: DataTypeMap[D]): TensorBuffer;\n print(x: T, verbose: boolean): void;\n clone(x: T): T;\n // TODO(yassogba) bring reshape back?\n}\n\n// For tracking tensor creation and disposal.\nlet trackerFn: () => TensorTracker = null;\n// Used by chaining methods to call into ops.\nlet opHandler: OpHandler = null;\n// Used to warn about deprecated methods.\nlet deprecationWarningFn: (msg: string) => void = null;\n// This here so that we can use this method on dev branches and keep the\n// functionality at master.\n// tslint:disable-next-line:no-unused-expression\n[deprecationWarningFn];\n\n/**\n * An external consumer can register itself as the tensor tracker. This way\n * the Tensor class can notify the tracker for every tensor created and\n * disposed.\n */\nexport function setTensorTracker(fn: () => TensorTracker) {\n trackerFn = fn;\n}\n\n/**\n * An external consumer can register itself as the op handler. This way the\n * Tensor class can have chaining methods that call into ops via the op\n * handler.\n */\nexport function setOpHandler(handler: OpHandler) {\n opHandler = handler;\n}\n\n/**\n * Sets the deprecation warning function to be used by this file. This way the\n * Tensor class can be a leaf but still use the environment.\n */\nexport function setDeprecationWarningFn(fn: (msg: string) => void) {\n deprecationWarningFn = fn;\n}\n\n/**\n * We wrap data id since we use weak map to avoid memory leaks.\n * Since we have our own memory management, we have a reference counter\n * mapping a tensor to its data, so there is always a pointer (even if that\n * data is otherwise garbage collectable).\n * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/\n * Global_Objects/WeakMap\n */\nexport type DataId = object; // object instead of {} to force non-primitive.\n\n// Declare this namespace to make Tensor class augmentation work in google3.\nexport declare namespace Tensor {}\n/**\n * A `tf.Tensor` object represents an immutable, multidimensional array of\n * numbers that has a shape and a data type.\n *\n * For performance reasons, functions that create tensors do not necessarily\n * perform a copy of the data passed to them (e.g. if the data is passed as a\n * `Float32Array`), and changes to the data will change the tensor. This is not\n * a feature and is not supported. To avoid this behavior, use the tensor before\n * changing the input data or create a copy with `copy = tf.add(yourTensor, 0)`.\n *\n * See `tf.tensor` for details on how to create a `tf.Tensor`.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\nexport class Tensor {\n /** Unique id of this tensor. */\n readonly id: number;\n /**\n * Id of the bucket holding the data for this tensor. Multiple arrays can\n * point to the same bucket (e.g. when calling array.reshape()).\n */\n dataId: DataId;\n /** The shape of the tensor. */\n readonly shape: ShapeMap[R];\n /** Number of elements in the tensor. */\n readonly size: number;\n /** The data type for the array. */\n readonly dtype: DataType;\n /** The rank type for the array (see `Rank` enum). */\n readonly rankType: R;\n\n /** Whether this tensor has been globally kept. */\n kept = false;\n /** The id of the scope this tensor is being tracked in. */\n scopeId: number;\n\n /**\n * Number of elements to skip in each dimension when indexing. See\n * https://docs.scipy.org/doc/numpy/reference/generated/\\\n * numpy.ndarray.strides.html\n */\n readonly strides: number[];\n\n constructor(shape: ShapeMap[R], dtype: DataType, dataId: DataId, id: number) {\n this.shape = shape.slice() as ShapeMap[R];\n this.dtype = dtype || 'float32';\n this.size = util.sizeFromShape(shape);\n this.strides = computeStrides(shape);\n this.dataId = dataId;\n this.id = id;\n this.rankType = (this.rank < 5 ? this.rank.toString() : 'higher') as R;\n }\n\n get rank(): number {\n return this.shape.length;\n }\n\n /**\n * Returns a promise of `tf.TensorBuffer` that holds the underlying data.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n async buffer(): Promise> {\n const vals = await this.data();\n return opHandler.buffer(this.shape, this.dtype as D, vals);\n }\n\n /**\n * Returns a `tf.TensorBuffer` that holds the underlying data.\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n bufferSync(): TensorBuffer {\n return opHandler.buffer(this.shape, this.dtype as D, this.dataSync());\n }\n\n /**\n * Returns the tensor data as a nested array. The transfer of data is done\n * asynchronously.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n async array(): Promise {\n const vals = await this.data();\n return toNestedArray(this.shape, vals, this.dtype === 'complex64') as\n ArrayMap[R];\n }\n\n /**\n * Returns the tensor data as a nested array. The transfer of data is done\n * synchronously.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n arraySync(): ArrayMap[R] {\n return toNestedArray(\n this.shape, this.dataSync(), this.dtype === 'complex64') as\n ArrayMap[R];\n }\n\n /**\n * Asynchronously downloads the values from the `tf.Tensor`. Returns a\n * promise of `TypedArray` that resolves when the computation has finished.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n async data(): Promise {\n this.throwIfDisposed();\n const data = trackerFn().read(this.dataId);\n if (this.dtype === 'string') {\n const bytes = await data as Uint8Array[];\n try {\n return bytes.map(b => util.decodeString(b)) as DataTypeMap[D];\n } catch {\n throw new Error(\n 'Failed to decode the string bytes into utf-8. ' +\n 'To get the original bytes, call tensor.bytes().');\n }\n }\n return data as Promise;\n }\n\n /**\n * Synchronously downloads the values from the `tf.Tensor`. This blocks the\n * UI thread until the values are ready, which can cause performance issues.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n dataSync(): DataTypeMap[D] {\n this.throwIfDisposed();\n const data = trackerFn().readSync(this.dataId);\n if (this.dtype === 'string') {\n try {\n return (data as Uint8Array[]).map(b => util.decodeString(b)) as\n DataTypeMap[D];\n } catch {\n throw new Error(\n 'Failed to decode the string bytes into utf-8. ' +\n 'To get the original bytes, call tensor.bytes().');\n }\n }\n return data as DataTypeMap[D];\n }\n\n /** Returns the underlying bytes of the tensor's data. */\n async bytes(): Promise {\n this.throwIfDisposed();\n const data = await trackerFn().read(this.dataId);\n if (this.dtype === 'string') {\n return data as Uint8Array[];\n } else {\n return new Uint8Array((data as TypedArray).buffer);\n }\n }\n\n /**\n * Disposes `tf.Tensor` from memory.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n dispose(): void {\n if (this.isDisposed) {\n return;\n }\n trackerFn().disposeTensor(this);\n this.isDisposedInternal = true;\n }\n\n protected isDisposedInternal = false;\n get isDisposed(): boolean {\n return this.isDisposedInternal;\n }\n\n throwIfDisposed() {\n if (this.isDisposed) {\n throw new Error(`Tensor is disposed.`);\n }\n }\n\n /**\n * Prints the `tf.Tensor`. See `tf.print` for details.\n *\n * @param verbose Whether to print verbose information about the tensor,\n * including dtype and size.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n print(verbose = false): void {\n return opHandler.print(this, verbose);\n }\n\n /**\n * Returns a copy of the tensor. See `tf.clone` for details.\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n clone(this: T): T {\n this.throwIfDisposed();\n return opHandler.clone(this);\n }\n\n /**\n * Returns a human-readable description of the tensor. Useful for logging.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n toString(verbose = false): string {\n const vals = this.dataSync();\n return tensorToString(vals, this.shape, this.dtype, verbose);\n }\n\n cast(dtype: DataType): T {\n this.throwIfDisposed();\n return opHandler.cast(this as T, dtype);\n }\n variable(trainable = true, name?: string, dtype?: DataType): Variable {\n this.throwIfDisposed();\n return trackerFn().makeVariable(this, trainable, name, dtype) as\n Variable;\n }\n}\nObject.defineProperty(Tensor, Symbol.hasInstance, {\n value: (instance: Tensor) => {\n // Implementation note: we should use properties of the object that will be\n // defined before the constructor body has finished executing (methods).\n // This is because when this code is transpiled by babel, babel will call\n // classCallCheck before the constructor body is run.\n // See https://github.com/tensorflow/tfjs/issues/3384 for backstory.\n return !!instance && instance.data != null && instance.dataSync != null &&\n instance.throwIfDisposed != null;\n }\n});\n\nexport function getGlobalTensorClass() {\n // Use getGlobal so that we can augment the Tensor class across package\n // boundaries becase the node resolution alg may result in different modules\n // being returned for this file depending on the path they are loaded from.\n return getGlobal('Tensor', () => {\n return Tensor;\n });\n}\n\n// Global side effect. Cache global reference to Tensor class\ngetGlobalTensorClass();\n\nexport interface NumericTensor extends Tensor {\n dtype: NumericDataType;\n dataSync(): DataTypeMap[D];\n data(): Promise;\n}\n\nexport interface StringTensor extends Tensor {\n dtype: 'string';\n dataSync(): DataTypeMap[D];\n data(): Promise;\n}\n\n/** @doclink Tensor */\nexport type Scalar = Tensor;\n/** @doclink Tensor */\nexport type Tensor1D = Tensor;\n/** @doclink Tensor */\nexport type Tensor2D = Tensor;\n/** @doclink Tensor */\nexport type Tensor3D = Tensor;\n/** @doclink Tensor */\nexport type Tensor4D = Tensor;\n/** @doclink Tensor */\nexport type Tensor5D = Tensor;\n/** @doclink Tensor */\nexport type Tensor6D = Tensor;\n\n/**\n * A mutable `tf.Tensor`, useful for persisting state, e.g. for training.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\nexport class Variable extends Tensor {\n name: string;\n\n constructor(\n initialValue: Tensor, public trainable: boolean, name: string,\n tensorId: number) {\n super(\n initialValue.shape, initialValue.dtype, initialValue.dataId, tensorId);\n this.name = name;\n }\n\n /**\n * Assign a new `tf.Tensor` to this variable. The new `tf.Tensor` must have\n * the same shape and dtype as the old `tf.Tensor`.\n *\n * @param newValue New tensor to be assigned to this variable.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n assign(newValue: Tensor): void {\n if (newValue.dtype !== this.dtype) {\n throw new Error(\n `dtype of the new value (${newValue.dtype}) and ` +\n `previous value (${this.dtype}) must match`);\n }\n if (!util.arraysEqual(newValue.shape, this.shape)) {\n throw new Error(\n `shape of the new value (${newValue.shape}) and ` +\n `previous value (${this.shape}) must match`);\n }\n trackerFn().disposeTensor(this);\n this.dataId = newValue.dataId;\n trackerFn().incRef(this, null /* backend */);\n }\n\n dispose(): void {\n trackerFn().disposeVariable(this);\n this.isDisposedInternal = true;\n }\n}\n\nObject.defineProperty(Variable, Symbol.hasInstance, {\n value: (instance: Variable) => {\n return instance instanceof Tensor && instance.assign != null &&\n instance.assign instanceof Function;\n }\n});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from './tensor';\nimport {TensorContainer, TensorContainerArray} from './tensor_types';\nimport {upcastType} from './types';\nimport {assert} from './util';\n\nexport function makeTypesMatch(a: T, b: T): [T, T] {\n if (a.dtype === b.dtype) {\n return [a, b];\n }\n const dtype = upcastType(a.dtype, b.dtype);\n return [a.cast(dtype), b.cast(dtype)];\n}\n\nexport function assertTypesMatch(a: Tensor, b: Tensor): void {\n assert(\n a.dtype === b.dtype,\n () => `The dtypes of the first(${a.dtype}) and` +\n ` second(${b.dtype}) input must match`);\n}\n\nexport function isTensorInList(tensor: Tensor, tensorList: Tensor[]): boolean {\n return tensorList.some(x => x.id === tensor.id);\n}\n\n/**\n * Extracts any `Tensor`s found within the provided object.\n *\n * @param container an object that may be a `Tensor` or may directly contain\n * `Tensor`s, such as a `Tensor[]` or `{key: Tensor, ...}`. In general it\n * is safe to pass any object here, except that `Promise`s are not\n * supported.\n * @returns An array of `Tensors` found within the passed object. If the\n * argument is simply a `Tensor', a list containing that `Tensor` is\n * returned. If the object is not a `Tensor` or does not\n * contain `Tensors`, an empty list is returned.\n */\nexport function getTensorsInContainer(result: TensorContainer): Tensor[] {\n const list: Tensor[] = [];\n const seen = new Set<{}|void>();\n walkTensorContainer(result, list, seen);\n return list;\n}\n\nfunction walkTensorContainer(\n container: TensorContainer, list: Tensor[], seen: Set<{}|void>): void {\n if (container == null) {\n return;\n }\n if (container instanceof Tensor) {\n list.push(container);\n return;\n }\n if (!isIterable(container)) {\n return;\n }\n // Iteration over keys works also for arrays.\n const iterable = container as TensorContainerArray;\n for (const k in iterable) {\n const val = iterable[k];\n if (!seen.has(val)) {\n seen.add(val);\n walkTensorContainer(val, list, seen);\n }\n }\n}\n\n// tslint:disable-next-line:no-any\nfunction isIterable(obj: any): boolean {\n return Array.isArray(obj) || typeof obj === 'object';\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/** @docalias number[] */\nexport interface ShapeMap {\n R0: number[];\n R1: [number];\n R2: [number, number];\n R3: [number, number, number];\n R4: [number, number, number, number];\n R5: [number, number, number, number, number];\n R6: [number, number, number, number, number, number];\n}\n\n/** @docalias number[] */\nexport interface ArrayMap {\n R0: number;\n R1: number[];\n R2: number[][];\n R3: number[][][];\n R4: number[][][][];\n R5: number[][][][][];\n R6: number[][][][][][];\n}\n\nexport interface DataTypeMap {\n float32: Float32Array;\n int32: Int32Array;\n bool: Uint8Array;\n complex64: Float32Array;\n string: string[];\n}\n\nexport interface SingleValueMap {\n bool: boolean;\n int32: number;\n float32: number;\n complex64: number;\n string: string;\n}\n\n/** @docalias 'float32'|'int32'|'bool'|'complex64'|'string' */\nexport type DataType = keyof DataTypeMap;\nexport type NumericDataType = 'float32'|'int32'|'bool'|'complex64';\nexport type TypedArray = Float32Array|Int32Array|Uint8Array;\n/** Tensor data used in tensor creation and user-facing API. */\nexport type DataValues = DataTypeMap[DataType];\n/** The underlying tensor data that gets stored in a backend. */\nexport type BackendValues = Float32Array|Int32Array|Uint8Array|Uint8Array[];\n\nexport enum Rank {\n R0 = 'R0',\n R1 = 'R1',\n R2 = 'R2',\n R3 = 'R3',\n R4 = 'R4',\n R5 = 'R5',\n R6 = 'R6'\n}\n\nexport type FlatVector = boolean[]|number[]|TypedArray;\nexport type RegularArray =\n T[]|T[][]|T[][][]|T[][][][]|T[][][][][]|T[][][][][][];\n\n// tslint:disable-next-line:no-any\nexport interface RecursiveArray {\n [index: number]: T|RecursiveArray;\n}\n\n// Looks for upcasting types. Used, for example, in operations with mixed dtype\n// inputs.\nenum UpcastInt32AndMap {\n 'float32' = 'float32',\n 'int32' = 'int32',\n 'bool' = 'int32',\n 'complex64' = 'complex64'\n}\n\nenum UpcastBoolAndMap {\n 'float32' = 'float32',\n 'int32' = 'int32',\n 'bool' = 'bool',\n 'complex64' = 'complex64'\n}\n\nenum UpcastFloat32AndMap {\n 'float32' = 'float32',\n 'int32' = 'float32',\n 'bool' = 'float32',\n 'complex64' = 'complex64'\n}\n\nenum UpcastComplex64AndMap {\n 'float32' = 'complex64',\n 'int32' = 'complex64',\n 'bool' = 'complex64',\n 'complex64' = 'complex64'\n}\n\nconst upcastTypeMap = {\n 'float32': UpcastFloat32AndMap,\n 'int32': UpcastInt32AndMap,\n 'bool': UpcastBoolAndMap,\n 'complex64': UpcastComplex64AndMap\n};\n\nexport function upcastType(typeA: DataType, typeB: DataType): DataType {\n if (typeA === 'string' || typeB === 'string') {\n if (typeA === 'string' && typeB === 'string') {\n return 'string';\n }\n throw new Error(`Can not upcast ${typeA} with ${typeB}`);\n }\n return upcastTypeMap[typeA][typeB];\n}\n\n/** Returns the output type after summation. */\nexport function sumOutType(type: DataType): DataType {\n return upcastType(type, 'int32');\n}\n\n/** @docalias TypedArray|Array */\nexport type TensorLike =\n TypedArray|number|boolean|string|RecursiveArray|\n RecursiveArray|RecursiveArray|Uint8Array[];\nexport type ScalarLike = number|boolean|string|Uint8Array;\n/** @docalias TypedArray|Array */\nexport type TensorLike1D = TypedArray|number[]|boolean[]|string[]|Uint8Array[];\n/** @docalias TypedArray|Array */\nexport type TensorLike2D = TypedArray|number[]|number[][]|boolean[]|boolean[][]|\n string[]|string[][]|Uint8Array[]|Uint8Array[][];\n/** @docalias TypedArray|Array */\nexport type TensorLike3D = TypedArray|number[]|number[][][]|boolean[]|\n boolean[][][]|string[]|string[][][]|Uint8Array[]|Uint8Array[][][];\n/** @docalias TypedArray|Array */\nexport type TensorLike4D = TypedArray|number[]|number[][][][]|boolean[]|\n boolean[][][][]|string[]|string[][][][]|Uint8Array[]|Uint8Array[][][][];\n/** @docalias TypedArray|Array */\nexport type TensorLike5D =\n TypedArray|number[]|number[][][][][]|boolean[]|boolean[][][][][]|string[]|\n string[][][][][]|Uint8Array[]|Uint8Array[][][][][];\n/** @docalias TypedArray|Array */\nexport type TensorLike6D =\n TypedArray|number[]|number[][][][][][]|boolean[]|boolean[][][][][][]|\n string[]|string[][][][][][]|Uint8Array[]|Uint8Array[][][][][];\n\n/** Type for representing image data in Uint8Array type. */\nexport interface PixelData {\n width: number;\n height: number;\n data: Uint8Array;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {BackendTimingInfo, DataMover, KernelBackend} from './backends/backend';\nimport {Environment, setEnvironmentGlobal} from './environment';\nimport {getGlobalNamespace} from './global_util';\nimport {Add, Cast, Identity} from './kernel_names';\nimport {getGradient, getKernel, getKernelsForBackend, GradFunc, NamedAttrMap, TensorInfo} from './kernel_registry';\nimport {KernelProfile, Profiler} from './profiler';\nimport {backpropagateGradients, getFilteredNodesXToY, TapeNode} from './tape';\nimport {DataId, setTensorTracker, Tensor, TensorTracker, Variable} from './tensor';\nimport {GradSaveFunc, NamedTensorMap, NamedVariableMap, TensorContainer} from './tensor_types';\nimport {getTensorsInContainer} from './tensor_util';\nimport {BackendValues, DataType, DataValues} from './types';\nimport * as util from './util';\nimport {bytesFromStringArray, makeOnesTypedArray, now, sizeFromShape} from './util';\nimport * as log from './log';\n/**\n * A function that computes an output. The save function is for saving tensors\n * computed in the forward pass, that we need in the backward pass.\n */\nexport type ForwardFunc = (backend: KernelBackend, save?: GradSaveFunc) => T;\n\n/**\n * @docalias (a: Tensor, b: Tensor,..., save?: Function) => {\n * value: Tensor,\n * gradFunc: (dy: Tensor, saved?: NamedTensorMap) => Tensor | Tensor[]\n * }\n */\nexport type CustomGradientFunc =\n (...inputs: Array) => {\n value: T;\n gradFunc: (dy: T, saved: Tensor[]) => Tensor | Tensor[];\n };\n\nexport type MemoryInfo = {\n numTensors: number; numDataBuffers: number; numBytes: number;\n unreliable?: boolean; reasons: string[];\n};\n\ntype KernelInfo = {\n name: string; bytesAdded: number; totalBytesSnapshot: number;\n tensorsAdded: number;\n totalTensorsSnapshot: number;\n inputShapes: number[][];\n outputShapes: number[][];\n kernelTimeMs: number | {error: string} | Promise;\n extraInfo: string | Promise;\n};\n\nexport type ProfileInfo = {\n newBytes: number; newTensors: number; peakBytes: number;\n kernels: KernelInfo[];\n result: TensorContainer;\n kernelNames: string[];\n};\n\nexport interface TimingInfo extends BackendTimingInfo {\n wallMs: number;\n}\n\n/** @docalias Function */\nexport type ScopeFn = () => T;\n\ninterface ScopeState {\n track: Tensor[];\n name: string;\n id: number;\n}\n\ninterface RegisteredKernelInvocation {\n kernelName: string;\n inputs: I;\n attrs?: NamedAttrMap;\n}\n\ninterface CustomGradKernelInvocation {\n forwardFunc: ForwardFunc;\n backwardsFunc: (dy: T, saved: Tensor[]) => {\n [P in keyof I]: () => I[P]\n };\n inputs: I;\n attrs?: NamedAttrMap;\n}\n\nfunction isRegisteredKernelInvocation(\n kernelInvocation: RegisteredKernelInvocation|\n CustomGradKernelInvocation):\n kernelInvocation is RegisteredKernelInvocation {\n return (kernelInvocation as RegisteredKernelInvocation).kernelName != null;\n}\n\nclass EngineState {\n // Public since optimizers will use it.\n registeredVariables: NamedVariableMap = {};\n\n nextTapeNodeId = 0;\n numBytes = 0;\n numTensors = 0;\n numStringTensors = 0;\n numDataBuffers = 0;\n\n activeTape: TapeNode[];\n // Number of nested tf.grad() statements when computing higher-order\n // gradients. E.g. `1` for first-order gradients and `2` for second-order\n // gradients. Used to track if the tape should be removed after a backprop.\n gradientDepth = 0;\n // Number of nested kernel calls. When kernel depth is greater than 1, we turn\n // off the tape.\n kernelDepth = 0;\n\n // Keep Tensors that parallel the tapes.\n activeScope: ScopeState;\n scopeStack: ScopeState[] = [];\n /**\n * Keeps track of the number of data moves during a kernel execution. We\n * maintain a stack since kernels can call other kernels, recursively.\n */\n numDataMovesStack: number[] = [];\n nextScopeId = 0;\n\n tensorInfo = new WeakMap();\n\n profiling = false;\n activeProfile: ProfileInfo = {\n newBytes: 0,\n newTensors: 0,\n peakBytes: 0,\n kernels: [],\n result: null,\n get kernelNames():\n string[] {\n return Array.from(new Set(this.kernels.map(k => k.name)));\n }\n };\n\n dispose() {\n for (const variableName in this.registeredVariables) {\n this.registeredVariables[variableName].dispose();\n }\n }\n}\n\nexport class Engine implements TensorTracker, DataMover {\n state: EngineState;\n backendName: string;\n registry: {[id: string]: KernelBackend} = {};\n registryFactory: {\n [id: string]: {\n factory: () => KernelBackend | Promise,\n priority: number\n }\n } = {};\n\n private profiler: Profiler;\n private backendInstance: KernelBackend;\n private pendingBackendInit: Promise;\n private pendingBackendInitId = 0;\n\n constructor(public ENV: Environment) {\n this.state = new EngineState();\n }\n\n async ready(): Promise {\n if (this.pendingBackendInit != null) {\n return this.pendingBackendInit.then(() => {});\n }\n if (this.backendInstance != null) {\n return;\n }\n const sortedBackends = this.getSortedBackends();\n\n for (let i = 0; i < sortedBackends.length; i++) {\n const backendName = sortedBackends[i];\n const success = await this.initializeBackend(backendName).success;\n if (success) {\n await this.setBackend(backendName);\n return;\n }\n }\n\n throw new Error(\n `Could not initialize any backends, all backend initializations ` +\n `failed.`);\n }\n\n get backend(): KernelBackend {\n if (this.pendingBackendInit != null) {\n throw new Error(\n `Backend '${this.backendName}' has not yet been initialized. Make ` +\n `sure to await tf.ready() or await tf.setBackend() before calling ` +\n `other methods`);\n }\n if (this.backendInstance == null) {\n const {name, asyncInit} = this.initializeBackendsAndReturnBest();\n if (asyncInit) {\n throw new Error(\n `The highest priority backend '${name}' has not yet been ` +\n `initialized. Make sure to await tf.ready() or ` +\n `await tf.setBackend() before calling other methods`);\n }\n this.setBackend(name);\n }\n return this.backendInstance;\n }\n\n backendNames(): string[] {\n return Object.keys(this.registryFactory);\n }\n\n findBackend(backendName: string): KernelBackend {\n if (!(backendName in this.registry)) {\n // If the backend hasn't been initialized but we have a registry entry for\n // it, initialize it and return it.\n if (backendName in this.registryFactory) {\n const {asyncInit} = this.initializeBackend(backendName);\n if (asyncInit) {\n // Backend is not ready yet.\n return null;\n }\n } else {\n return null;\n }\n }\n return this.registry[backendName];\n }\n\n findBackendFactory(backendName: string):\n () => KernelBackend | Promise {\n if (!(backendName in this.registryFactory)) {\n return null;\n }\n return this.registryFactory[backendName].factory;\n }\n\n registerBackend(\n backendName: string,\n factory: () => KernelBackend | Promise,\n priority = 1): boolean {\n if (backendName in this.registryFactory) {\n log.warn(\n `${backendName} backend was already registered. ` +\n `Reusing existing backend factory.`);\n return false;\n }\n this.registryFactory[backendName] = {factory, priority};\n return true;\n }\n\n async setBackend(backendName: string): Promise {\n if (this.registryFactory[backendName] == null) {\n throw new Error(`Backend name '${backendName}' not found in registry`);\n }\n this.backendName = backendName;\n if (this.registry[backendName] == null) {\n this.backendInstance = null;\n const {success, asyncInit} = this.initializeBackend(backendName);\n const result = asyncInit ? await success : success;\n if (!result) {\n return false;\n }\n }\n this.backendInstance = this.registry[backendName];\n this.setupRegisteredKernels();\n // Reset the profiler.\n this.profiler = new Profiler(this.backendInstance);\n\n return true;\n }\n\n private setupRegisteredKernels(): void {\n const kernels = getKernelsForBackend(this.backendName);\n kernels.forEach(kernel => {\n if (kernel.setupFunc != null) {\n kernel.setupFunc(this.backendInstance);\n }\n });\n }\n\n private disposeRegisteredKernels(backendName: string): void {\n const kernels = getKernelsForBackend(backendName);\n kernels.forEach(kernel => {\n if (kernel.disposeFunc != null) {\n kernel.disposeFunc(this.registry[backendName]);\n }\n });\n }\n\n /**\n * Initializes a backend by looking up the backend name in the factory\n * registry and calling the factory method. Returns a boolean representing\n * whether the initialization of the backend suceeded. Throws an error if\n * there is no backend in the factory registry.\n */\n private initializeBackend(backendName: string):\n {success: boolean|Promise, asyncInit: boolean} {\n const registryFactoryEntry = this.registryFactory[backendName];\n if (registryFactoryEntry == null) {\n throw new Error(\n `Cannot initialize backend ${backendName}, no registration found.`);\n }\n\n try {\n const backend = registryFactoryEntry.factory();\n /* Test if the factory returns a promise.\n Done in a more liberal way than\n previous 'Promise.resolve(backend)===backend'\n as we needed to account for custom Promise\n implementations (e.g. Angular) */\n if (backend && !(backend instanceof KernelBackend) &&\n typeof backend.then === 'function') {\n const promiseId = ++this.pendingBackendInitId;\n const success =\n backend\n .then(backendInstance => {\n // Outdated promise. Another backend was set in the meantime.\n if (promiseId < this.pendingBackendInitId) {\n return false;\n }\n this.registry[backendName] = backendInstance;\n this.pendingBackendInit = null;\n return true;\n })\n .catch(err => {\n // Outdated promise. Another backend was set in the meantime.\n if (promiseId < this.pendingBackendInitId) {\n return false;\n }\n this.pendingBackendInit = null;\n log.warn(\n `Initialization of backend ${backendName} failed`);\n log.warn(err.stack || err.message);\n return false;\n });\n this.pendingBackendInit = success;\n return {success, asyncInit: true};\n } else {\n this.registry[backendName] = backend as KernelBackend;\n return {success: true, asyncInit: false};\n }\n } catch (err) {\n log.warn(`Initialization of backend ${backendName} failed`);\n log.warn(err.stack || err.message);\n return {success: false, asyncInit: false};\n }\n }\n\n removeBackend(backendName: string): void {\n if (!(backendName in this.registryFactory)) {\n throw new Error(`${backendName} backend not found in registry`);\n }\n if (this.backendName === backendName && this.pendingBackendInit != null) {\n // There is a pending promise of the backend we want to remove. Make it\n // obsolete.\n this.pendingBackendInitId++;\n }\n\n if (backendName in this.registry) {\n this.disposeRegisteredKernels(backendName);\n this.registry[backendName].dispose();\n delete this.registry[backendName];\n }\n\n delete this.registryFactory[backendName];\n\n // Unset the backend if it is active.\n if (this.backendName === backendName) {\n this.pendingBackendInit = null;\n this.backendName = null;\n this.backendInstance = null;\n }\n }\n\n private getSortedBackends(): string[] {\n if (Object.keys(this.registryFactory).length === 0) {\n throw new Error('No backend found in registry.');\n }\n return Object.keys(this.registryFactory).sort((a: string, b: string) => {\n // Highest priority comes first.\n return this.registryFactory[b].priority -\n this.registryFactory[a].priority;\n });\n }\n\n private initializeBackendsAndReturnBest():\n {name: string, asyncInit: boolean} {\n const sortedBackends = this.getSortedBackends();\n\n for (let i = 0; i < sortedBackends.length; i++) {\n const backendName = sortedBackends[i];\n const {success, asyncInit} = this.initializeBackend(backendName);\n if (asyncInit || success) {\n return {name: backendName, asyncInit};\n }\n }\n throw new Error(\n `Could not initialize any backends, all backend initializations ` +\n `failed.`);\n }\n\n moveData(backend: KernelBackend, dataId: DataId) {\n const info = this.state.tensorInfo.get(dataId);\n const srcBackend = info.backend;\n const values = this.readSync(dataId);\n const refCount = srcBackend.refCount(dataId);\n // Delete the tensor from the old backend and move it to the new\n // backend.\n srcBackend.disposeData(dataId, true);\n info.backend = backend;\n backend.move(dataId, values, info.shape, info.dtype, refCount);\n if (this.shouldCheckForMemLeaks()) {\n // Track the number of moves during a kernel execution to correctly\n // detect memory leaks.\n this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1]++;\n }\n }\n\n tidy(nameOrFn: string|ScopeFn, fn?: ScopeFn):\n T {\n let name: string = null;\n if (fn == null) {\n // Called with only 1 argument.\n if (typeof nameOrFn !== 'function') {\n throw new Error('Please provide a function to tidy()');\n }\n fn = nameOrFn;\n } else {\n // Called with 2 arguments.\n if (typeof nameOrFn !== 'string' && !(nameOrFn instanceof String)) {\n throw new Error(\n 'When calling with two arguments, the first argument ' +\n 'to tidy() must be a string');\n }\n if (typeof fn !== 'function') {\n throw new Error(\n 'When calling with two arguments, the 2nd argument ' +\n 'to tidy() must be a function');\n }\n name = nameOrFn as string;\n // TODO(nsthorat,smilkov): Do operation logging and performance\n // profiling.\n }\n let result: T;\n return this.scopedRun(\n () => this.startScope(name), () => this.endScope(result), () => {\n result = fn();\n if (result instanceof Promise) {\n console.error('Cannot return a Promise inside of tidy.');\n }\n return result;\n });\n }\n\n private scopedRun(start: () => void, end: () => void, f: () => T): T {\n start();\n try {\n const res = f();\n end();\n return res;\n } catch (ex) {\n end();\n throw ex;\n }\n }\n\n private static nextTensorId = 0;\n private nextTensorId(): number {\n return Engine.nextTensorId++;\n }\n\n private static nextVariableId = 0;\n private nextVariableId(): number {\n return Engine.nextVariableId++;\n }\n\n /**\n * This method is called instead of the public-facing tensor.clone() when\n * saving a tensor for backwards pass. It makes sure to add the clone\n * operation to the tape regardless of being called inside a kernel\n * execution.\n */\n private clone(x: Tensor): Tensor {\n const y: Tensor = ENGINE.runKernel(Identity, {x} as {} as NamedTensorMap);\n const inputs = {x};\n const grad = (dy: Tensor) => ({\n x: () => {\n const dtype = 'float32';\n const gradInputs = {x: dy};\n const attrs = {dtype};\n\n return ENGINE.runKernel(\n Cast, gradInputs as {} as NamedTensorMap,\n // tslint:disable-next-line: no-unnecessary-type-assertion\n attrs as {} as NamedAttrMap) as Tensor;\n }\n });\n const saved: Tensor[] = [];\n this.addTapeNode(this.state.activeScope.name, inputs, [y], grad, saved, {});\n return y;\n }\n\n /**\n * Execute a kernel with the given name and return the output tensor.\n *\n * @param kernelName The name of the kernel to execute.\n * @param inputs A map of input names to tensors.\n * @param attrs A map of attribute names to their values. An attribute is a\n * primitive (non-tensor) input to the kernel.\n * @param inputsToSave A list of tensors, inputs to save for the backprop\n * computation.\n * @param outputsToSave A list of booleans, specifying which output to save\n * for the backprop computation. These are booleans since the output\n * tensors are not visible to the user.\n */\n runKernel(\n kernelName: string, inputs: NamedTensorMap, attrs?: NamedAttrMap): T {\n if (this.backendName == null) {\n // backend has not been initialized yet (backend initialization is lazy\n // can be deferred until an op/ kernel is run).\n // The below getter has side effects that will try to initialize the\n // backend and set properties like this.backendName\n // tslint:disable-next-line: no-unused-expression\n this.backend;\n }\n const hasKernel = getKernel(kernelName, this.backendName) != null;\n if (!hasKernel) {\n throw new Error(`Kernel '${kernelName}' not registered for backend '${\n this.backendName}'`);\n }\n return this.runKernelFunc({kernelName, inputs, attrs});\n }\n\n private shouldCheckForMemLeaks(): boolean {\n return this.ENV.getBool('IS_TEST');\n }\n\n private checkKernelForMemLeak(\n kernelName: string, numDataIdsBefore: number,\n outInfos: TensorInfo[]): void {\n const numDataIdsAfter = this.backend.numDataIds();\n\n // Count the number of data ids associated with the result of the kernel.\n let numOutputDataIds = 0;\n outInfos.forEach(info => {\n // Complex numbers allocate 3 data ids, one for 'real', one for\n // 'imaginary', and one for the container that holds the former two.\n numOutputDataIds += (info.dtype === 'complex64' ? 3 : 1);\n });\n\n // Account for the number of moves during kernel execution. A \"data move\"\n // can happen in the middle of a kernel execution, placing a new (key,value)\n // pair in the data storage. Since data moves have net zero effect (we\n // always remove the data from the old backend), we have to cancel them out\n // when detecting memory leaks.\n const numMoves =\n this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1];\n const dataIdsLeaked =\n numDataIdsAfter - numDataIdsBefore - numOutputDataIds - numMoves;\n if (dataIdsLeaked > 0) {\n throw new Error(\n `Backend '${this.backendName}' has an internal memory leak ` +\n `(${dataIdsLeaked} data ids) after running '${kernelName}'`);\n }\n }\n\n /**\n * Internal helper method to execute a kernel Func\n *\n * Use `runKernel` to execute kernels from outside of engine.\n */\n private runKernelFunc(\n kernelParams: RegisteredKernelInvocation|\n CustomGradKernelInvocation): T {\n let outputs: Tensor[];\n let saved: Tensor[] = [];\n const isTapeOn = this.isTapeOn();\n\n const startingBytecount = this.state.numBytes;\n const startingNumTensors = this.state.numTensors;\n\n if (this.shouldCheckForMemLeaks()) {\n this.state.numDataMovesStack.push(0);\n }\n\n let kernelFunc: () => Tensor[];\n if (this.backendName == null) {\n // backend has not been initialized yet (backend initialization is lazy\n // can be deferred until an op/ kernel is run).\n // The below getter has side effects that will try to initialize the\n // backend and set properties like this.backendName\n // tslint:disable-next-line: no-unused-expression\n this.backend;\n }\n\n let out: TensorInfo|TensorInfo[];\n\n const kernelOrScopeName = isRegisteredKernelInvocation(kernelParams) ?\n kernelParams.kernelName :\n this.state.activeScope != null ? this.state.activeScope.name : '';\n\n // Create the kernelFunc from either a registered kernel OR passed in\n // forward/backward functions (used by custom grad). In this context a\n // kernelFunc wraps a kernel implementation with some bookkeeping.\n\n if (isRegisteredKernelInvocation(kernelParams)) {\n const {kernelName, inputs, attrs} = kernelParams;\n if (this.backendName == null) {\n // backend has not been initialized yet (backend initialization is lazy\n // can be deferred until an op/ kernel is run).\n // The below getter has side effects that will try to initialize the\n // backend and set properties like this.backendName\n // tslint:disable-next-line: no-unused-expression\n this.backend;\n }\n const kernel = getKernel(kernelName, this.backendName);\n util.assert(\n kernel != null,\n () => `Cannot find registered kernel '${kernelName}' for backend '${\n this.backendName}'`);\n\n kernelFunc = () => {\n const numDataIdsBefore = this.backend.numDataIds();\n out = kernel.kernelFunc({inputs, attrs, backend: this.backend});\n const outInfos = Array.isArray(out) ? out : [out];\n if (this.shouldCheckForMemLeaks()) {\n this.checkKernelForMemLeak(kernelName, numDataIdsBefore, outInfos);\n }\n\n const outTensors = outInfos.map((outInfo: TensorInfo|Tensor) => {\n // todo (yassogba) remove this option (Tensor) when node backend\n // methods have been modularized and they all return tensorInfo.\n // TensorInfos do not have a rank attribute.\n if ((outInfo as Tensor).rank != null) {\n return outInfo as Tensor;\n }\n const {dataId, shape, dtype} = outInfo as TensorInfo;\n return this.makeTensorFromDataId(dataId, shape, dtype);\n });\n\n // Save any required inputs and outputs.\n\n // Do not save unless we are recording to the tape. Otherwise it would\n // cause a mem leak since there would be no backprop for these tensors\n // (which would otherwise dispose them).\n if (isTapeOn) {\n const tensorsToSave =\n this.getTensorsForGradient(kernelName, inputs, outTensors);\n saved = this.saveTensorsForBackwardMode(tensorsToSave);\n }\n return outTensors;\n };\n } else {\n const {forwardFunc} = kernelParams;\n // Running a customGrad op.\n const saveFunc: GradSaveFunc = (tensors) => {\n // Do not save unless we are recording to the tape. Otherwise it would\n // cause a mem leak since we would never run backprop, which disposes\n // the kept tensors.\n if (!isTapeOn) {\n return;\n }\n saved = tensors.map(tensor => this.keep(this.clone(tensor)));\n };\n\n kernelFunc = () => {\n const numDataIdsBefore = this.backend.numDataIds();\n out = this.tidy(() => forwardFunc(this.backend, saveFunc));\n const outs = (Array.isArray(out) ? out : [out]) as Tensor[];\n if (this.shouldCheckForMemLeaks()) {\n // Scope name is used to print a more helpful error message if needed.\n this.checkKernelForMemLeak(kernelOrScopeName, numDataIdsBefore, outs);\n }\n return outs;\n };\n }\n\n //\n // Run the kernelFunc. Optionally profiling it.\n //\n const {inputs, attrs} = kernelParams;\n const backwardsFunc = isRegisteredKernelInvocation(kernelParams) ?\n null :\n kernelParams.backwardsFunc;\n\n let kernelProfile: KernelProfile;\n this.scopedRun(\n // Stop recording to a tape when running a kernel.\n () => this.state.kernelDepth++, () => this.state.kernelDepth--, () => {\n if (!this.ENV.getBool('DEBUG') && !this.state.profiling) {\n outputs = kernelFunc();\n } else {\n kernelProfile = this.profiler.profileKernel(\n kernelOrScopeName, inputs, () => kernelFunc());\n if (this.ENV.getBool('DEBUG')) {\n this.profiler.logKernelProfile(kernelProfile);\n }\n outputs = kernelProfile.outputs;\n }\n });\n\n if (isTapeOn) {\n this.addTapeNode(\n kernelOrScopeName, inputs, outputs, backwardsFunc, saved, attrs);\n }\n\n if (this.state.profiling) {\n this.state.activeProfile.kernels.push({\n name: kernelOrScopeName,\n bytesAdded: this.state.numBytes - startingBytecount,\n totalBytesSnapshot: this.state.numBytes,\n tensorsAdded: this.state.numTensors - startingNumTensors,\n totalTensorsSnapshot: this.state.numTensors,\n inputShapes: Object.keys(inputs).map(\n key => inputs[key] != null ? inputs[key].shape : null),\n outputShapes: outputs.map(item => item.shape),\n kernelTimeMs: kernelProfile.timeMs,\n extraInfo: kernelProfile.extraInfo\n });\n }\n return (Array.isArray(out) ? outputs : outputs[0]) as T;\n }\n\n /**\n * Saves tensors used in forward mode for use in backward mode.\n *\n * @param tensors the list of tensors to save.\n */\n private saveTensorsForBackwardMode(tensors: Tensor[]): Tensor[] {\n const saved = tensors.map(tensor => this.keep(this.clone(tensor)));\n return saved;\n }\n\n /**\n * Returns a list of tensors to save for a given gradient calculation.\n *\n * @param kernelName name of kernel to look up gradient for.\n * @param inputs a map of input tensors.\n * @param outputs an array of output tensors from forward mode of kernel.\n */\n private getTensorsForGradient(\n kernelName: string, inputs: NamedTensorMap,\n outputs: Tensor[]): Tensor[]|null {\n const gradConfig = getGradient(kernelName);\n if (gradConfig != null) {\n const inputsToSave: string[] = gradConfig.inputsToSave || [];\n const outputsToSave: boolean[] = gradConfig.outputsToSave || [];\n\n // If saveAllInputs is true, all inputs will be saved. Otherwise, inputs\n // specified in inputsToSave will be saved.\n let inputTensorsToSave: Tensor[];\n if (gradConfig.saveAllInputs) {\n util.assert(\n Array.isArray(inputs),\n () => 'saveAllInputs is true, expected inputs to be an array.');\n\n inputTensorsToSave = Object.keys(inputs).map((key) => inputs[key]);\n } else {\n inputTensorsToSave = inputsToSave.map((inputName) => inputs[inputName]);\n }\n\n const outputTensorsToSave: Tensor[] =\n outputs.filter((_, i) => outputsToSave[i]);\n\n return inputTensorsToSave.concat(outputTensorsToSave);\n }\n // We return an empty list rather than throw an error because the kernel we\n // are looking up may not actually be relevant to backproping through the\n // overall function\n //\n // See 'does not error if irrelevant (pruned) ops are missing grads' test\n // in gradients_test.ts for an example.\n return [];\n }\n\n /**\n * Internal method used by public APIs for tensor creation. Makes a new\n * tensor with the provided shape, dtype and values. It always\n * creates a new data id and writes the values to the underlying backend.\n */\n makeTensor(\n values: DataValues, shape: number[], dtype: DataType,\n backend?: KernelBackend): Tensor {\n if (values == null) {\n throw new Error('Values passed to engine.makeTensor() are null');\n }\n dtype = dtype || 'float32';\n backend = backend || this.backend;\n let backendVals = values as BackendValues;\n if (dtype === 'string' && util.isString(values[0])) {\n backendVals = (values as string[]).map(d => util.encodeString(d));\n }\n const dataId = backend.write(backendVals, shape, dtype);\n const t = new Tensor(shape, dtype, dataId, this.nextTensorId());\n this.trackTensor(t, backend);\n\n // Count bytes for string tensors.\n if (dtype === 'string') {\n const info = this.state.tensorInfo.get(dataId);\n const newBytes = bytesFromStringArray(backendVals as Uint8Array[]);\n this.state.numBytes += newBytes - info.bytes;\n info.bytes = newBytes;\n }\n return t;\n }\n\n /**\n * Internal method used by backends. Makes a new tensor\n * that is a wrapper around an existing data id. It doesn't create\n * a new data id, only increments the ref count used in memory tracking.\n */\n makeTensorFromDataId(\n dataId: DataId, shape: number[], dtype: DataType,\n backend?: KernelBackend): Tensor {\n dtype = dtype || 'float32';\n const t = new Tensor(shape, dtype, dataId, this.nextTensorId());\n this.trackTensor(t, backend);\n return t;\n }\n\n makeVariable(\n initialValue: Tensor, trainable = true, name?: string,\n dtype?: DataType): Variable {\n name = name || this.nextVariableId().toString();\n if (dtype != null && dtype !== initialValue.dtype) {\n initialValue = initialValue.cast(dtype);\n }\n const v = new Variable(initialValue, trainable, name, this.nextTensorId());\n if (this.state.registeredVariables[v.name] != null) {\n throw new Error(`Variable with name ${v.name} was already registered`);\n }\n this.state.registeredVariables[v.name] = v;\n this.incRef(v, this.backend);\n return v;\n }\n\n trackTensor(a: Tensor, backend: KernelBackend): void {\n this.state.numTensors++;\n if (a.dtype === 'string') {\n this.state.numStringTensors++;\n }\n // Bytes for complex numbers are counted by their components. Bytes for\n // string tensors are counted when writing values.\n let bytes = 0;\n if (a.dtype !== 'complex64' && a.dtype !== 'string') {\n bytes = a.size * util.bytesPerElement(a.dtype);\n }\n this.state.numBytes += bytes;\n\n if (!this.state.tensorInfo.has(a.dataId)) {\n this.state.numDataBuffers++;\n this.state.tensorInfo.set(a.dataId, {\n backend: backend || this.backend,\n dtype: a.dtype,\n shape: a.shape,\n bytes\n });\n }\n\n if (!(a instanceof Variable)) {\n this.track(a);\n }\n }\n\n // Track the tensor by dataId and increase the refCount for the dataId in the\n // backend.\n // TODO(pyu10055): This is currently used by makeVariable method, to increase\n // refCount on the backend for the dataId. It can potentially be replaced with\n // Identity op indead of calling backend directly.\n incRef(a: Tensor, backend: KernelBackend): void {\n this.trackTensor(a, backend);\n this.backend.incRef(a.dataId);\n }\n\n removeDataId(dataId: DataId, backend: KernelBackend) {\n if (this.state.tensorInfo.has(dataId) &&\n this.state.tensorInfo.get(dataId).backend === backend) {\n this.state.tensorInfo.delete(dataId);\n this.state.numDataBuffers--;\n }\n }\n disposeTensor(a: Tensor): void {\n if (!this.state.tensorInfo.has(a.dataId)) {\n return;\n }\n const info = this.state.tensorInfo.get(a.dataId);\n\n this.state.numTensors--;\n if (a.dtype === 'string') {\n this.state.numStringTensors--;\n this.state.numBytes -= info.bytes;\n }\n // Don't count bytes for complex numbers as they are counted by their\n // components.\n if (a.dtype !== 'complex64' && a.dtype !== 'string') {\n const bytes = a.size * util.bytesPerElement(a.dtype);\n this.state.numBytes -= bytes;\n }\n\n // Remove the reference to dataId if backend dispose the data successfully\n if (info.backend.disposeData(a.dataId)) {\n this.removeDataId(a.dataId, info.backend);\n }\n\n // TODO(nsthorat): Construct an error and save the stack trace for\n // debugging when in debug mode. Creating a stack trace is too expensive\n // to do unconditionally.\n }\n\n disposeVariables(): void {\n for (const varName in this.state.registeredVariables) {\n const v = this.state.registeredVariables[varName];\n this.disposeVariable(v);\n }\n }\n\n disposeVariable(v: Variable): void {\n this.disposeTensor(v);\n if (this.state.registeredVariables[v.name] != null) {\n delete this.state.registeredVariables[v.name];\n }\n }\n\n memory(): MemoryInfo {\n const info = this.backend.memory() as MemoryInfo;\n info.numTensors = this.state.numTensors;\n info.numDataBuffers = this.state.numDataBuffers;\n info.numBytes = this.state.numBytes;\n if (this.state.numStringTensors > 0) {\n info.unreliable = true;\n if (info.reasons == null) {\n info.reasons = [];\n }\n info.reasons.push(\n 'Memory usage by string tensors is approximate ' +\n '(2 bytes per character)');\n }\n return info;\n }\n\n async profile(query: () => (TensorContainer | Promise)):\n Promise {\n this.state.profiling = true;\n\n const startBytes = this.state.numBytes;\n const startNumTensors = this.state.numTensors;\n\n this.state.activeProfile.kernels = [];\n this.state.activeProfile.result = await query();\n\n this.state.profiling = false;\n\n this.state.activeProfile.peakBytes = Math.max(\n ...this.state.activeProfile.kernels.map(d => d.totalBytesSnapshot));\n this.state.activeProfile.newBytes = this.state.numBytes - startBytes;\n this.state.activeProfile.newTensors =\n this.state.numTensors - startNumTensors;\n for (const kernel of this.state.activeProfile.kernels) {\n kernel.kernelTimeMs = await kernel.kernelTimeMs;\n kernel.extraInfo = await kernel.extraInfo;\n }\n return this.state.activeProfile;\n }\n\n isTapeOn(): boolean {\n return this.state.gradientDepth > 0 && this.state.kernelDepth === 0;\n }\n\n private addTapeNode(\n kernelName: string, inputs: NamedTensorMap, outputs: Tensor[],\n gradientsFunc: GradFunc, saved: Tensor[], attrs: NamedAttrMap): void {\n const tapeNode: TapeNode =\n {id: this.state.nextTapeNodeId++, kernelName, inputs, outputs, saved};\n\n const gradConfig = getGradient(kernelName);\n if (gradConfig != null) {\n gradientsFunc = gradConfig.gradFunc;\n }\n if (gradientsFunc != null) {\n tapeNode.gradient = (dys: Tensor[]) => {\n // TODO(smilkov): To optimize back-prop, pass dys that are not used in\n // the backprop graph to the user as null instead of zeros\n dys = dys.map((dy, i) => {\n if (dy == null) {\n const output = outputs[i];\n const vals = util.makeZerosTypedArray(output.size, output.dtype);\n return this.makeTensor(vals, output.shape, output.dtype);\n }\n return dy;\n });\n // Grad functions of ops with single outputs expect a dy, while ops\n // with multiple outputs expect dys (array of dy).\n return gradientsFunc(dys.length > 1 ? dys : dys[0], saved, attrs);\n };\n }\n this.state.activeTape.push(tapeNode);\n }\n\n keep(result: T): T {\n result.kept = true;\n return result;\n }\n\n private startTape() {\n if (this.state.gradientDepth === 0) {\n this.state.activeTape = [];\n }\n this.state.gradientDepth++;\n }\n\n private endTape() {\n this.state.gradientDepth--;\n }\n\n /**\n * Start a scope. Use this with endScope() to achieve the same functionality\n * as scope() without the need for a function closure.\n */\n startScope(name?: string) {\n const scopeInfo: ScopeState = {\n track: [],\n name: 'unnamed scope',\n id: this.state.nextScopeId++\n };\n if (name) {\n scopeInfo.name = name;\n }\n this.state.scopeStack.push(scopeInfo);\n this.state.activeScope = scopeInfo;\n }\n\n /**\n * End a scope. Use this with startScope() to achieve the same functionality\n * as scope() without the need for a function closure.\n */\n endScope(result?: TensorContainer) {\n const tensorsToTrackInParent = getTensorsInContainer(result);\n const tensorsToTrackInParentSet =\n new Set(tensorsToTrackInParent.map(t => t.id));\n\n // Dispose the arrays tracked in this scope.\n for (let i = 0; i < this.state.activeScope.track.length; i++) {\n const tensor = this.state.activeScope.track[i];\n if (!tensor.kept && !tensorsToTrackInParentSet.has(tensor.id)) {\n tensor.dispose();\n }\n }\n\n const oldScope = this.state.scopeStack.pop();\n this.state.activeScope = this.state.scopeStack.length === 0 ?\n null :\n this.state.scopeStack[this.state.scopeStack.length - 1];\n\n // Track the current result in the parent scope.\n tensorsToTrackInParent.forEach(tensor => {\n // Only track the tensor if was allocated in the inner scope and is not\n // globally kept.\n if (!tensor.kept && tensor.scopeId === oldScope.id) {\n this.track(tensor);\n }\n });\n }\n\n /**\n * Returns gradients of `f` with respect to each of the `xs`. The gradients\n * returned are of the same length as `xs`, but some might be null if `f`\n * was not a function of that `x`. It also takes optional dy to multiply the\n * gradient, which defaults to `1`.\n */\n gradients(\n f: () => T, xs: Tensor[], dy?: T,\n allowNoGradients = false): {value: T, grads: Tensor[]} {\n util.assert(\n xs.length > 0, () => 'gradients() received an empty list of xs.');\n if (dy != null && dy.dtype !== 'float32') {\n throw new Error(`dy must have 'float32' dtype, but has '${dy.dtype}'`);\n }\n\n const y = this.scopedRun(\n () => this.startTape(), () => this.endTape(),\n () => this.tidy('forward', f));\n\n util.assert(\n y instanceof Tensor,\n () => 'The result y returned by f() must be a tensor.');\n // Filter out the nodes that don't connect x => y.\n const filteredTape = getFilteredNodesXToY(this.state.activeTape, xs, y);\n if (!allowNoGradients && filteredTape.length === 0 && xs.length > 0) {\n throw new Error(\n 'Cannot compute gradient of y=f(x) with respect to x. Make sure ' +\n 'that the f you passed encloses all operations that lead from x ' +\n 'to y.');\n }\n\n return this.tidy('backward', () => {\n const accumulatedGradientMap: {[tensorId: number]: Tensor} = {};\n accumulatedGradientMap[y.id] = (dy == null) ? ones(y.shape) : dy;\n\n // Backprop gradients through the filtered nodes.\n backpropagateGradients(\n accumulatedGradientMap, filteredTape,\n // Pass the tidy function to avoid circular dep with `tape.ts`.\n f => this.tidy(f as ScopeFn),\n // Pass an add function to avoide a circular dep with `tape.ts`.\n add);\n const grads = xs.map(x => accumulatedGradientMap[x.id]);\n\n if (this.state.gradientDepth === 0) {\n // This means that we are not computing higher-order gradients\n // and can clean up the tape.\n this.state.activeTape.forEach(node => {\n for (const tensor of node.saved) {\n tensor.dispose();\n }\n });\n this.state.activeTape = null;\n }\n return {value: y, grads};\n });\n }\n\n customGrad(f: CustomGradientFunc):\n (...args: Array) => T {\n util.assert(\n util.isFunction(f),\n () => 'The f passed in customGrad(f) must be a function.');\n return (...inputs: Tensor[]): T => {\n util.assert(\n inputs.every(t => t instanceof Tensor),\n () => 'The args passed in customGrad(f)(x1, x2,...) must all be ' +\n 'tensors');\n\n let res: {\n value: T,\n gradFunc: (dy: T, saved: Tensor[]) => Tensor | Tensor[],\n };\n const inputMap: NamedTensorMap = {};\n inputs.forEach((input, i) => {\n inputMap[i] = input;\n });\n\n const forwardFunc: ForwardFunc = (_, save) => {\n res = f(...[...inputs, save]);\n util.assert(\n res.value instanceof Tensor,\n () => 'The function f passed in customGrad(f) must return an ' +\n 'object where `obj.value` is a tensor');\n util.assert(\n util.isFunction(res.gradFunc),\n () => 'The function f passed in customGrad(f) must return an ' +\n 'object where `obj.gradFunc` is a function.');\n return res.value;\n };\n\n const backwardsFunc = (dy: T, saved: Tensor[]) => {\n const gradRes = res.gradFunc(dy, saved);\n const grads: Tensor[] = Array.isArray(gradRes) ? gradRes : [gradRes];\n util.assert(\n grads.length === inputs.length,\n () => 'The function f passed in customGrad(f) must return an ' +\n 'object where `obj.gradFunc` is a function that returns ' +\n 'the same number of tensors as inputs passed to f(...).');\n util.assert(\n grads.every(t => t instanceof Tensor),\n () => 'The function f passed in customGrad(f) must return an ' +\n 'object where `obj.gradFunc` is a function that returns ' +\n 'a list of only tensors.');\n const gradMap: {[key: string]: () => Tensor} = {};\n grads.forEach((grad, i) => {\n gradMap[i] = () => grad;\n });\n return gradMap;\n };\n\n return this.runKernelFunc({\n forwardFunc,\n backwardsFunc,\n inputs: inputMap,\n });\n };\n }\n\n readSync(dataId: DataId): BackendValues {\n // Route the read to the correct backend.\n const info = this.state.tensorInfo.get(dataId);\n return info.backend.readSync(dataId);\n }\n read(dataId: DataId): Promise {\n // Route the read to the correct backend.\n const info = this.state.tensorInfo.get(dataId);\n return info.backend.read(dataId);\n }\n\n async time(query: () => void): Promise {\n const start = now();\n const timingInfo = await this.backend.time(query) as TimingInfo;\n timingInfo.wallMs = now() - start;\n return timingInfo;\n }\n\n /**\n * Tracks a Tensor in the current scope to be automatically cleaned up\n * when the current scope ends, and returns the value.\n *\n * @param result The Tensor to track in the current scope.\n */\n private track(result: T): T {\n if (this.state.activeScope != null) {\n result.scopeId = this.state.activeScope.id;\n this.state.activeScope.track.push(result);\n }\n\n return result;\n }\n\n get registeredVariables(): NamedVariableMap {\n return this.state.registeredVariables;\n }\n\n /**\n * Resets the engine state. Removes all backends but does not remove\n * registered backend factories.\n */\n reset(): void {\n // Make any pending promise obsolete.\n this.pendingBackendInitId++;\n\n this.state.dispose();\n this.ENV.reset();\n this.state = new EngineState();\n\n for (const backendName in this.registry) {\n this.disposeRegisteredKernels(backendName);\n this.registry[backendName].dispose();\n delete this.registry[backendName];\n }\n this.backendName = null;\n this.backendInstance = null;\n this.pendingBackendInit = null;\n }\n}\n\nfunction ones(shape: number[]): Tensor {\n const values = makeOnesTypedArray(sizeFromShape(shape), 'float32');\n return ENGINE.makeTensor(values, shape, 'float32');\n}\n\nexport function getOrMakeEngine(): Engine {\n const ns = getGlobalNamespace() as {} as {_tfengine: Engine};\n if (ns._tfengine == null) {\n const environment = new Environment(ns);\n ns._tfengine = new Engine(environment);\n }\n setEnvironmentGlobal(ns._tfengine.ENV);\n\n // Tell the current tensor interface that the global engine is responsible\n // for tracking.\n setTensorTracker(() => ns._tfengine);\n return ns._tfengine;\n}\n\nexport const ENGINE = getOrMakeEngine();\n\n/**\n * A implementation of the add op for use within engine and tape.\n *\n * This allows us to avoid a circular dependency between add.ts and engine.\n * It is exported to be available in tape tests.\n */\nexport function add(a: Tensor, b: Tensor): Tensor {\n // We duplicate Add here to avoid a circular dependency with add.ts.\n const inputs = {a, b};\n return ENGINE.runKernel(Add, inputs as {} as NamedTensorMap);\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// tslint:disable-next-line:no-any\nfunction _isNavigatorDefined(): boolean {\n return typeof navigator !== 'undefined' && navigator != null;\n}\n\nlet isMobileMockValue: boolean | undefined;\n\nexport function mockIsMobile(value: boolean | undefined) {\n isMobileMockValue = value;\n}\n\nexport function isMobile(nav?: Navigator): boolean {\n if (isMobileMockValue !== undefined) {\n return isMobileMockValue;\n }\n if (nav || _isNavigatorDefined()) {\n if (!nav) {\n nav = navigator;\n }\n if (nav.product === 'ReactNative') {\n return true;\n }\n\n // tslint:disable-next-line:no-any\n const a = nav.userAgent || nav.vendor ||\n (typeof window !== 'undefined' ? (window as any).opera : '');\n // Use `navigator.userAgentData.mobile` as fallback.\n if (!a) {\n // tslint:disable-next-line:no-any\n const navAny = nav as any;\n return navAny.userAgentData && navAny.userAgentData.mobile;\n }\n // tslint:disable-next-line:max-line-length\n 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\n .test(a) ||\n // tslint:disable-next-line:max-line-length\n /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\n .test(a.substr(0, 4));\n }\n return false;\n}\n\nexport function isBrowser(): boolean {\n return (typeof window !== 'undefined' && window.document != null) ||\n //@ts-ignore\n (typeof WorkerGlobalScope !== 'undefined');\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport './engine';\n\nimport * as device_util from './device_util';\nimport {env} from './environment';\n\nconst ENV = env();\n\n/**\n * This file contains environment-related flag registrations.\n */\n\n/** Whether to enable debug mode. */\nENV.registerFlag('DEBUG', () => false, debugValue => {\n if (debugValue) {\n console.warn(\n 'Debugging mode is ON. The output of every math call will ' +\n 'be downloaded to CPU and checked for NaNs. ' +\n 'This significantly impacts performance.');\n }\n});\n\n/** Whether we are in a browser (as versus, say, node.js) environment. */\nENV.registerFlag('IS_BROWSER', () => device_util.isBrowser());\n\n/** Whether we are in a browser (as versus, say, node.js) environment. */\nENV.registerFlag(\n 'IS_NODE',\n () => (typeof process !== 'undefined') &&\n (typeof process.versions !== 'undefined') &&\n (typeof process.versions.node !== 'undefined'));\n\n/** Whether this browser is Chrome. */\nENV.registerFlag(\n 'IS_CHROME',\n () => typeof navigator !== 'undefined' && navigator != null &&\n navigator.userAgent != null && /Chrome/.test(navigator.userAgent) &&\n /Google Inc/.test(navigator.vendor));\n\n/**\n * True when the environment is \"production\" where we disable safety checks\n * to gain performance.\n */\nENV.registerFlag('PROD', () => false);\n\n/**\n * Whether to do sanity checks when inferring a shape from user-provided\n * values, used when creating a new tensor.\n */\nENV.registerFlag(\n 'TENSORLIKE_CHECK_SHAPE_CONSISTENCY', () => ENV.getBool('DEBUG'));\n\n/** Whether deprecation warnings are enabled. */\nENV.registerFlag('DEPRECATION_WARNINGS_ENABLED', () => true);\n\n/** True if running unit tests. */\nENV.registerFlag('IS_TEST', () => false);\n\n/** Whether to check computation result for errors. */\nENV.registerFlag('CHECK_COMPUTATION_FOR_ERRORS', () => true);\n\n/** Whether the backend needs to wrap input to imageBitmap. */\nENV.registerFlag('WRAP_TO_IMAGEBITMAP', () => false);\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from './engine';\nimport {env} from './environment';\nimport {Tensor} from './tensor';\nimport {DataType, TensorLike} from './types';\nimport {assert, flatten, inferDtype, isTypedArray, toTypedArray} from './util';\n\nexport function inferShape(val: TensorLike, dtype?: DataType): number[] {\n let firstElem: typeof val = val;\n\n if (isTypedArray(val)) {\n return dtype === 'string' ? [] : [val.length];\n }\n if (!Array.isArray(val)) {\n return []; // Scalar.\n }\n const shape: number[] = [];\n\n while (Array.isArray(firstElem) ||\n isTypedArray(firstElem) && dtype !== 'string') {\n shape.push(firstElem.length);\n firstElem = firstElem[0];\n }\n if (Array.isArray(val) &&\n env().getBool('TENSORLIKE_CHECK_SHAPE_CONSISTENCY')) {\n deepAssertShapeConsistency(val, shape, []);\n }\n\n return shape;\n}\n\nfunction deepAssertShapeConsistency(\n val: TensorLike, shape: number[], indices: number[]) {\n indices = indices || [];\n if (!(Array.isArray(val)) && !isTypedArray(val)) {\n assert(\n shape.length === 0,\n () => `Element arr[${indices.join('][')}] is a primitive, ` +\n `but should be an array/TypedArray of ${shape[0]} elements`);\n return;\n }\n assert(\n shape.length > 0,\n () => `Element arr[${indices.join('][')}] should be a primitive, ` +\n `but is an array of ${val.length} elements`);\n assert(\n val.length === shape[0],\n () => `Element arr[${indices.join('][')}] should have ${shape[0]} ` +\n `elements, but has ${val.length} elements`);\n const subShape = shape.slice(1);\n for (let i = 0; i < val.length; ++i) {\n deepAssertShapeConsistency(val[i], subShape, indices.concat(i));\n }\n}\n\nfunction assertDtype(\n expectedDtype: DataType|'numeric'|'string_or_numeric',\n actualDType: DataType, argName: string, functionName: string) {\n if (expectedDtype === 'string_or_numeric') {\n return;\n }\n if (expectedDtype == null) {\n throw new Error(`Expected dtype cannot be null.`);\n }\n if (expectedDtype !== 'numeric' && expectedDtype !== actualDType ||\n expectedDtype === 'numeric' && actualDType === 'string') {\n throw new Error(\n `Argument '${argName}' passed to '${functionName}' must ` +\n `be ${expectedDtype} tensor, but got ${actualDType} tensor`);\n }\n}\n\nexport function convertToTensor(\n x: T|TensorLike, argName: string, functionName: string,\n parseAsDtype: DataType|'numeric'|'string_or_numeric' = 'numeric'): T {\n if (x instanceof Tensor) {\n assertDtype(parseAsDtype, x.dtype, argName, functionName);\n return x;\n }\n let inferredDtype = inferDtype(x);\n // If the user expects a bool/int/float, use that info to update the\n // inferredDtype when it is not a string.\n if (inferredDtype !== 'string' &&\n ['bool', 'int32', 'float32'].indexOf(parseAsDtype) >= 0) {\n inferredDtype = parseAsDtype as DataType;\n }\n assertDtype(parseAsDtype, inferredDtype, argName, functionName);\n\n if ((x == null) ||\n (!isTypedArray(x) && !Array.isArray(x) && typeof x !== 'number' &&\n typeof x !== 'boolean' && typeof x !== 'string')) {\n const type = x == null ? 'null' : (x as {}).constructor.name;\n throw new Error(\n `Argument '${argName}' passed to '${functionName}' must be a ` +\n `Tensor or TensorLike, but got '${type}'`);\n }\n const inferredShape = inferShape(x, inferredDtype);\n if (!isTypedArray(x) && !Array.isArray(x)) {\n x = [x] as number[];\n }\n const skipTypedArray = true;\n const values = inferredDtype !== 'string' ?\n toTypedArray(x, inferredDtype as DataType) :\n flatten(x as string[], [], skipTypedArray) as string[];\n return ENGINE.makeTensor(values, inferredShape, inferredDtype) as T;\n}\n\nexport function convertToTensorArray(\n arg: Array, argName: string, functionName: string,\n parseAsDtype: DataType|'numeric'|'string_or_numeric' = 'numeric'): T[] {\n if (!Array.isArray(arg)) {\n throw new Error(\n `Argument ${argName} passed to ${functionName} must be a ` +\n '`Tensor[]` or `TensorLike[]`');\n }\n const tensors = arg as T[];\n return tensors.map(\n (t, i) =>\n convertToTensor(t, `${argName}[${i}]`, functionName, parseAsDtype));\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {isPromise} from '../util';\n\nexport const OP_SCOPE_SUFFIX = '__op';\n\n/**\n * Used for wrapping functions that perform math operations on\n * Tensors. The function will be wrapped in a named scope that cleans all\n * memory usage after the function is done.\n */\nexport function op(f: {[name: string]: T}): T {\n const keys = Object.keys(f);\n if (keys.length !== 1) {\n throw new Error(\n `Please provide an object with a single key ` +\n `(operation name) mapping to a function. Got an object with ` +\n `${keys.length} keys.`);\n }\n\n let opName = keys[0];\n const fn = f[opName];\n\n // Strip the underscore from the end of the function name.\n if (opName.endsWith('_')) {\n opName = opName.substring(0, opName.length - 1);\n }\n\n // add an __op suffix to distinguish ops from kernels in tf.profile\n opName = opName + OP_SCOPE_SUFFIX;\n\n // tslint:disable-next-line:no-any\n const f2 = (...args: any[]) => {\n ENGINE.startScope(opName);\n try {\n const result = fn(...args);\n if (isPromise(result)) {\n console.error('Cannot return a Promise inside of tidy.');\n }\n ENGINE.endScope(result);\n return result;\n } catch (ex) {\n ENGINE.endScope(null);\n throw ex;\n }\n };\n Object.defineProperty(f2, 'name', {value: opName, configurable: true});\n\n // tslint:disable-next-line:no-any\n return f2 as any as T;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Complex, ComplexInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Converts two real numbers to a complex number.\n *\n * Given a tensor `real` representing the real part of a complex number, and a\n * tensor `imag` representing the imaginary part of a complex number, this\n * operation returns complex numbers elementwise of the form [r0, i0, r1, i1],\n * where r represents the real part and i represents the imag part.\n *\n * The input tensors real and imag must have the same shape.\n *\n * ```js\n * const real = tf.tensor1d([2.25, 3.25]);\n * const imag = tf.tensor1d([4.75, 5.75]);\n * const complex = tf.complex(real, imag);\n *\n * complex.print();\n * ```\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction complex_(real: T|TensorLike, imag: T|TensorLike): T {\n const $real = convertToTensor(real, 'real', 'complex');\n const $imag = convertToTensor(imag, 'imag', 'complex');\n util.assertShapesMatch(\n $real.shape, $imag.shape,\n `real and imag shapes, ${$real.shape} and ${$imag.shape}, ` +\n `must match in call to tf.complex().`);\n\n const inputs: ComplexInputs = {real: $real, imag: $imag};\n return ENGINE.runKernel(Complex, inputs as {} as NamedTensorMap);\n}\n\nexport const complex = op({complex_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tensor} from '../tensor';\nimport {TensorLike, TypedArray} from '../types';\nimport {DataType} from '../types';\nimport {assert, assertNonNegativeIntegerDimensions, flatten, inferDtype, isTypedArray, sizeFromShape, toTypedArray} from '../util';\n\n/** This is shared code across all tensor creation methods. */\nexport function makeTensor(\n values: TensorLike, shape: number[], inferredShape: number[],\n dtype?: DataType): Tensor {\n if (dtype == null) {\n dtype = inferDtype(values);\n }\n if (dtype === 'complex64') {\n throw new Error(\n `Cannot construct a complex64 tensor directly. ` +\n `Please use tf.complex(real, imag).`);\n }\n if (!isTypedArray(values) && !Array.isArray(values) &&\n typeof values !== 'number' && typeof values !== 'boolean' &&\n typeof values !== 'string') {\n throw new Error(\n 'values passed to tensor(values) must be a number/boolean/string or ' +\n 'an array of numbers/booleans/strings, or a TypedArray');\n }\n if (shape != null) {\n assertNonNegativeIntegerDimensions(shape);\n\n const providedSize = sizeFromShape(shape);\n const inferredSize = sizeFromShape(inferredShape);\n assert(\n providedSize === inferredSize,\n () =>\n `Based on the provided shape, [${shape}], the tensor should have ` +\n `${providedSize} values but has ${inferredSize}`);\n\n for (let i = 0; i < inferredShape.length; ++i) {\n const inferred = inferredShape[i];\n const flatDimsDontMatch = i === inferredShape.length - 1 ?\n inferred !== sizeFromShape(shape.slice(i)) :\n true;\n assert(\n inferredShape[i] === shape[i] || !flatDimsDontMatch,\n () => `Error creating a new Tensor. Inferred shape ` +\n `(${inferredShape}) does not match the provided ` +\n `shape (${shape}). `);\n }\n }\n\n if (!isTypedArray(values) && !Array.isArray(values)) {\n values = [values] as number[];\n }\n\n shape = shape || inferredShape;\n values = dtype !== 'string' ?\n toTypedArray(values, dtype) :\n flatten(values as string[], [], true) as string[];\n return ENGINE.makeTensor(values as TypedArray, shape, dtype);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {inferShape} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {DataType, Rank, ShapeMap} from '../types';\n\nimport {makeTensor} from './tensor_ops_util';\n\n/**\n * Creates a `tf.Tensor` with the provided values, shape and dtype.\n *\n * ```js\n * // Pass an array of values to create a vector.\n * tf.tensor([1, 2, 3, 4]).print();\n * ```\n *\n * ```js\n * // Pass a nested array of values to make a matrix or a higher\n * // dimensional tensor.\n * tf.tensor([[1, 2], [3, 4]]).print();\n * ```\n *\n * ```js\n * // Pass a flat array and specify a shape yourself.\n * tf.tensor([1, 2, 3, 4], [2, 2]).print();\n * ```\n *\n * @param values The values of the tensor. Can be nested array of numbers,\n * or a flat array, or a `TypedArray`. If the values are strings,\n * they will be encoded as utf-8 and kept as `Uint8Array[]`.\n * @param shape The shape of the tensor. Optional. If not provided,\n * it is inferred from `values`.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function tensor(\n values: TensorLike, shape?: ShapeMap[R], dtype?: DataType): Tensor {\n const inferredShape = inferShape(values, dtype);\n return makeTensor(values, shape, inferredShape, dtype) as Tensor;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/* Type definitions for exporting and importing of models. */\n\n/**\n * A map from Tensor dtype to number of bytes per element of the Tensor.\n */\nexport const DTYPE_VALUE_SIZE_MAP: {[dtype: string]: number} = {\n 'float32': 4,\n 'float16': 2,\n 'int32': 4,\n 'uint16': 2,\n 'uint8': 1,\n 'bool': 1,\n 'complex64': 8\n};\n\n/**\n * A weight manifest.\n *\n * The weight manifest consists of an ordered list of weight-manifest groups.\n * Each weight-manifest group (\"group\" for short hereafter) consists of a\n * number of weight values stored in a number of paths.\n * See the documentation of `WeightManifestGroupConfig` below for more details.\n */\nexport declare type WeightsManifestConfig = WeightsManifestGroupConfig[];\n\n/**\n * A weight-manifest group.\n *\n * Consists of an ordered list of weight values encoded in binary format,\n * stored in an ordered list of paths.\n */\nexport declare interface WeightsManifestGroupConfig {\n /**\n * An ordered list of paths.\n *\n * Paths are intentionally abstract in order to be general. For example, they\n * can be relative URL paths or relative paths on the file system.\n */\n paths: string[];\n\n /**\n * Specifications of the weights stored in the paths.\n */\n weights: WeightsManifestEntry[];\n}\n\n/**\n * Group to which the weight belongs.\n *\n * - 'optimizer': Weight from a stateful optimizer.\n */\nexport type WeightGroup = 'model'|'optimizer';\n\n/**\n * An entry in the weight manifest.\n *\n * The entry contains specification of a weight.\n */\nexport declare interface WeightsManifestEntry {\n /**\n * Name of the weight, e.g., 'Dense_1/bias'\n */\n name: string;\n\n /**\n * Shape of the weight.\n */\n shape: number[];\n\n /**\n * Data type of the weight.\n */\n dtype: 'float32'|'int32'|'bool'|'string'|'complex64';\n\n /**\n * Type of the weight.\n *\n * Optional.\n *\n * The value 'optimizer' indicates the weight belongs to an optimizer\n * (i.e., used only during model training and not during inference).\n */\n group?: WeightGroup;\n\n /**\n * Information for dequantization of the weight.\n */\n quantization?: {\n scale?: number, // The scaling constant to multiply by.\n min?: number, // The (possibly nudged) minimum weight to add.\n dtype: 'uint16'|'uint8'|'float16' // The dtype of the quantized weights.\n };\n}\n\n/**\n * Options for saving a model.\n * @innamespace io\n */\nexport interface SaveConfig {\n /**\n * Whether to save only the trainable weights of the model, ignoring the\n * non-trainable ones.\n */\n trainableOnly?: boolean;\n\n /**\n * Whether the optimizer will be saved (if exists).\n *\n * Default: `false`.\n */\n includeOptimizer?: boolean;\n}\n\n/**\n * Result of a saving operation.\n */\nexport interface SaveResult {\n /**\n * Information about the model artifacts saved.\n */\n modelArtifactsInfo: ModelArtifactsInfo;\n\n /**\n * HTTP responses from the server that handled the model-saving request (if\n * any). This is applicable only to server-based saving routes.\n */\n responses?: Response[];\n\n /**\n * Error messages and related data (if any).\n */\n errors?: Array<{}|string>;\n}\n\nexport declare interface ModelArtifactsInfo {\n /**\n * Timestamp for when the model is saved.\n */\n dateSaved: Date;\n\n /**\n * TODO (cais,yassogba) consider removing GraphDef as GraphDefs now\n * come in a JSON format and none of our IOHandlers support a non json\n * format. We could conder replacing this with 'Binary' if we want to\n * allow future handlers to save to non json formats (though they will\n * probably want more information than 'Binary').\n * Type of the model topology\n *\n * Type of the model topology\n *\n * Possible values:\n * - JSON: JSON config (human-readable, e.g., Keras JSON).\n * - GraphDef: TensorFlow\n * [GraphDef](https://www.tensorflow.org/extend/tool_developers/#graphdef)\n * protocol buffer (binary).\n */\n modelTopologyType: 'JSON'|'GraphDef';\n\n /**\n * Size of model topology (Keras JSON or GraphDef), in bytes.\n */\n modelTopologyBytes?: number;\n\n /**\n * Size of weight specification or manifest, in bytes.\n */\n weightSpecsBytes?: number;\n\n /**\n * Size of weight value data, in bytes.\n */\n weightDataBytes?: number;\n}\n\n/** Model training configuration. */\nexport declare interface TrainingConfig {\n // TODO(cais): Tighten the typing once keras spec is available to tfjs-core.\n // See\n // tslint:disable-next-line:max-line-length\n // https://github.com/tensorflow/tfjs-layers/blob/master/src/keras_format/training_config.ts\n /** Optimizer used for the model training. */\n optimizer_config: {};\n\n // TODO(cais): Tighten the typing once keras spec is available to tfjs-core.\n /** Loss function(s) for the model's output(s). */\n loss: string|string[]|{[key: string]: string};\n\n // TODO(cais): Tighten the typing once keras spec is available to tfjs-core.\n /** Metric function(s) for the model's output(s). */\n metrics?: string[]|{[key: string]: string};\n\n // TODO(cais): Tighten the typing once keras spec is available to tfjs-core.\n weighted_metrics?: string[];\n\n // TODO(cais): Tighten the typing once keras spec is available to tfjs-core.\n sample_weight_mode?: string;\n\n loss_weights?: number[]|{[key: string]: number};\n}\n\n/**\n * The serialized artifacts of a model, including topology and weights.\n *\n * The `modelTopology`, `trainingConfig`, `weightSpecs` and `weightData` fields\n * of this interface are optional, in order to support topology- or weights-only\n * saving and loading.\n *\n * Note this interface is used internally in IOHandlers. For the file format\n * written to disk as `model.json`, see `ModelJSON`.\n */\nexport declare interface ModelArtifacts {\n /**\n * Model topology.\n *\n * For Keras-style `tf.Model`s, this is a JSON object.\n * For TensorFlow-style models (e.g., `SavedModel`), this is the JSON\n * encoding of the `GraphDef` protocol buffer.\n */\n modelTopology?: {}|ArrayBuffer;\n\n /**\n * Serialized configuration for the model's training.\n */\n trainingConfig?: TrainingConfig;\n\n /**\n * Weight specifications.\n *\n * This corresponds to the weightsData below.\n */\n weightSpecs?: WeightsManifestEntry[];\n\n /**\n * Binary buffer for all weight values concatenated in the order specified\n * by `weightSpecs`.\n */\n weightData?: ArrayBuffer;\n\n /**\n * Hard-coded format name for models saved from TensorFlow.js or converted\n * by TensorFlow.js Converter.\n */\n format?: string;\n\n /**\n * What library is responsible for originally generating this artifact.\n *\n * Used for debugging purposes. E.g., 'TensorFlow.js v1.0.0'.\n */\n generatedBy?: string;\n\n /**\n * What library or tool is responsible for converting the original model\n * to this format, applicable only if the model is output by a converter.\n *\n * Used for debugging purposes. E.g., 'TensorFlow.js Converter v1.0.0'.\n *\n * A value of `null` means the model artifacts are generated without any\n * conversion process (e.g., saved directly from a TensorFlow.js\n * `tf.LayersModel` instance.)\n */\n convertedBy?: string|null;\n\n /**\n * Inputs and outputs signature for saved model.\n */\n signature?: {};\n\n /**\n * User-defined metadata about the model.\n */\n userDefinedMetadata?: {[key: string]: {}};\n\n /**\n * Initializer for the model.\n */\n modelInitializer?: {};\n}\n\n/**\n * The on-disk format of the `model.json` file.\n *\n * TF.js 1.0 always populates the optional fields when writing model.json.\n * Prior versions did not provide those fields.\n */\nexport declare interface ModelJSON {\n /**\n * Model topology.\n *\n * For Keras-style `tf.Model`s, this is a JSON object.\n * For TensorFlow-style models (e.g., `SavedModel`), this is the JSON\n * encoding of the `GraphDef` protocol buffer.\n */\n modelTopology: {};\n\n /** Model training configuration. */\n trainingConfig?: TrainingConfig;\n\n /**\n * Weights manifest.\n *\n * The weights manifest consists of an ordered list of weight-manifest\n * groups. Each weight-manifest group consists of a number of weight values\n * stored in a number of paths. See the documentation of\n * `WeightsManifestConfig` for more details.\n */\n weightsManifest: WeightsManifestConfig;\n\n /**\n * Hard-coded format name for models saved from TensorFlow.js or converted\n * by TensorFlow.js Converter.\n */\n format?: string;\n\n /**\n * What library is responsible for originally generating this artifact.\n *\n * Used for debugging purposes. E.g., 'TensorFlow.js v1.0.0'.\n */\n generatedBy?: string;\n\n /**\n * What library or tool is responsible for converting the original model\n * to this format, applicable only if the model is output by a converter.\n *\n * Used for debugging purposes. E.g., 'TensorFlow.js Converter v1.0.0'.\n *\n * A value of `null` means the model artifacts are generated without any\n * conversion process (e.g., saved directly from a TensorFlow.js\n * `tf.LayersModel` instance.)\n */\n convertedBy?: string|null;\n\n /**\n * Inputs and outputs signature for saved model.\n */\n signature?: {};\n\n /**\n * User-defined metadata about the model.\n */\n userDefinedMetadata?: {[key: string]: {}};\n\n /**\n * Initializer for the model.\n */\n modelInitializer?: {};\n}\n\n/**\n * Type definition for handlers of loading operations.\n */\nexport type LoadHandler = () => Promise;\n\n/**\n * Type definition for handlers of saving operations.\n */\nexport type SaveHandler = (modelArtifact: ModelArtifacts) =>\n Promise;\n\n/**\n * Interface for a model import/export handler.\n *\n * The `save` and `load` handlers are both optional, in order to allow handlers\n * that support only saving or loading.\n */\n// tslint:disable-next-line:interface-name\nexport interface IOHandler {\n save?: SaveHandler;\n load?: LoadHandler;\n}\n\n/**\n * An interface for the manager of a model store.\n *\n * A model store is defined as a storage medium on which multiple models can\n * be stored. Each stored model has a unique `path` as its identifier.\n * A `ModelStoreManager` for the store allows actions including\n *\n * - Listing the models stored in the store.\n * - Deleting a model from the store.\n */\nexport interface ModelStoreManager {\n /**\n * List all models in the model store.\n *\n * @returns A dictionary mapping paths of existing models to their\n * model artifacts info. Model artifacts info include type of the model's\n * topology, byte sizes of the topology, weights, etc.\n */\n listModels(): Promise<{[path: string]: ModelArtifactsInfo}>;\n\n /**\n * Remove a model specified by `path`.\n *\n * @param path\n * @returns ModelArtifactsInfo of the deleted model (if and only if deletion\n * is successful).\n * @throws Error if deletion fails, e.g., if no model exists at `path`.\n */\n removeModel(path: string): Promise;\n}\n\n/**\n * Callback for the progress of a long-running action such as an HTTP\n * request for a large binary object.\n *\n * `fraction` should be a number in the [0, 1] interval, indicating how\n * much of the action has completed.\n */\nexport type OnProgressCallback = (fraction: number) => void;\n\n/** @innamespace io */\nexport interface LoadOptions {\n /**\n * RequestInit (options) for HTTP requests.\n *\n * For detailed information on the supported fields, see\n * [https://developer.mozilla.org/en-US/docs/Web/API/Request/Request](\n * https://developer.mozilla.org/en-US/docs/Web/API/Request/Request)\n */\n requestInit?: RequestInit;\n\n /**\n * Progress callback.\n */\n onProgress?: OnProgressCallback;\n\n /**\n * A function used to override the `window.fetch` function.\n */\n fetchFunc?: Function;\n\n /**\n * Strict loading model: whether extraneous weights or missing\n * weights should trigger an `Error`.\n *\n * If `true`, require that the provided weights exactly match those\n * required by the layers. `false` means that both extra weights\n * and missing weights will be silently ignored.\n *\n * Default: `true`.\n */\n strict?: boolean;\n\n /**\n * Path prefix for weight files, by default this is calculated from the\n * path of the model JSON file.\n *\n * For instance, if the path to the model JSON file is\n * `http://localhost/foo/model.json`, then the default path prefix will be\n * `http://localhost/foo/`. If a weight file has the path value\n * `group1-shard1of2` in the weight manifest, then the weight file will be\n * loaded from `http://localhost/foo/group1-shard1of2` by default. However,\n * if you provide a `weightPathPrefix` value of\n * `http://localhost/foo/alt-weights`, then the weight file will be loaded\n * from the path `http://localhost/foo/alt-weights/group1-shard1of2` instead.\n */\n weightPathPrefix?: string;\n\n /**\n * Whether the module or model is to be loaded from TF Hub.\n *\n * Setting this to `true` allows passing a TF-Hub module URL, omitting the\n * standard model file name and the query parameters.\n *\n * Default: `false`.\n */\n fromTFHub?: boolean;\n\n /**\n * An async function to convert weight file name to URL. The weight file\n * names are stored in model.json's weightsManifest.paths field. By default we\n * consider weight files are colocated with the model.json file. For example:\n * model.json URL: https://www.google.com/models/1/model.json\n * group1-shard1of1.bin url:\n * https://www.google.com/models/1/group1-shard1of1.bin\n *\n * With this func you can convert the weight file name to any URL.\n */\n weightUrlConverter?: (weightFileName: string) => Promise;\n}\n\n/**\n * Additional options for Platform.fetch\n */\nexport interface RequestDetails {\n /**\n * Is this request for a binary file (as opposed to a json file)\n */\n isBinary?: boolean;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {complex} from '../ops/complex';\nimport {tensor} from '../ops/tensor';\nimport {NamedTensor, NamedTensorMap} from '../tensor_types';\nimport {TypedArray} from '../types';\nimport {sizeFromShape} from '../util';\n\nimport {DTYPE_VALUE_SIZE_MAP, ModelArtifacts, ModelArtifactsInfo, ModelJSON, WeightGroup, WeightsManifestConfig, WeightsManifestEntry} from './types';\n\n/** Number of bytes reserved for the length of the string. (32bit integer). */\nconst NUM_BYTES_STRING_LENGTH = 4;\n\n/**\n * Encode a map from names to weight values as an ArrayBuffer, along with an\n * `Array` of `WeightsManifestEntry` as specification of the encoded weights.\n *\n * This function does not perform sharding.\n *\n * This function is the reverse of `decodeWeights`.\n *\n * @param tensors A map (\"dict\") from names to tensors.\n * @param group Group to which the weights belong (optional).\n * @returns A `Promise` of\n * - A flat `ArrayBuffer` with all the binary values of the `Tensor`s\n * concatenated.\n * - An `Array` of `WeightManifestEntry`s, carrying information including\n * tensor names, `dtype`s and shapes.\n * @throws Error: on unsupported tensor `dtype`.\n */\nexport async function encodeWeights(\n tensors: NamedTensorMap|NamedTensor[], group?: WeightGroup):\n Promise<{data: ArrayBuffer, specs: WeightsManifestEntry[]}> {\n // TODO(adarob, cais): Support quantization.\n const specs: WeightsManifestEntry[] = [];\n const dataPromises: Array> = [];\n\n const names: string[] = Array.isArray(tensors) ?\n tensors.map(tensor => tensor.name) :\n Object.keys(tensors);\n\n for (let i = 0; i < names.length; ++i) {\n const name = names[i];\n const t = Array.isArray(tensors) ? tensors[i].tensor : tensors[name];\n if (t.dtype !== 'float32' && t.dtype !== 'int32' && t.dtype !== 'bool' &&\n t.dtype !== 'string' && t.dtype !== 'complex64') {\n throw new Error(`Unsupported dtype in weight '${name}': ${t.dtype}`);\n }\n const spec: WeightsManifestEntry = {name, shape: t.shape, dtype: t.dtype};\n if (t.dtype === 'string') {\n const utf8bytes = new Promise(async resolve => {\n const vals = await t.bytes() as Uint8Array[];\n const totalNumBytes = vals.reduce((p, c) => p + c.length, 0) +\n NUM_BYTES_STRING_LENGTH * vals.length;\n const bytes = new Uint8Array(totalNumBytes);\n let offset = 0;\n for (let i = 0; i < vals.length; i++) {\n const val = vals[i];\n const bytesOfLength =\n new Uint8Array(new Uint32Array([val.length]).buffer);\n bytes.set(bytesOfLength, offset);\n offset += NUM_BYTES_STRING_LENGTH;\n bytes.set(val, offset);\n offset += val.length;\n }\n resolve(bytes);\n });\n dataPromises.push(utf8bytes);\n } else {\n dataPromises.push(t.data());\n }\n if (group != null) {\n spec.group = group;\n }\n specs.push(spec);\n }\n\n const tensorValues = await Promise.all(dataPromises);\n return {data: concatenateTypedArrays(tensorValues), specs};\n}\n\n/**\n * Decode flat ArrayBuffer as weights.\n *\n * This function does not handle sharding.\n *\n * This function is the reverse of `encodeWeights`.\n *\n * @param buffer A flat ArrayBuffer carrying the binary values of the tensors\n * concatenated in the order specified in `specs`.\n * @param specs Specifications of the names, dtypes and shapes of the tensors\n * whose value are encoded by `buffer`.\n * @return A map from tensor name to tensor value, with the names corresponding\n * to names in `specs`.\n * @throws Error, if any of the tensors has unsupported dtype.\n */\nexport function decodeWeights(\n buffer: ArrayBuffer, specs: WeightsManifestEntry[]): NamedTensorMap {\n // TODO(adarob, cais): Support quantization.\n const out: NamedTensorMap = {};\n let float16Decode: (buffer: Uint16Array) => Float32Array | undefined;\n let offset = 0;\n for (const spec of specs) {\n const name = spec.name;\n const dtype = spec.dtype;\n const shape = spec.shape;\n const size = sizeFromShape(shape);\n let values: TypedArray|string[]|Uint8Array[];\n\n if ('quantization' in spec) {\n const quantization = spec.quantization;\n if (quantization.dtype === 'uint8' || quantization.dtype === 'uint16') {\n if (!('min' in quantization && 'scale' in quantization)) {\n throw new Error(\n `Weight ${spec.name} with quantization ${quantization.dtype} ` +\n `doesn't have corresponding metadata min and scale.`);\n }\n } else if (quantization.dtype === 'float16') {\n if (dtype !== 'float32') {\n throw new Error(\n `Weight ${spec.name} is quantized with ${quantization.dtype} ` +\n `which only supports weights of type float32 not ${dtype}.`);\n }\n } else {\n throw new Error(\n `Weight ${spec.name} has unknown ` +\n `quantization dtype ${quantization.dtype}. ` +\n `Supported quantization dtypes are: ` +\n `'uint8', 'uint16', and 'float16'.`);\n }\n const quantizationSizeFactor = DTYPE_VALUE_SIZE_MAP[quantization.dtype];\n const byteBuffer =\n buffer.slice(offset, offset + size * quantizationSizeFactor);\n const quantizedArray = (quantization.dtype === 'uint8') ?\n new Uint8Array(byteBuffer) :\n new Uint16Array(byteBuffer);\n if (dtype === 'float32') {\n if (quantization.dtype === 'uint8' || quantization.dtype === 'uint16') {\n values = new Float32Array(quantizedArray.length);\n for (let i = 0; i < quantizedArray.length; i++) {\n const v = quantizedArray[i];\n values[i] = v * quantization.scale + quantization.min;\n }\n } else if (quantization.dtype === 'float16') {\n if (float16Decode === undefined) {\n float16Decode = getFloat16Decoder();\n }\n values = float16Decode(quantizedArray as Uint16Array);\n } else {\n throw new Error(\n `Unsupported quantization type ${quantization.dtype} ` +\n `for weight type float32.`);\n }\n } else if (dtype === 'int32') {\n if (quantization.dtype !== 'uint8' && quantization.dtype !== 'uint16') {\n throw new Error(\n `Unsupported quantization type ${quantization.dtype} ` +\n `for weight type int32.`);\n }\n values = new Int32Array(quantizedArray.length);\n for (let i = 0; i < quantizedArray.length; i++) {\n const v = quantizedArray[i];\n values[i] = Math.round(v * quantization.scale + quantization.min);\n }\n } else {\n throw new Error(`Unsupported dtype in weight '${name}': ${dtype}`);\n }\n offset += size * quantizationSizeFactor;\n } else if (dtype === 'string') {\n const size = sizeFromShape(spec.shape);\n values = [];\n for (let i = 0; i < size; i++) {\n const byteLength = new Uint32Array(\n buffer.slice(offset, offset + NUM_BYTES_STRING_LENGTH))[0];\n offset += NUM_BYTES_STRING_LENGTH;\n const bytes = new Uint8Array(buffer.slice(offset, offset + byteLength));\n (values as Uint8Array[]).push(bytes);\n offset += byteLength;\n }\n } else {\n const dtypeFactor = DTYPE_VALUE_SIZE_MAP[dtype];\n const byteBuffer = buffer.slice(offset, offset + size * dtypeFactor);\n\n if (dtype === 'float32') {\n values = new Float32Array(byteBuffer);\n } else if (dtype === 'int32') {\n values = new Int32Array(byteBuffer);\n } else if (dtype === 'bool') {\n values = new Uint8Array(byteBuffer);\n } else if (dtype === 'complex64') {\n values = new Float32Array(byteBuffer);\n const real = new Float32Array(values.length / 2);\n const image = new Float32Array(values.length / 2);\n for (let i = 0; i < real.length; i++) {\n real[i] = values[i * 2];\n image[i] = values[i * 2 + 1];\n }\n const realTensor = tensor(real, shape, 'float32');\n const imageTensor = tensor(image, shape, 'float32');\n out[name] = complex(realTensor, imageTensor);\n realTensor.dispose();\n imageTensor.dispose();\n } else {\n throw new Error(`Unsupported dtype in weight '${name}': ${dtype}`);\n }\n offset += size * dtypeFactor;\n }\n if (dtype !== 'complex64') {\n out[name] = tensor(values, shape, dtype);\n }\n }\n return out;\n}\n\n/**\n * Concatenate TypedArrays into an ArrayBuffer.\n */\nexport function concatenateTypedArrays(xs: TypedArray[]): ArrayBuffer {\n // TODO(adarob, cais): Support quantization.\n if (xs === null) {\n throw new Error(`Invalid input value: ${JSON.stringify(xs)}`);\n }\n\n let totalByteLength = 0;\n\n // `normalizedXs` is here for this reason: a `TypedArray`'s `buffer'\n // can have a different byte length from that of the `TypedArray` itself,\n // for example, when the `TypedArray` is created from an offset in an\n // `ArrayBuffer`. `normliazedXs` holds `TypedArray`s whose `buffer`s match\n // the `TypedArray` in byte length. If an element of `xs` does not show\n // this property, a new `TypedArray` that satisfy this property will be\n // constructed and pushed into `normalizedXs`.\n const normalizedXs: TypedArray[] = [];\n xs.forEach((x: TypedArray) => {\n totalByteLength += x.byteLength;\n // tslint:disable:no-any\n normalizedXs.push(\n x.byteLength === x.buffer.byteLength ? x :\n new (x.constructor as any)(x));\n if (!(x as any instanceof Float32Array || x as any instanceof Int32Array ||\n x as any instanceof Uint8Array)) {\n throw new Error(`Unsupported TypedArray subtype: ${x.constructor.name}`);\n }\n // tslint:enable:no-any\n });\n\n const y = new Uint8Array(totalByteLength);\n let offset = 0;\n normalizedXs.forEach((x: TypedArray) => {\n y.set(new Uint8Array(x.buffer), offset);\n offset += x.byteLength;\n });\n\n return y.buffer;\n}\n\n// Use Buffer on Node.js instead of Blob/atob/btoa\nconst useNodeBuffer = typeof Buffer !== 'undefined' &&\n (typeof Blob === 'undefined' || typeof atob === 'undefined' ||\n typeof btoa === 'undefined');\n\n/**\n * Calculate the byte length of a JavaScript string.\n *\n * Note that a JavaScript string can contain wide characters, therefore the\n * length of the string is not necessarily equal to the byte length.\n *\n * @param str Input string.\n * @returns Byte length.\n */\nexport function stringByteLength(str: string): number {\n if (useNodeBuffer) {\n return Buffer.byteLength(str);\n }\n return new Blob([str]).size;\n}\n\n/**\n * Encode an ArrayBuffer as a base64 encoded string.\n *\n * @param buffer `ArrayBuffer` to be converted.\n * @returns A string that base64-encodes `buffer`.\n */\nexport function arrayBufferToBase64String(buffer: ArrayBuffer): string {\n if (useNodeBuffer) {\n return Buffer.from(buffer).toString('base64');\n }\n const buf = new Uint8Array(buffer);\n let s = '';\n for (let i = 0, l = buf.length; i < l; i++) {\n s += String.fromCharCode(buf[i]);\n }\n return btoa(s);\n}\n\n/**\n * Decode a base64 string as an ArrayBuffer.\n *\n * @param str Base64 string.\n * @returns Decoded `ArrayBuffer`.\n */\nexport function base64StringToArrayBuffer(str: string): ArrayBuffer {\n if (useNodeBuffer) {\n const buf = Buffer.from(str, 'base64');\n return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);\n }\n const s = atob(str);\n const buffer = new Uint8Array(s.length);\n for (let i = 0; i < s.length; ++i) {\n buffer.set([s.charCodeAt(i)], i);\n }\n return buffer.buffer;\n}\n\n/**\n * Concatenate a number of ArrayBuffers into one.\n *\n * @param buffers A number of array buffers to concatenate.\n * @returns Result of concatenating `buffers` in order.\n */\nexport function concatenateArrayBuffers(buffers: ArrayBuffer[]): ArrayBuffer {\n if (buffers.length === 1) {\n return buffers[0];\n }\n\n let totalByteLength = 0;\n buffers.forEach((buffer: ArrayBuffer) => {\n totalByteLength += buffer.byteLength;\n });\n\n const temp = new Uint8Array(totalByteLength);\n let offset = 0;\n buffers.forEach((buffer: ArrayBuffer) => {\n temp.set(new Uint8Array(buffer), offset);\n offset += buffer.byteLength;\n });\n return temp.buffer;\n}\n\n/**\n * Get the basename of a path.\n *\n * Behaves in a way analogous to Linux's basename command.\n *\n * @param path\n */\nexport function basename(path: string): string {\n const SEPARATOR = '/';\n path = path.trim();\n while (path.endsWith(SEPARATOR)) {\n path = path.slice(0, path.length - 1);\n }\n const items = path.split(SEPARATOR);\n return items[items.length - 1];\n}\n\n/**\n * Create `ModelJSON` from `ModelArtifacts`.\n *\n * @param artifacts Model artifacts, describing the model and its weights.\n * @param manifest Weight manifest, describing where the weights of the\n * `ModelArtifacts` are stored, and some metadata about them.\n * @returns Object representing the `model.json` file describing the model\n * artifacts and weights\n */\nexport function getModelJSONForModelArtifacts(\n artifacts: ModelArtifacts, manifest: WeightsManifestConfig): ModelJSON {\n const result: ModelJSON = {\n modelTopology: artifacts.modelTopology,\n format: artifacts.format,\n generatedBy: artifacts.generatedBy,\n convertedBy: artifacts.convertedBy,\n weightsManifest: manifest\n };\n if (artifacts.signature != null) {\n result.signature = artifacts.signature;\n }\n if (artifacts.userDefinedMetadata != null) {\n result.userDefinedMetadata = artifacts.userDefinedMetadata;\n }\n if (artifacts.modelInitializer != null) {\n result.modelInitializer = artifacts.modelInitializer;\n }\n if (artifacts.trainingConfig != null) {\n result.trainingConfig = artifacts.trainingConfig;\n }\n return result;\n}\n\n/**\n * Create `ModelArtifacts` from a JSON file.\n *\n * @param modelJSON Object containing the parsed JSON of `model.json`\n * @param loadWeights Function that takes the JSON file's weights manifest,\n * reads weights from the listed path(s), and returns a Promise of the\n * weight manifest entries along with the weights data.\n * @returns A Promise of the `ModelArtifacts`, as described by the JSON file.\n */\nexport async function getModelArtifactsForJSON(\n modelJSON: ModelJSON,\n loadWeights: (weightsManifest: WeightsManifestConfig) => Promise<[\n /* weightSpecs */ WeightsManifestEntry[], /* weightData */ ArrayBuffer\n ]>): Promise {\n const modelArtifacts: ModelArtifacts = {\n modelTopology: modelJSON.modelTopology,\n format: modelJSON.format,\n generatedBy: modelJSON.generatedBy,\n convertedBy: modelJSON.convertedBy\n };\n\n if (modelJSON.trainingConfig != null) {\n modelArtifacts.trainingConfig = modelJSON.trainingConfig;\n }\n if (modelJSON.weightsManifest != null) {\n const [weightSpecs, weightData] =\n await loadWeights(modelJSON.weightsManifest);\n modelArtifacts.weightSpecs = weightSpecs;\n modelArtifacts.weightData = weightData;\n }\n if (modelJSON.signature != null) {\n modelArtifacts.signature = modelJSON.signature;\n }\n if (modelJSON.userDefinedMetadata != null) {\n modelArtifacts.userDefinedMetadata = modelJSON.userDefinedMetadata;\n }\n if (modelJSON.modelInitializer != null) {\n modelArtifacts.modelInitializer = modelJSON.modelInitializer;\n }\n\n return modelArtifacts;\n}\n\n/**\n * Populate ModelArtifactsInfo fields for a model with JSON topology.\n * @param modelArtifacts\n * @returns A ModelArtifactsInfo object.\n */\nexport function getModelArtifactsInfoForJSON(modelArtifacts: ModelArtifacts):\n ModelArtifactsInfo {\n if (modelArtifacts.modelTopology instanceof ArrayBuffer) {\n throw new Error('Expected JSON model topology, received ArrayBuffer.');\n }\n\n return {\n dateSaved: new Date(),\n modelTopologyType: 'JSON',\n modelTopologyBytes: modelArtifacts.modelTopology == null ?\n 0 :\n stringByteLength(JSON.stringify(modelArtifacts.modelTopology)),\n weightSpecsBytes: modelArtifacts.weightSpecs == null ?\n 0 :\n stringByteLength(JSON.stringify(modelArtifacts.weightSpecs)),\n weightDataBytes: modelArtifacts.weightData == null ?\n 0 :\n modelArtifacts.weightData.byteLength,\n };\n}\n\n/**\n * Computes mantisa table for casting Float16 to Float32\n * See http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n *\n * @returns Uint32Array, 2048 mantissa lookup values.\n */\nfunction computeFloat16MantisaTable(): Uint32Array {\n const convertMantissa = (i: number): number => {\n let m = i << 13;\n let e = 0;\n\n while ((m & 0x00800000) === 0) {\n e -= 0x00800000;\n m <<= 1;\n }\n m &= ~0x00800000;\n e += 0x38800000;\n\n return m | e;\n };\n\n const mantisaTable = new Uint32Array(2048);\n\n mantisaTable[0] = 0;\n for (let i = 1; i < 1024; i++) {\n mantisaTable[i] = convertMantissa(i);\n }\n for (let i = 1024; i < 2048; i++) {\n mantisaTable[i] = 0x38000000 + ((i - 1024) << 13);\n }\n\n return mantisaTable;\n}\n\n/**\n * Computes exponent table for casting Float16 to Float32\n * See http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n *\n * @returns Uint32Array, 64 exponent lookup values.\n */\nfunction computeFloat16ExponentTable(): Uint32Array {\n const exponentTable = new Uint32Array(64);\n\n exponentTable[0] = 0;\n exponentTable[31] = 0x47800000;\n exponentTable[32] = 0x80000000;\n exponentTable[63] = 0xc7800000;\n for (let i = 1; i < 31; i++) {\n exponentTable[i] = i << 23;\n }\n for (let i = 33; i < 63; i++) {\n exponentTable[i] = 0x80000000 + ((i - 32) << 23);\n }\n\n return exponentTable;\n}\n\n/**\n * Computes offset table for casting Float16 to Float32\n * See http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n *\n * @returns Uint32Array, 6d offset values.\n */\nfunction computeFloat16OffsetTable(): Uint32Array {\n const offsetTable = new Uint32Array(64);\n\n for (let i = 0; i < 64; i++) {\n offsetTable[i] = 1024;\n }\n offsetTable[0] = offsetTable[32] = 0;\n\n return offsetTable;\n}\n\n/**\n * Retrieve a Float16 decoder which will decode a ByteArray of Float16 values\n * to a Float32Array.\n *\n * @returns Function (buffer: Uint16Array) => Float32Array which decodes\n * the Uint16Array of Float16 bytes to a Float32Array.\n */\nexport function getFloat16Decoder(): (buffer: Uint16Array) => Float32Array {\n // Algorithm is based off of\n // http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n\n // Cache lookup tables\n const mantisaTable = computeFloat16MantisaTable();\n const exponentTable = computeFloat16ExponentTable();\n const offsetTable = computeFloat16OffsetTable();\n\n return (quantizedArray: Uint16Array) => {\n const buffer = new ArrayBuffer(4 * quantizedArray.length);\n const bufferUint32View = new Uint32Array(buffer);\n for (let index = 0; index < quantizedArray.length; index++) {\n const float16Bits = quantizedArray[index];\n const float32Bits =\n mantisaTable[offsetTable[float16Bits >> 10] + (float16Bits & 0x3ff)] +\n exponentTable[float16Bits >> 10];\n bufferUint32View[index] = float32Bits;\n }\n return new Float32Array(buffer);\n };\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {IOHandler, LoadOptions} from './types';\n\nexport type IORouter = (url: string|string[], loadOptions?: LoadOptions) =>\n IOHandler;\n\nexport class IORouterRegistry {\n // Singleton instance.\n private static instance: IORouterRegistry;\n\n private saveRouters: IORouter[];\n private loadRouters: IORouter[];\n\n private constructor() {\n this.saveRouters = [];\n this.loadRouters = [];\n }\n\n private static getInstance(): IORouterRegistry {\n if (IORouterRegistry.instance == null) {\n IORouterRegistry.instance = new IORouterRegistry();\n }\n return IORouterRegistry.instance;\n }\n\n /**\n * Register a save-handler router.\n *\n * @param saveRouter A function that maps a URL-like string onto an instance\n * of `IOHandler` with the `save` method defined or `null`.\n */\n static registerSaveRouter(saveRouter: IORouter) {\n IORouterRegistry.getInstance().saveRouters.push(saveRouter);\n }\n\n /**\n * Register a load-handler router.\n *\n * @param loadRouter A function that maps a URL-like string onto an instance\n * of `IOHandler` with the `load` method defined or `null`.\n */\n static registerLoadRouter(loadRouter: IORouter) {\n IORouterRegistry.getInstance().loadRouters.push(loadRouter);\n }\n\n /**\n * Look up IOHandler for saving, given a URL-like string.\n *\n * @param url\n * @returns If only one match is found, an instance of IOHandler with the\n * `save` method defined. If no match is found, `null`.\n * @throws Error, if more than one match is found.\n */\n static getSaveHandlers(url: string|string[]): IOHandler[] {\n return IORouterRegistry.getHandlers(url, 'save');\n }\n\n /**\n * Look up IOHandler for loading, given a URL-like string.\n *\n * @param url\n * @param loadOptions Optional, custom load options.\n * @returns All valid handlers for `url`, given the currently registered\n * handler routers.\n */\n static getLoadHandlers(url: string|string[], loadOptions?: LoadOptions):\n IOHandler[] {\n return IORouterRegistry.getHandlers(url, 'load', loadOptions);\n }\n\n private static getHandlers(\n url: string|string[], handlerType: 'save'|'load',\n loadOptions?: LoadOptions): IOHandler[] {\n const validHandlers: IOHandler[] = [];\n const routers = handlerType === 'load' ?\n IORouterRegistry.getInstance().loadRouters :\n IORouterRegistry.getInstance().saveRouters;\n routers.forEach(router => {\n const handler = router(url, loadOptions);\n if (handler !== null) {\n validHandlers.push(handler);\n }\n });\n return validHandlers;\n }\n}\n\nexport const registerSaveRouter = (loudRouter: IORouter) =>\n IORouterRegistry.registerSaveRouter(loudRouter);\nexport const registerLoadRouter = (loudRouter: IORouter) =>\n IORouterRegistry.registerLoadRouter(loudRouter);\nexport const getSaveHandlers = (url: string|string[]) =>\n IORouterRegistry.getSaveHandlers(url);\nexport const getLoadHandlers =\n (url: string|string[], loadOptions?: LoadOptions) =>\n IORouterRegistry.getLoadHandlers(url, loadOptions);\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport '../flags';\n\nimport {env} from '../environment';\n\nimport {getModelArtifactsInfoForJSON} from './io_utils';\nimport {IORouter, IORouterRegistry} from './router_registry';\nimport {IOHandler, ModelArtifacts, ModelArtifactsInfo, ModelStoreManager, SaveResult} from './types';\n\nconst DATABASE_NAME = 'tensorflowjs';\nconst DATABASE_VERSION = 1;\n\n// Model data and ModelArtifactsInfo (metadata) are stored in two separate\n// stores for efficient access of the list of stored models and their metadata.\n// 1. The object store for model data: topology, weights and weight manifests.\nconst MODEL_STORE_NAME = 'models_store';\n// 2. The object store for ModelArtifactsInfo, including meta-information such\n// as the type of topology (JSON vs binary), byte size of the topology, byte\n// size of the weights, etc.\nconst INFO_STORE_NAME = 'model_info_store';\n\n/**\n * Delete the entire database for tensorflow.js, including the models store.\n */\nexport async function deleteDatabase(): Promise {\n const idbFactory = getIndexedDBFactory();\n\n return new Promise((resolve, reject) => {\n const deleteRequest = idbFactory.deleteDatabase(DATABASE_NAME);\n deleteRequest.onsuccess = () => resolve();\n deleteRequest.onerror = error => reject(error);\n });\n}\n\nfunction getIndexedDBFactory(): IDBFactory {\n if (!env().getBool('IS_BROWSER')) {\n // TODO(cais): Add more info about what IOHandler subtypes are available.\n // Maybe point to a doc page on the web and/or automatically determine\n // the available IOHandlers and print them in the error message.\n throw new Error(\n 'Failed to obtain IndexedDB factory because the current environment' +\n 'is not a web browser.');\n }\n // tslint:disable-next-line:no-any\n const theWindow: any = typeof window === 'undefined' ? self : window;\n const factory = theWindow.indexedDB || theWindow.mozIndexedDB ||\n theWindow.webkitIndexedDB || theWindow.msIndexedDB ||\n theWindow.shimIndexedDB;\n if (factory == null) {\n throw new Error(\n 'The current browser does not appear to support IndexedDB.');\n }\n return factory;\n}\n\nfunction setUpDatabase(openRequest: IDBRequest) {\n const db = openRequest.result as IDBDatabase;\n db.createObjectStore(MODEL_STORE_NAME, {keyPath: 'modelPath'});\n db.createObjectStore(INFO_STORE_NAME, {keyPath: 'modelPath'});\n}\n\n/**\n * IOHandler subclass: Browser IndexedDB.\n *\n * See the doc string of `browserIndexedDB` for more details.\n */\nexport class BrowserIndexedDB implements IOHandler {\n protected readonly indexedDB: IDBFactory;\n protected readonly modelPath: string;\n\n static readonly URL_SCHEME = 'indexeddb://';\n\n constructor(modelPath: string) {\n this.indexedDB = getIndexedDBFactory();\n\n if (modelPath == null || !modelPath) {\n throw new Error(\n 'For IndexedDB, modelPath must not be null, undefined or empty.');\n }\n this.modelPath = modelPath;\n }\n\n async save(modelArtifacts: ModelArtifacts): Promise {\n // TODO(cais): Support saving GraphDef models.\n if (modelArtifacts.modelTopology instanceof ArrayBuffer) {\n throw new Error(\n 'BrowserLocalStorage.save() does not support saving model topology ' +\n 'in binary formats yet.');\n }\n\n return this.databaseAction(this.modelPath, modelArtifacts) as\n Promise;\n }\n\n async load(): Promise {\n return this.databaseAction(this.modelPath) as Promise;\n }\n\n /**\n * Perform database action to put model artifacts into or read model artifacts\n * from IndexedDB object store.\n *\n * Whether the action is put or get depends on whether `modelArtifacts` is\n * specified. If it is specified, the action will be put; otherwise the action\n * will be get.\n *\n * @param modelPath A unique string path for the model.\n * @param modelArtifacts If specified, it will be the model artifacts to be\n * stored in IndexedDB.\n * @returns A `Promise` of `SaveResult`, if the action is put, or a `Promise`\n * of `ModelArtifacts`, if the action is get.\n */\n private databaseAction(modelPath: string, modelArtifacts?: ModelArtifacts):\n Promise {\n return new Promise((resolve, reject) => {\n const openRequest = this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);\n openRequest.onupgradeneeded = () => setUpDatabase(openRequest);\n\n openRequest.onsuccess = () => {\n const db = openRequest.result;\n\n if (modelArtifacts == null) {\n // Read model out from object store.\n const modelTx = db.transaction(MODEL_STORE_NAME, 'readonly');\n const modelStore = modelTx.objectStore(MODEL_STORE_NAME);\n const getRequest = modelStore.get(this.modelPath);\n getRequest.onsuccess = () => {\n if (getRequest.result == null) {\n db.close();\n return reject(new Error(\n `Cannot find model with path '${this.modelPath}' ` +\n `in IndexedDB.`));\n } else {\n resolve(getRequest.result.modelArtifacts);\n }\n };\n getRequest.onerror = error => {\n db.close();\n return reject(getRequest.error);\n };\n modelTx.oncomplete = () => db.close();\n } else {\n // Put model into object store.\n const modelArtifactsInfo: ModelArtifactsInfo =\n getModelArtifactsInfoForJSON(modelArtifacts);\n // First, put ModelArtifactsInfo into info store.\n const infoTx = db.transaction(INFO_STORE_NAME, 'readwrite');\n let infoStore = infoTx.objectStore(INFO_STORE_NAME);\n const putInfoRequest =\n infoStore.put({modelPath: this.modelPath, modelArtifactsInfo});\n let modelTx: IDBTransaction;\n putInfoRequest.onsuccess = () => {\n // Second, put model data into model store.\n modelTx = db.transaction(MODEL_STORE_NAME, 'readwrite');\n const modelStore = modelTx.objectStore(MODEL_STORE_NAME);\n const putModelRequest = modelStore.put({\n modelPath: this.modelPath,\n modelArtifacts,\n modelArtifactsInfo\n });\n putModelRequest.onsuccess = () => resolve({modelArtifactsInfo});\n putModelRequest.onerror = error => {\n // If the put-model request fails, roll back the info entry as\n // well.\n infoStore = infoTx.objectStore(INFO_STORE_NAME);\n const deleteInfoRequest = infoStore.delete(this.modelPath);\n deleteInfoRequest.onsuccess = () => {\n db.close();\n return reject(putModelRequest.error);\n };\n deleteInfoRequest.onerror = error => {\n db.close();\n return reject(putModelRequest.error);\n };\n };\n };\n putInfoRequest.onerror = error => {\n db.close();\n return reject(putInfoRequest.error);\n };\n infoTx.oncomplete = () => {\n if (modelTx == null) {\n db.close();\n } else {\n modelTx.oncomplete = () => db.close();\n }\n };\n }\n };\n openRequest.onerror = error => reject(openRequest.error);\n });\n }\n}\n\nexport const indexedDBRouter: IORouter = (url: string|string[]) => {\n if (!env().getBool('IS_BROWSER')) {\n return null;\n } else {\n if (!Array.isArray(url) && url.startsWith(BrowserIndexedDB.URL_SCHEME)) {\n return browserIndexedDB(url.slice(BrowserIndexedDB.URL_SCHEME.length));\n } else {\n return null;\n }\n }\n};\nIORouterRegistry.registerSaveRouter(indexedDBRouter);\nIORouterRegistry.registerLoadRouter(indexedDBRouter);\n\n/**\n * Creates a browser IndexedDB IOHandler for saving and loading models.\n *\n * ```js\n * const model = tf.sequential();\n * model.add(\n * tf.layers.dense({units: 1, inputShape: [100], activation: 'sigmoid'}));\n *\n * const saveResult = await model.save('indexeddb://MyModel'));\n * console.log(saveResult);\n * ```\n *\n * @param modelPath A unique identifier for the model to be saved. Must be a\n * non-empty string.\n * @returns An instance of `BrowserIndexedDB` (sublcass of `IOHandler`),\n * which can be used with, e.g., `tf.Model.save`.\n */\nexport function browserIndexedDB(modelPath: string): IOHandler {\n return new BrowserIndexedDB(modelPath);\n}\n\nfunction maybeStripScheme(key: string) {\n return key.startsWith(BrowserIndexedDB.URL_SCHEME) ?\n key.slice(BrowserIndexedDB.URL_SCHEME.length) :\n key;\n}\n\nexport class BrowserIndexedDBManager implements ModelStoreManager {\n private indexedDB: IDBFactory;\n\n constructor() {\n this.indexedDB = getIndexedDBFactory();\n }\n\n async listModels(): Promise<{[path: string]: ModelArtifactsInfo}> {\n return new Promise<{[path: string]: ModelArtifactsInfo}>(\n (resolve, reject) => {\n const openRequest =\n this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);\n openRequest.onupgradeneeded = () => setUpDatabase(openRequest);\n\n openRequest.onsuccess = () => {\n const db = openRequest.result;\n const tx = db.transaction(INFO_STORE_NAME, 'readonly');\n const store = tx.objectStore(INFO_STORE_NAME);\n // tslint:disable:max-line-length\n // Need to cast `store` as `any` here because TypeScript's DOM\n // library does not have the `getAll()` method even though the\n // method is supported in the latest version of most mainstream\n // browsers:\n // https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/getAll\n // tslint:enable:max-line-length\n // tslint:disable-next-line:no-any\n const getAllInfoRequest = (store as any).getAll() as IDBRequest;\n getAllInfoRequest.onsuccess = () => {\n const out: {[path: string]: ModelArtifactsInfo} = {};\n for (const item of getAllInfoRequest.result) {\n out[item.modelPath] = item.modelArtifactsInfo;\n }\n resolve(out);\n };\n getAllInfoRequest.onerror = error => {\n db.close();\n return reject(getAllInfoRequest.error);\n };\n tx.oncomplete = () => db.close();\n };\n openRequest.onerror = error => reject(openRequest.error);\n });\n }\n\n async removeModel(path: string): Promise {\n path = maybeStripScheme(path);\n return new Promise((resolve, reject) => {\n const openRequest = this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);\n openRequest.onupgradeneeded = () => setUpDatabase(openRequest);\n\n openRequest.onsuccess = () => {\n const db = openRequest.result;\n const infoTx = db.transaction(INFO_STORE_NAME, 'readwrite');\n const infoStore = infoTx.objectStore(INFO_STORE_NAME);\n\n const getInfoRequest = infoStore.get(path);\n let modelTx: IDBTransaction;\n getInfoRequest.onsuccess = () => {\n if (getInfoRequest.result == null) {\n db.close();\n return reject(new Error(\n `Cannot find model with path '${path}' ` +\n `in IndexedDB.`));\n } else {\n // First, delete the entry in the info store.\n const deleteInfoRequest = infoStore.delete(path);\n const deleteModelData = () => {\n // Second, delete the entry in the model store.\n modelTx = db.transaction(MODEL_STORE_NAME, 'readwrite');\n const modelStore = modelTx.objectStore(MODEL_STORE_NAME);\n const deleteModelRequest = modelStore.delete(path);\n deleteModelRequest.onsuccess = () =>\n resolve(getInfoRequest.result.modelArtifactsInfo);\n deleteModelRequest.onerror = error =>\n reject(getInfoRequest.error);\n };\n // Proceed with deleting model data regardless of whether deletion\n // of info data succeeds or not.\n deleteInfoRequest.onsuccess = deleteModelData;\n deleteInfoRequest.onerror = error => {\n deleteModelData();\n db.close();\n return reject(getInfoRequest.error);\n };\n }\n };\n getInfoRequest.onerror = error => {\n db.close();\n return reject(getInfoRequest.error);\n };\n\n infoTx.oncomplete = () => {\n if (modelTx == null) {\n db.close();\n } else {\n modelTx.oncomplete = () => db.close();\n }\n };\n };\n openRequest.onerror = error => reject(openRequest.error);\n });\n }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport '../flags';\nimport {env} from '../environment';\n\nimport {assert} from '../util';\nimport {arrayBufferToBase64String, base64StringToArrayBuffer, getModelArtifactsInfoForJSON} from './io_utils';\nimport {IORouter, IORouterRegistry} from './router_registry';\nimport {IOHandler, ModelArtifacts, ModelArtifactsInfo, ModelJSON, ModelStoreManager, SaveResult} from './types';\n\nconst PATH_SEPARATOR = '/';\nconst PATH_PREFIX = 'tensorflowjs_models';\nconst INFO_SUFFIX = 'info';\nconst MODEL_TOPOLOGY_SUFFIX = 'model_topology';\nconst WEIGHT_SPECS_SUFFIX = 'weight_specs';\nconst WEIGHT_DATA_SUFFIX = 'weight_data';\nconst MODEL_METADATA_SUFFIX = 'model_metadata';\n\n/**\n * Purge all tensorflow.js-saved model artifacts from local storage.\n *\n * @returns Paths of the models purged.\n */\nexport function purgeLocalStorageArtifacts(): string[] {\n if (!env().getBool('IS_BROWSER') || typeof window === 'undefined' ||\n typeof window.localStorage === 'undefined') {\n throw new Error(\n 'purgeLocalStorageModels() cannot proceed because local storage is ' +\n 'unavailable in the current environment.');\n }\n const LS = window.localStorage;\n const purgedModelPaths: string[] = [];\n for (let i = 0; i < LS.length; ++i) {\n const key = LS.key(i);\n const prefix = PATH_PREFIX + PATH_SEPARATOR;\n if (key.startsWith(prefix) && key.length > prefix.length) {\n LS.removeItem(key);\n const modelName = getModelPathFromKey(key);\n if (purgedModelPaths.indexOf(modelName) === -1) {\n purgedModelPaths.push(modelName);\n }\n }\n }\n return purgedModelPaths;\n}\n\ntype LocalStorageKeys = {\n /** Key of the localStorage entry storing `ModelArtifactsInfo`. */\n info: string,\n /**\n * Key of the localStorage entry storing the 'modelTopology' key of\n * `model.json`\n */\n topology: string,\n /**\n * Key of the localStorage entry storing the `weightsManifest.weights` entries\n * of `model.json`\n */\n weightSpecs: string,\n /** Key of the localStorage entry storing the weight data in Base64 */\n weightData: string,\n /**\n * Key of the localStorage entry storing the remaining fields of `model.json`\n * @see {@link ModelMetadata}\n */\n modelMetadata: string,\n};\n\ntype ModelMetadata = Omit;\n\nfunction getModelKeys(path: string): LocalStorageKeys {\n return {\n info: [PATH_PREFIX, path, INFO_SUFFIX].join(PATH_SEPARATOR),\n topology: [PATH_PREFIX, path, MODEL_TOPOLOGY_SUFFIX].join(PATH_SEPARATOR),\n weightSpecs: [PATH_PREFIX, path, WEIGHT_SPECS_SUFFIX].join(PATH_SEPARATOR),\n weightData: [PATH_PREFIX, path, WEIGHT_DATA_SUFFIX].join(PATH_SEPARATOR),\n modelMetadata:\n [PATH_PREFIX, path, MODEL_METADATA_SUFFIX].join(PATH_SEPARATOR)\n };\n}\n\nfunction removeItems(keys: LocalStorageKeys): void {\n for (const key of Object.values(keys)) {\n window.localStorage.removeItem(key);\n }\n}\n\n/**\n * Get model path from a local-storage key.\n *\n * E.g., 'tensorflowjs_models/my/model/1/info' --> 'my/model/1'\n *\n * @param key\n */\nfunction getModelPathFromKey(key: string) {\n const items = key.split(PATH_SEPARATOR);\n if (items.length < 3) {\n throw new Error(`Invalid key format: ${key}`);\n }\n return items.slice(1, items.length - 1).join(PATH_SEPARATOR);\n}\n\nfunction maybeStripScheme(key: string) {\n return key.startsWith(BrowserLocalStorage.URL_SCHEME) ?\n key.slice(BrowserLocalStorage.URL_SCHEME.length) :\n key;\n}\n\n/**\n * IOHandler subclass: Browser Local Storage.\n *\n * See the doc string to `browserLocalStorage` for more details.\n */\nexport class BrowserLocalStorage implements IOHandler {\n protected readonly LS: Storage;\n protected readonly modelPath: string;\n protected readonly keys: LocalStorageKeys;\n\n static readonly URL_SCHEME = 'localstorage://';\n\n constructor(modelPath: string) {\n if (!env().getBool('IS_BROWSER') || typeof window === 'undefined' ||\n typeof window.localStorage === 'undefined') {\n // TODO(cais): Add more info about what IOHandler subtypes are\n // available.\n // Maybe point to a doc page on the web and/or automatically determine\n // the available IOHandlers and print them in the error message.\n throw new Error(\n 'The current environment does not support local storage.');\n }\n this.LS = window.localStorage;\n\n if (modelPath == null || !modelPath) {\n throw new Error(\n 'For local storage, modelPath must not be null, undefined or empty.');\n }\n this.modelPath = modelPath;\n this.keys = getModelKeys(this.modelPath);\n }\n\n /**\n * Save model artifacts to browser local storage.\n *\n * See the documentation to `browserLocalStorage` for details on the saved\n * artifacts.\n *\n * @param modelArtifacts The model artifacts to be stored.\n * @returns An instance of SaveResult.\n */\n async save(modelArtifacts: ModelArtifacts): Promise {\n if (modelArtifacts.modelTopology instanceof ArrayBuffer) {\n throw new Error(\n 'BrowserLocalStorage.save() does not support saving model topology ' +\n 'in binary formats yet.');\n } else {\n const topology = JSON.stringify(modelArtifacts.modelTopology);\n const weightSpecs = JSON.stringify(modelArtifacts.weightSpecs);\n\n const modelArtifactsInfo: ModelArtifactsInfo =\n getModelArtifactsInfoForJSON(modelArtifacts);\n\n try {\n this.LS.setItem(this.keys.info, JSON.stringify(modelArtifactsInfo));\n this.LS.setItem(this.keys.topology, topology);\n this.LS.setItem(this.keys.weightSpecs, weightSpecs);\n this.LS.setItem(\n this.keys.weightData,\n arrayBufferToBase64String(modelArtifacts.weightData));\n\n // Note that JSON.stringify doesn't write out keys that have undefined\n // values, so for some keys, we set undefined instead of a null-ish\n // value.\n const metadata: Required = {\n format: modelArtifacts.format,\n generatedBy: modelArtifacts.generatedBy,\n convertedBy: modelArtifacts.convertedBy,\n signature: modelArtifacts.signature != null ?\n modelArtifacts.signature :\n undefined,\n userDefinedMetadata: modelArtifacts.userDefinedMetadata != null ?\n modelArtifacts.userDefinedMetadata :\n undefined,\n modelInitializer: modelArtifacts.modelInitializer != null ?\n modelArtifacts.modelInitializer :\n undefined,\n trainingConfig: modelArtifacts.trainingConfig != null ?\n modelArtifacts.trainingConfig :\n undefined\n };\n this.LS.setItem(this.keys.modelMetadata, JSON.stringify(metadata));\n\n return {modelArtifactsInfo};\n } catch (err) {\n // If saving failed, clean up all items saved so far.\n removeItems(this.keys);\n\n throw new Error(\n `Failed to save model '${this.modelPath}' to local storage: ` +\n `size quota being exceeded is a possible cause of this failure: ` +\n `modelTopologyBytes=${modelArtifactsInfo.modelTopologyBytes}, ` +\n `weightSpecsBytes=${modelArtifactsInfo.weightSpecsBytes}, ` +\n `weightDataBytes=${modelArtifactsInfo.weightDataBytes}.`);\n }\n }\n }\n\n /**\n * Load a model from local storage.\n *\n * See the documentation to `browserLocalStorage` for details on the saved\n * artifacts.\n *\n * @returns The loaded model (if loading succeeds).\n */\n async load(): Promise {\n const info =\n JSON.parse(this.LS.getItem(this.keys.info)) as ModelArtifactsInfo;\n if (info == null) {\n throw new Error(\n `In local storage, there is no model with name '${this.modelPath}'`);\n }\n\n if (info.modelTopologyType !== 'JSON') {\n throw new Error(\n 'BrowserLocalStorage does not support loading non-JSON model ' +\n 'topology yet.');\n }\n\n const out: ModelArtifacts = {};\n\n // Load topology.\n const topology = JSON.parse(this.LS.getItem(this.keys.topology));\n if (topology == null) {\n throw new Error(\n `In local storage, the topology of model '${this.modelPath}' ` +\n `is missing.`);\n }\n out.modelTopology = topology;\n\n // Load weight specs.\n const weightSpecs = JSON.parse(this.LS.getItem(this.keys.weightSpecs));\n if (weightSpecs == null) {\n throw new Error(\n `In local storage, the weight specs of model '${this.modelPath}' ` +\n `are missing.`);\n }\n out.weightSpecs = weightSpecs;\n\n // Load meta-data fields.\n const metadataString = this.LS.getItem(this.keys.modelMetadata);\n if (metadataString != null) {\n const metadata = JSON.parse(metadataString) as ModelMetadata;\n out.format = metadata.format;\n out.generatedBy = metadata.generatedBy;\n out.convertedBy = metadata.convertedBy;\n if (metadata.signature != null) {\n out.signature = metadata.signature;\n }\n if (metadata.userDefinedMetadata != null) {\n out.userDefinedMetadata = metadata.userDefinedMetadata;\n }\n if (metadata.modelInitializer != null) {\n out.modelInitializer = metadata.modelInitializer;\n }\n if (metadata.trainingConfig != null) {\n out.trainingConfig = metadata.trainingConfig;\n }\n }\n\n // Load weight data.\n const weightDataBase64 = this.LS.getItem(this.keys.weightData);\n if (weightDataBase64 == null) {\n throw new Error(\n `In local storage, the binary weight values of model ` +\n `'${this.modelPath}' are missing.`);\n }\n out.weightData = base64StringToArrayBuffer(weightDataBase64);\n\n return out;\n }\n}\n\nexport const localStorageRouter: IORouter = (url: string|string[]) => {\n if (!env().getBool('IS_BROWSER')) {\n return null;\n } else {\n if (!Array.isArray(url) && url.startsWith(BrowserLocalStorage.URL_SCHEME)) {\n return browserLocalStorage(\n url.slice(BrowserLocalStorage.URL_SCHEME.length));\n } else {\n return null;\n }\n }\n};\nIORouterRegistry.registerSaveRouter(localStorageRouter);\nIORouterRegistry.registerLoadRouter(localStorageRouter);\n\n/**\n * Factory function for local storage IOHandler.\n *\n * This `IOHandler` supports both `save` and `load`.\n *\n * For each model's saved artifacts, four items are saved to local storage.\n * - `${PATH_SEPARATOR}/${modelPath}/info`: Contains meta-info about the\n * model, such as date saved, type of the topology, size in bytes, etc.\n * - `${PATH_SEPARATOR}/${modelPath}/topology`: Model topology. For Keras-\n * style models, this is a stringized JSON.\n * - `${PATH_SEPARATOR}/${modelPath}/weight_specs`: Weight specs of the\n * model, can be used to decode the saved binary weight values (see\n * item below).\n * - `${PATH_SEPARATOR}/${modelPath}/weight_data`: Concatenated binary\n * weight values, stored as a base64-encoded string.\n *\n * Saving may throw an `Error` if the total size of the artifacts exceed the\n * browser-specific quota.\n *\n * @param modelPath A unique identifier for the model to be saved. Must be a\n * non-empty string.\n * @returns An instance of `IOHandler`, which can be used with, e.g.,\n * `tf.Model.save`.\n */\nexport function browserLocalStorage(modelPath: string): IOHandler {\n return new BrowserLocalStorage(modelPath);\n}\n\nexport class BrowserLocalStorageManager implements ModelStoreManager {\n private readonly LS: Storage;\n\n constructor() {\n assert(\n env().getBool('IS_BROWSER'),\n () => 'Current environment is not a web browser');\n assert(\n typeof window === 'undefined' ||\n typeof window.localStorage !== 'undefined',\n () => 'Current browser does not appear to support localStorage');\n this.LS = window.localStorage;\n }\n\n async listModels(): Promise<{[path: string]: ModelArtifactsInfo}> {\n const out: {[path: string]: ModelArtifactsInfo} = {};\n const prefix = PATH_PREFIX + PATH_SEPARATOR;\n const suffix = PATH_SEPARATOR + INFO_SUFFIX;\n for (let i = 0; i < this.LS.length; ++i) {\n const key = this.LS.key(i);\n if (key.startsWith(prefix) && key.endsWith(suffix)) {\n const modelPath = getModelPathFromKey(key);\n out[modelPath] = JSON.parse(this.LS.getItem(key)) as ModelArtifactsInfo;\n }\n }\n return out;\n }\n\n async removeModel(path: string): Promise {\n path = maybeStripScheme(path);\n const keys = getModelKeys(path);\n if (this.LS.getItem(keys.info) == null) {\n throw new Error(`Cannot find model at path '${path}'`);\n }\n const info = JSON.parse(this.LS.getItem(keys.info)) as ModelArtifactsInfo;\n removeItems(keys);\n return info;\n }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * Classes and functions for model management across multiple storage mediums.\n *\n * Supported client actions:\n * - Listing models on all registered storage mediums.\n * - Remove model by URL from any registered storage mediums, by using URL\n * string.\n * - Moving or copying model from one path to another in the same medium or from\n * one medium to another, by using URL strings.\n */\n\nimport {assert} from '../util';\n\nimport {IORouterRegistry} from './router_registry';\nimport {ModelArtifactsInfo, ModelStoreManager} from './types';\n\nconst URL_SCHEME_SUFFIX = '://';\n\nexport class ModelStoreManagerRegistry {\n // Singleton instance.\n private static instance: ModelStoreManagerRegistry;\n\n private managers: {[scheme: string]: ModelStoreManager};\n\n private constructor() {\n this.managers = {};\n }\n\n private static getInstance(): ModelStoreManagerRegistry {\n if (ModelStoreManagerRegistry.instance == null) {\n ModelStoreManagerRegistry.instance = new ModelStoreManagerRegistry();\n }\n return ModelStoreManagerRegistry.instance;\n }\n\n /**\n * Register a save-handler router.\n *\n * @param saveRouter A function that maps a URL-like string onto an instance\n * of `IOHandler` with the `save` method defined or `null`.\n */\n static registerManager(scheme: string, manager: ModelStoreManager) {\n assert(scheme != null, () => 'scheme must not be undefined or null.');\n if (scheme.endsWith(URL_SCHEME_SUFFIX)) {\n scheme = scheme.slice(0, scheme.indexOf(URL_SCHEME_SUFFIX));\n }\n assert(scheme.length > 0, () => 'scheme must not be an empty string.');\n const registry = ModelStoreManagerRegistry.getInstance();\n assert(\n registry.managers[scheme] == null,\n () => `A model store manager is already registered for scheme '${\n scheme}'.`);\n registry.managers[scheme] = manager;\n }\n\n static getManager(scheme: string): ModelStoreManager {\n const manager = this.getInstance().managers[scheme];\n if (manager == null) {\n throw new Error(`Cannot find model manager for scheme '${scheme}'`);\n }\n return manager;\n }\n\n static getSchemes(): string[] {\n return Object.keys(this.getInstance().managers);\n }\n}\n\n/**\n * Helper method for parsing a URL string into a scheme and a path.\n *\n * @param url E.g., 'localstorage://my-model'\n * @returns A dictionary with two fields: scheme and path.\n * Scheme: e.g., 'localstorage' in the example above.\n * Path: e.g., 'my-model' in the example above.\n */\nfunction parseURL(url: string): {scheme: string, path: string} {\n if (url.indexOf(URL_SCHEME_SUFFIX) === -1) {\n throw new Error(\n `The url string provided does not contain a scheme. ` +\n `Supported schemes are: ` +\n `${ModelStoreManagerRegistry.getSchemes().join(',')}`);\n }\n return {\n scheme: url.split(URL_SCHEME_SUFFIX)[0],\n path: url.split(URL_SCHEME_SUFFIX)[1],\n };\n}\n\nasync function cloneModelInternal(\n sourceURL: string, destURL: string,\n deleteSource = false): Promise {\n assert(\n sourceURL !== destURL,\n () => `Old path and new path are the same: '${sourceURL}'`);\n\n const loadHandlers = IORouterRegistry.getLoadHandlers(sourceURL);\n assert(\n loadHandlers.length > 0,\n () => `Copying failed because no load handler is found for source URL ${\n sourceURL}.`);\n assert(\n loadHandlers.length < 2,\n () => `Copying failed because more than one (${loadHandlers.length}) ` +\n `load handlers for source URL ${sourceURL}.`);\n const loadHandler = loadHandlers[0];\n\n const saveHandlers = IORouterRegistry.getSaveHandlers(destURL);\n assert(\n saveHandlers.length > 0,\n () => `Copying failed because no save handler is found for destination ` +\n `URL ${destURL}.`);\n assert(\n saveHandlers.length < 2,\n () => `Copying failed because more than one (${loadHandlers.length}) ` +\n `save handlers for destination URL ${destURL}.`);\n const saveHandler = saveHandlers[0];\n\n const sourceScheme = parseURL(sourceURL).scheme;\n const sourcePath = parseURL(sourceURL).path;\n const sameMedium = sourceScheme === parseURL(sourceURL).scheme;\n\n const modelArtifacts = await loadHandler.load();\n\n // If moving within the same storage medium, remove the old model as soon as\n // the loading is done. Without doing this, it is possible that the combined\n // size of the two models will cause the cloning to fail.\n if (deleteSource && sameMedium) {\n await ModelStoreManagerRegistry.getManager(sourceScheme)\n .removeModel(sourcePath);\n }\n\n const saveResult = await saveHandler.save(modelArtifacts);\n\n // If moving between mediums, the deletion is done after the save succeeds.\n // This guards against the case in which saving to the destination medium\n // fails.\n if (deleteSource && !sameMedium) {\n await ModelStoreManagerRegistry.getManager(sourceScheme)\n .removeModel(sourcePath);\n }\n\n return saveResult.modelArtifactsInfo;\n}\n\n/**\n * List all models stored in registered storage mediums.\n *\n * For a web browser environment, the registered mediums are Local Storage and\n * IndexedDB.\n *\n * ```js\n * // First create and save a model.\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n * {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * await model.save('localstorage://demo/management/model1');\n *\n * // Then list existing models.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Delete the model.\n * await tf.io.removeModel('localstorage://demo/management/model1');\n *\n * // List models again.\n * console.log(JSON.stringify(await tf.io.listModels()));\n * ```\n *\n * @returns A `Promise` of a dictionary mapping URLs of existing models to\n * their model artifacts info. URLs include medium-specific schemes, e.g.,\n * 'indexeddb://my/model/1'. Model artifacts info include type of the\n * model's topology, byte sizes of the topology, weights, etc.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Management',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nasync function listModels(): Promise<{[url: string]: ModelArtifactsInfo}> {\n const schemes = ModelStoreManagerRegistry.getSchemes();\n const out: {[url: string]: ModelArtifactsInfo} = {};\n for (const scheme of schemes) {\n const schemeOut =\n await ModelStoreManagerRegistry.getManager(scheme).listModels();\n for (const path in schemeOut) {\n const url = scheme + URL_SCHEME_SUFFIX + path;\n out[url] = schemeOut[path];\n }\n }\n return out;\n}\n\n/**\n * Remove a model specified by URL from a reigstered storage medium.\n *\n * ```js\n * // First create and save a model.\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n * {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * await model.save('localstorage://demo/management/model1');\n *\n * // Then list existing models.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Delete the model.\n * await tf.io.removeModel('localstorage://demo/management/model1');\n *\n * // List models again.\n * console.log(JSON.stringify(await tf.io.listModels()));\n * ```\n *\n * @param url A URL to a stored model, with a scheme prefix, e.g.,\n * 'localstorage://my-model-1', 'indexeddb://my/model/2'.\n * @returns ModelArtifactsInfo of the deleted model (if and only if deletion\n * is successful).\n * @throws Error if deletion fails, e.g., if no model exists at `path`.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Management',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nasync function removeModel(url: string): Promise {\n const schemeAndPath = parseURL(url);\n const manager = ModelStoreManagerRegistry.getManager(schemeAndPath.scheme);\n return manager.removeModel(schemeAndPath.path);\n}\n\n/**\n * Copy a model from one URL to another.\n *\n * This function supports:\n *\n * 1. Copying within a storage medium, e.g.,\n * `tf.io.copyModel('localstorage://model-1', 'localstorage://model-2')`\n * 2. Copying between two storage mediums, e.g.,\n * `tf.io.copyModel('localstorage://model-1', 'indexeddb://model-1')`\n *\n * ```js\n * // First create and save a model.\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n * {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * await model.save('localstorage://demo/management/model1');\n *\n * // Then list existing models.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Copy the model, from Local Storage to IndexedDB.\n * await tf.io.copyModel(\n * 'localstorage://demo/management/model1',\n * 'indexeddb://demo/management/model1');\n *\n * // List models again.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Remove both models.\n * await tf.io.removeModel('localstorage://demo/management/model1');\n * await tf.io.removeModel('indexeddb://demo/management/model1');\n * ```\n *\n * @param sourceURL Source URL of copying.\n * @param destURL Destination URL of copying.\n * @returns ModelArtifactsInfo of the copied model (if and only if copying\n * is successful).\n * @throws Error if copying fails, e.g., if no model exists at `sourceURL`, or\n * if `oldPath` and `newPath` are identical.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Management',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nasync function copyModel(\n sourceURL: string, destURL: string): Promise {\n const deleteSource = false;\n return cloneModelInternal(sourceURL, destURL, deleteSource);\n}\n\n/**\n * Move a model from one URL to another.\n *\n * This function supports:\n *\n * 1. Moving within a storage medium, e.g.,\n * `tf.io.moveModel('localstorage://model-1', 'localstorage://model-2')`\n * 2. Moving between two storage mediums, e.g.,\n * `tf.io.moveModel('localstorage://model-1', 'indexeddb://model-1')`\n *\n * ```js\n * // First create and save a model.\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n * {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * await model.save('localstorage://demo/management/model1');\n *\n * // Then list existing models.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Move the model, from Local Storage to IndexedDB.\n * await tf.io.moveModel(\n * 'localstorage://demo/management/model1',\n * 'indexeddb://demo/management/model1');\n *\n * // List models again.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Remove the moved model.\n * await tf.io.removeModel('indexeddb://demo/management/model1');\n * ```\n *\n * @param sourceURL Source URL of moving.\n * @param destURL Destination URL of moving.\n * @returns ModelArtifactsInfo of the copied model (if and only if copying\n * is successful).\n * @throws Error if moving fails, e.g., if no model exists at `sourceURL`, or\n * if `oldPath` and `newPath` are identical.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Management',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nasync function moveModel(\n sourceURL: string, destURL: string): Promise {\n const deleteSource = true;\n return cloneModelInternal(sourceURL, destURL, deleteSource);\n}\n\nexport {moveModel, copyModel, removeModel, listModels};\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport '../flags';\n\nimport {env} from '../environment';\nimport {BrowserIndexedDB, BrowserIndexedDBManager} from '../io/indexed_db';\nimport {BrowserLocalStorage, BrowserLocalStorageManager} from '../io/local_storage';\nimport {ModelStoreManagerRegistry} from '../io/model_management';\n\nimport {Platform} from './platform';\n\nexport class PlatformBrowser implements Platform {\n // According to the spec, the built-in encoder can do only UTF-8 encoding.\n // https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder/TextEncoder\n private textEncoder: TextEncoder;\n\n fetch(path: string, init?: RequestInit): Promise {\n return fetch(path, init);\n }\n\n now(): number {\n return performance.now();\n }\n\n encode(text: string, encoding: string): Uint8Array {\n if (encoding !== 'utf-8' && encoding !== 'utf8') {\n throw new Error(\n `Browser's encoder only supports utf-8, but got ${encoding}`);\n }\n if (this.textEncoder == null) {\n this.textEncoder = new TextEncoder();\n }\n return this.textEncoder.encode(text);\n }\n decode(bytes: Uint8Array, encoding: string): string {\n return new TextDecoder(encoding).decode(bytes);\n }\n}\n\nif (env().get('IS_BROWSER')) {\n env().setPlatform('browser', new PlatformBrowser());\n\n // Register LocalStorage IOHandler\n try {\n ModelStoreManagerRegistry.registerManager(\n BrowserLocalStorage.URL_SCHEME, new BrowserLocalStorageManager());\n } catch (err) {\n }\n\n // Register IndexedDB IOHandler\n try {\n ModelStoreManagerRegistry.registerManager(\n BrowserIndexedDB.URL_SCHEME, new BrowserIndexedDBManager());\n } catch (err) {\n }\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {env} from '../environment';\n\nimport {Platform} from './platform';\n\n// We are wrapping this within an object so it can be stubbed by Jasmine.\nexport const getNodeFetch = {\n // tslint:disable-next-line:no-require-imports\n importFetch: () => require('node-fetch')\n};\n\ntype FetchFn = (url: string, init?: RequestInit) => Promise;\nlet systemFetch: FetchFn;\n// These getters and setters are for testing so we don't export a mutable\n// variable.\nexport function resetSystemFetch() {\n systemFetch = null;\n}\nexport function setSystemFetch(fetchFn: FetchFn) {\n systemFetch = fetchFn;\n}\nexport function getSystemFetch(): FetchFn {\n return systemFetch;\n}\n\nexport class PlatformNode implements Platform {\n private textEncoder: TextEncoder;\n // tslint:disable-next-line:no-any\n util: any;\n\n constructor() {\n // tslint:disable-next-line:no-require-imports\n this.util = require('util');\n // According to the spec, the built-in encoder can do only UTF-8 encoding.\n // https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder/TextEncoder\n this.textEncoder = new this.util.TextEncoder();\n }\n\n fetch(path: string, requestInits?: RequestInit): Promise {\n if (env().global.fetch != null) {\n return env().global.fetch(path, requestInits);\n }\n\n if (systemFetch == null) {\n systemFetch = getNodeFetch.importFetch();\n }\n return systemFetch(path, requestInits);\n }\n\n now(): number {\n const time = process.hrtime();\n return time[0] * 1000 + time[1] / 1000000;\n }\n\n encode(text: string, encoding: string): Uint8Array {\n if (encoding !== 'utf-8' && encoding !== 'utf8') {\n throw new Error(\n `Node built-in encoder only supports utf-8, but got ${encoding}`);\n }\n return this.textEncoder.encode(text);\n }\n decode(bytes: Uint8Array, encoding: string): string {\n if (bytes.length === 0) {\n return '';\n }\n return new this.util.TextDecoder(encoding).decode(bytes);\n }\n}\n\nif (env().get('IS_NODE')) {\n env().setPlatform('node', new PlatformNode());\n}\n", "/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {TensorBuffer} from '../tensor';\nimport {DataType, DataTypeMap, Rank, ShapeMap} from '../types';\nimport * as util from '../util';\n\n/**\n * Creates an empty `tf.TensorBuffer` with the specified `shape` and `dtype`.\n *\n * The values are stored in CPU as `TypedArray`. Fill the buffer using\n * `buffer.set()`, or by modifying directly `buffer.values`.\n *\n * When done, call `buffer.toTensor()` to get an immutable `tf.Tensor` with\n * those values.\n *\n * ```js\n * // Create a buffer and set values at particular indices.\n * const buffer = tf.buffer([2, 2]);\n * buffer.set(3, 0, 0);\n * buffer.set(5, 1, 0);\n *\n * // Convert the buffer back to a tensor.\n * buffer.toTensor().print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param dtype The dtype of the buffer. Defaults to 'float32'.\n * @param values The values of the buffer as `TypedArray`. Defaults to\n * zeros.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function buffer(\n shape: ShapeMap[R], dtype: D = 'float32' as D,\n values?: DataTypeMap[D]): TensorBuffer {\n dtype = dtype || 'float32' as D;\n util.assertNonNegativeIntegerDimensions(shape);\n return new TensorBuffer(shape, dtype, values);\n}\n", "/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Cast, CastAttrs, CastInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {DataType, TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Casts a `tf.Tensor` to a new dtype.\n *\n * ```js\n * const x = tf.tensor1d([1.5, 2.5, 3]);\n * tf.cast(x, 'int32').print();\n * ```\n * @param x The input tensor to be casted.\n * @param dtype The dtype to cast the input tensor to.\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction cast_(x: T|TensorLike, dtype: DataType): T {\n const $x = convertToTensor(x, 'x', 'cast');\n\n // Sanity checks.\n if (!util.isValidDtype(dtype)) {\n throw new Error(`Failed to cast to unknown dtype ${dtype}`);\n }\n if (dtype === 'string' && $x.dtype !== 'string' ||\n dtype !== 'string' && $x.dtype === 'string') {\n throw new Error('Only strings can be casted to strings');\n }\n\n const inputs: CastInputs = {x: $x};\n const attrs: CastAttrs = {dtype};\n\n return ENGINE.runKernel(\n Cast, inputs as {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const cast = op({cast_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Identity, IdentityInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Creates a new tensor with the same values and shape as the specified\n * tensor.\n *\n * ```js\n * const x = tf.tensor([1, 2]);\n *\n * x.clone().print();\n * ```\n *\n * @param x The tensor to clone.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction clone_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'clone', 'string_or_numeric');\n const inputs: IdentityInputs = {x: $x};\n\n // Note this op is called tf.identity in python. Hence the kernel name used\n // here.\n return ENGINE.runKernel(Identity, inputs as {} as NamedTensorMap);\n}\n\nexport const clone = op({clone_});\n", "/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\n\n/**\n * Prints information about the `tf.Tensor` including its data.\n *\n * ```js\n * const verbose = true;\n * tf.tensor2d([1, 2, 3, 4], [2, 2]).print(verbose);\n * ```\n * @param x The tensor to be printed.\n * @param verbose Whether to print verbose information about the ` Tensor`,\n * including dtype and size.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function print(x: T, verbose = false): void {\n console.log(x.toString(verbose));\n}\n", "/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Required side effectful code for tfjs-core\n\n// Set up Engine and ENV\nimport {getOrMakeEngine} from './engine';\ngetOrMakeEngine();\n\n// Register backend-agnostic flags.\nimport './flags';\n// Register platforms\nimport './platforms/platform_browser';\nimport './platforms/platform_node';\n\n// Set up OpHandler\nimport {buffer} from './ops/buffer';\nimport {cast} from './ops/cast';\nimport {clone} from './ops/clone';\nimport {print} from './ops/print';\nimport {OpHandler, setOpHandler} from './tensor';\nconst opHandler: OpHandler = {\n buffer,\n cast,\n clone,\n print\n};\nsetOpHandler(opHandler);\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Importing local_storage and indexed_db is necessary for the routers to be\n// registered.\nimport './indexed_db';\nimport './local_storage';\n\nimport {browserFiles} from './browser_files';\nimport {browserHTTPRequest, http, isHTTPScheme} from './http';\nimport {concatenateArrayBuffers, decodeWeights, encodeWeights, getModelArtifactsForJSON, getModelArtifactsInfoForJSON} from './io_utils';\nimport {fromMemory, withSaveHandler} from './passthrough';\nimport {getLoadHandlers, getSaveHandlers, registerLoadRouter, registerSaveRouter} from './router_registry';\nimport {IOHandler, LoadHandler, LoadOptions, ModelArtifacts, ModelArtifactsInfo, ModelJSON, ModelStoreManager, OnProgressCallback, RequestDetails, SaveConfig, SaveHandler, SaveResult, TrainingConfig, WeightGroup, WeightsManifestConfig, WeightsManifestEntry} from './types';\nimport {loadWeights, weightsLoaderFactory} from './weights_loader';\n\nexport {copyModel, listModels, moveModel, removeModel} from './model_management';\nexport {\n browserFiles,\n browserHTTPRequest,\n concatenateArrayBuffers,\n decodeWeights,\n encodeWeights,\n fromMemory,\n getLoadHandlers,\n getModelArtifactsForJSON,\n getModelArtifactsInfoForJSON,\n getSaveHandlers,\n http,\n IOHandler,\n isHTTPScheme,\n LoadHandler,\n LoadOptions,\n loadWeights,\n ModelArtifacts,\n ModelArtifactsInfo,\n ModelJSON,\n ModelStoreManager,\n OnProgressCallback,\n registerLoadRouter,\n registerSaveRouter,\n RequestDetails,\n SaveConfig,\n SaveHandler,\n SaveResult,\n TrainingConfig,\n WeightGroup,\n weightsLoaderFactory,\n WeightsManifestConfig,\n WeightsManifestEntry,\n withSaveHandler\n};\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * IOHandlers related to files, such as browser-triggered file downloads,\n * user-selected files in browser.\n */\n\nimport '../flags';\nimport {env} from '../environment';\n\nimport {basename, concatenateArrayBuffers, getModelArtifactsForJSON, getModelArtifactsInfoForJSON, getModelJSONForModelArtifacts} from './io_utils';\nimport {IORouter, IORouterRegistry} from './router_registry';\nimport {IOHandler, ModelArtifacts, ModelJSON, SaveResult, WeightsManifestConfig, WeightsManifestEntry} from './types';\n\nconst DEFAULT_FILE_NAME_PREFIX = 'model';\nconst DEFAULT_JSON_EXTENSION_NAME = '.json';\nconst DEFAULT_WEIGHT_DATA_EXTENSION_NAME = '.weights.bin';\n\nfunction defer(f: () => T): Promise {\n return new Promise(resolve => setTimeout(resolve)).then(f);\n}\n\nexport class BrowserDownloads implements IOHandler {\n private readonly modelJsonFileName: string;\n private readonly weightDataFileName: string;\n private readonly modelJsonAnchor: HTMLAnchorElement;\n private readonly weightDataAnchor: HTMLAnchorElement;\n\n static readonly URL_SCHEME = 'downloads://';\n\n constructor(fileNamePrefix?: string) {\n if (!env().getBool('IS_BROWSER')) {\n // TODO(cais): Provide info on what IOHandlers are available under the\n // current environment.\n throw new Error(\n 'browserDownloads() cannot proceed because the current environment ' +\n 'is not a browser.');\n }\n\n if (fileNamePrefix.startsWith(BrowserDownloads.URL_SCHEME)) {\n fileNamePrefix = fileNamePrefix.slice(BrowserDownloads.URL_SCHEME.length);\n }\n if (fileNamePrefix == null || fileNamePrefix.length === 0) {\n fileNamePrefix = DEFAULT_FILE_NAME_PREFIX;\n }\n\n this.modelJsonFileName = fileNamePrefix + DEFAULT_JSON_EXTENSION_NAME;\n this.weightDataFileName =\n fileNamePrefix + DEFAULT_WEIGHT_DATA_EXTENSION_NAME;\n }\n\n async save(modelArtifacts: ModelArtifacts): Promise {\n if (typeof (document) === 'undefined') {\n throw new Error(\n 'Browser downloads are not supported in ' +\n 'this environment since `document` is not present');\n }\n const weightsURL = window.URL.createObjectURL(new Blob(\n [modelArtifacts.weightData], {type: 'application/octet-stream'}));\n\n if (modelArtifacts.modelTopology instanceof ArrayBuffer) {\n throw new Error(\n 'BrowserDownloads.save() does not support saving model topology ' +\n 'in binary formats yet.');\n } else {\n const weightsManifest: WeightsManifestConfig = [{\n paths: ['./' + this.weightDataFileName],\n weights: modelArtifacts.weightSpecs\n }];\n const modelJSON: ModelJSON =\n getModelJSONForModelArtifacts(modelArtifacts, weightsManifest);\n\n const modelJsonURL = window.URL.createObjectURL(\n new Blob([JSON.stringify(modelJSON)], {type: 'application/json'}));\n\n // If anchor elements are not provided, create them without attaching them\n // to parents, so that the downloaded file names can be controlled.\n const jsonAnchor = this.modelJsonAnchor == null ?\n document.createElement('a') :\n this.modelJsonAnchor;\n jsonAnchor.download = this.modelJsonFileName;\n jsonAnchor.href = modelJsonURL;\n // Trigger downloads by evoking a click event on the download anchors.\n // When multiple downloads are started synchronously, Firefox will only\n // save the last one.\n await defer(() => jsonAnchor.dispatchEvent(new MouseEvent('click')));\n\n if (modelArtifacts.weightData != null) {\n const weightDataAnchor = this.weightDataAnchor == null ?\n document.createElement('a') :\n this.weightDataAnchor;\n weightDataAnchor.download = this.weightDataFileName;\n weightDataAnchor.href = weightsURL;\n await defer(\n () => weightDataAnchor.dispatchEvent(new MouseEvent('click')));\n }\n\n return {modelArtifactsInfo: getModelArtifactsInfoForJSON(modelArtifacts)};\n }\n }\n}\n\nclass BrowserFiles implements IOHandler {\n private readonly jsonFile: File;\n private readonly weightsFiles: File[];\n\n constructor(files: File[]) {\n if (files == null || files.length < 1) {\n throw new Error(\n `When calling browserFiles, at least 1 file is required, ` +\n `but received ${files}`);\n }\n this.jsonFile = files[0];\n this.weightsFiles = files.slice(1);\n }\n\n async load(): Promise {\n return new Promise((resolve, reject) => {\n const jsonReader = new FileReader();\n jsonReader.onload = (event: Event) => {\n // tslint:disable-next-line:no-any\n const modelJSON = JSON.parse((event.target as any).result) as ModelJSON;\n\n const modelTopology = modelJSON.modelTopology;\n if (modelTopology == null) {\n reject(new Error(`modelTopology field is missing from file ${\n this.jsonFile.name}`));\n return;\n }\n\n const weightsManifest = modelJSON.weightsManifest;\n if (weightsManifest == null) {\n reject(new Error(`weightManifest field is missing from file ${\n this.jsonFile.name}`));\n return;\n }\n\n if (this.weightsFiles.length === 0) {\n resolve({modelTopology});\n return;\n }\n\n const modelArtifactsPromise = getModelArtifactsForJSON(\n modelJSON, (weightsManifest) => this.loadWeights(weightsManifest));\n resolve(modelArtifactsPromise);\n };\n\n jsonReader.onerror = error => reject(\n `Failed to read model topology and weights manifest JSON ` +\n `from file '${this.jsonFile.name}'. BrowserFiles supports loading ` +\n `Keras-style tf.Model artifacts only.`);\n jsonReader.readAsText(this.jsonFile);\n });\n }\n\n private loadWeights(weightsManifest: WeightsManifestConfig): Promise<[\n /* weightSpecs */ WeightsManifestEntry[], /* weightData */ ArrayBuffer\n ]> {\n const weightSpecs: WeightsManifestEntry[] = [];\n const paths: string[] = [];\n for (const entry of weightsManifest) {\n weightSpecs.push(...entry.weights);\n paths.push(...entry.paths);\n }\n\n const pathToFile: {[path: string]: File} =\n this.checkManifestAndWeightFiles(weightsManifest);\n\n const promises: Array> =\n paths.map(path => this.loadWeightsFile(path, pathToFile[path]));\n\n return Promise.all(promises).then(\n buffers => [weightSpecs, concatenateArrayBuffers(buffers)]);\n }\n\n private loadWeightsFile(path: string, file: File): Promise {\n return new Promise((resolve, reject) => {\n const weightFileReader = new FileReader();\n weightFileReader.onload = (event: Event) => {\n // tslint:disable-next-line:no-any\n const weightData = (event.target as any).result as ArrayBuffer;\n resolve(weightData);\n };\n weightFileReader.onerror = error =>\n reject(`Failed to weights data from file of path '${path}'.`);\n weightFileReader.readAsArrayBuffer(file);\n });\n }\n\n /**\n * Check the compatibility between weights manifest and weight files.\n */\n private checkManifestAndWeightFiles(manifest: WeightsManifestConfig):\n {[path: string]: File} {\n const basenames: string[] = [];\n const fileNames = this.weightsFiles.map(file => basename(file.name));\n const pathToFile: {[path: string]: File} = {};\n for (const group of manifest) {\n group.paths.forEach(path => {\n const pathBasename = basename(path);\n if (basenames.indexOf(pathBasename) !== -1) {\n throw new Error(\n `Duplicate file basename found in weights manifest: ` +\n `'${pathBasename}'`);\n }\n basenames.push(pathBasename);\n if (fileNames.indexOf(pathBasename) === -1) {\n throw new Error(\n `Weight file with basename '${pathBasename}' is not provided.`);\n } else {\n pathToFile[path] = this.weightsFiles[fileNames.indexOf(pathBasename)];\n }\n });\n }\n\n if (basenames.length !== this.weightsFiles.length) {\n throw new Error(\n `Mismatch in the number of files in weights manifest ` +\n `(${basenames.length}) and the number of weight files provided ` +\n `(${this.weightsFiles.length}).`);\n }\n return pathToFile;\n }\n}\n\nexport const browserDownloadsRouter: IORouter = (url: string|string[]) => {\n if (!env().getBool('IS_BROWSER')) {\n return null;\n } else {\n if (!Array.isArray(url) && url.startsWith(BrowserDownloads.URL_SCHEME)) {\n return browserDownloads(url.slice(BrowserDownloads.URL_SCHEME.length));\n } else {\n return null;\n }\n }\n};\nIORouterRegistry.registerSaveRouter(browserDownloadsRouter);\n\n/**\n * Creates an IOHandler that triggers file downloads from the browser.\n *\n * The returned `IOHandler` instance can be used as model exporting methods such\n * as `tf.Model.save` and supports only saving.\n *\n * ```js\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n * {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * const saveResult = await model.save('downloads://mymodel');\n * // This will trigger downloading of two files:\n * // 'mymodel.json' and 'mymodel.weights.bin'.\n * console.log(saveResult);\n * ```\n *\n * @param fileNamePrefix Prefix name of the files to be downloaded. For use with\n * `tf.Model`, `fileNamePrefix` should follow either of the following two\n * formats:\n * 1. `null` or `undefined`, in which case the default file\n * names will be used:\n * - 'model.json' for the JSON file containing the model topology and\n * weights manifest.\n * - 'model.weights.bin' for the binary file containing the binary weight\n * values.\n * 2. A single string or an Array of a single string, as the file name prefix.\n * For example, if `'foo'` is provided, the downloaded JSON\n * file and binary weights file will be named 'foo.json' and\n * 'foo.weights.bin', respectively.\n * @param config Additional configuration for triggering downloads.\n * @returns An instance of `BrowserDownloads` `IOHandler`.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Loading',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nexport function browserDownloads(fileNamePrefix = 'model'): IOHandler {\n return new BrowserDownloads(fileNamePrefix);\n}\n\n/**\n * Creates an IOHandler that loads model artifacts from user-selected files.\n *\n * This method can be used for loading from files such as user-selected files\n * in the browser.\n * When used in conjunction with `tf.loadLayersModel`, an instance of\n * `tf.LayersModel` (Keras-style) can be constructed from the loaded artifacts.\n *\n * ```js\n * // Note: This code snippet won't run properly without the actual file input\n * // elements in the HTML DOM.\n *\n * // Suppose there are two HTML file input (``)\n * // elements.\n * const uploadJSONInput = document.getElementById('upload-json');\n * const uploadWeightsInput = document.getElementById('upload-weights');\n * const model = await tf.loadLayersModel(tf.io.browserFiles(\n * [uploadJSONInput.files[0], uploadWeightsInput.files[0]]));\n * ```\n *\n * @param files `File`s to load from. Currently, this function supports only\n * loading from files that contain Keras-style models (i.e., `tf.Model`s), for\n * which an `Array` of `File`s is expected (in that order):\n * - A JSON file containing the model topology and weight manifest.\n * - Optionally, One or more binary files containing the binary weights.\n * These files must have names that match the paths in the `weightsManifest`\n * contained by the aforementioned JSON file, or errors will be thrown\n * during loading. These weights files have the same format as the ones\n * generated by `tensorflowjs_converter` that comes with the `tensorflowjs`\n * Python PIP package. If no weights files are provided, only the model\n * topology will be loaded from the JSON file above.\n * @returns An instance of `Files` `IOHandler`.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Loading',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nexport function browserFiles(files: File[]): IOHandler {\n return new BrowserFiles(files);\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {assert} from '../util';\n\nimport {OnProgressCallback} from './types';\n\n/**\n * Monitor Promise.all progress, fire onProgress callback function.\n *\n * @param promises Promise list going to be monitored\n * @param onProgress Callback function. Fired when a promise resolved.\n * @param startFraction Optional fraction start. Default to 0.\n * @param endFraction Optional fraction end. Default to 1.\n */\nexport function monitorPromisesProgress(\n promises: Array>, onProgress: OnProgressCallback,\n startFraction?: number, endFraction?: number) {\n checkPromises(promises);\n startFraction = startFraction == null ? 0 : startFraction;\n endFraction = endFraction == null ? 1 : endFraction;\n checkFraction(startFraction, endFraction);\n let resolvedPromise = 0;\n\n const registerMonitor = (promise: Promise<{}>) => {\n promise.then(value => {\n const fraction = startFraction +\n ++resolvedPromise / promises.length * (endFraction - startFraction);\n // pass fraction as parameter to callback function.\n onProgress(fraction);\n return value;\n });\n return promise;\n };\n\n function checkPromises(promises: Array>): void {\n assert(\n promises != null && Array.isArray(promises) && promises.length > 0,\n () => 'promises must be a none empty array');\n }\n\n function checkFraction(startFraction: number, endFraction: number): void {\n assert(\n startFraction >= 0 && startFraction <= 1,\n () => `Progress fraction must be in range [0, 1], but ` +\n `got startFraction ${startFraction}`);\n assert(\n endFraction >= 0 && endFraction <= 1,\n () => `Progress fraction must be in range [0, 1], but ` +\n `got endFraction ${endFraction}`);\n assert(\n endFraction >= startFraction,\n () => `startFraction must be no more than endFraction, but ` +\n `got startFraction ${startFraction} and endFraction ` +\n `${endFraction}`);\n }\n\n return Promise.all(promises.map(registerMonitor));\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env} from '../environment';\n\nimport {NamedTensorMap} from '../tensor_types';\nimport * as util from '../util';\nimport {decodeWeights} from './io_utils';\nimport {monitorPromisesProgress} from './progress';\nimport {DTYPE_VALUE_SIZE_MAP, LoadOptions, WeightsManifestConfig, WeightsManifestEntry} from './types';\n\n/**\n * Reads binary weights data from a number of URLs.\n *\n * @param fetchURLs URLs to send the HTTP requests at, using `fetch` calls.\n * @param requestOptions RequestInit (options) for the HTTP requests.\n * @param fetchFunc Optional overriding value for the `window.fetch` function.\n * @param onProgress Optional, progress callback function, fired periodically\n * before the load is completed.\n * @returns A `Promise` of an Array of `ArrayBuffer`. The Array has the same\n * length as `fetchURLs`.\n */\nexport async function loadWeightsAsArrayBuffer(\n fetchURLs: string[], loadOptions?: LoadOptions): Promise {\n if (loadOptions == null) {\n loadOptions = {};\n }\n\n const fetchFunc = loadOptions.fetchFunc == null ? env().platform.fetch :\n loadOptions.fetchFunc;\n\n // Create the requests for all of the weights in parallel.\n const requests = fetchURLs.map(\n fetchURL =>\n fetchFunc(fetchURL, loadOptions.requestInit, {isBinary: true}));\n\n const fetchStartFraction = 0;\n const fetchEndFraction = 0.5;\n\n const responses = loadOptions.onProgress == null ?\n await Promise.all(requests) :\n await monitorPromisesProgress(\n requests, loadOptions.onProgress, fetchStartFraction,\n fetchEndFraction);\n\n const bufferPromises = responses.map(response => response.arrayBuffer());\n\n const bufferStartFraction = 0.5;\n const bufferEndFraction = 1;\n\n const buffers = loadOptions.onProgress == null ?\n await Promise.all(bufferPromises) :\n await monitorPromisesProgress(\n bufferPromises, loadOptions.onProgress, bufferStartFraction,\n bufferEndFraction);\n return buffers;\n}\n\n/**\n * Reads a weights manifest JSON configuration, fetches the weights and\n * returns them as `Tensor`s.\n *\n * @param manifest The weights manifest JSON.\n * @param filePathPrefix The path prefix for filenames given in the manifest.\n * Defaults to the empty string.\n * @param weightNames The names of the weights to be fetched.\n */\nexport async function loadWeights(\n manifest: WeightsManifestConfig, filePathPrefix = '',\n weightNames?: string[],\n requestInit?: RequestInit): Promise {\n // TODO(nsthorat): Groups are currently fetched atomically. If you need a\n // single weight from a group, the whole group will be fetched. At a future\n // date, we should support fetching only the individual shards within a\n // group that are needed to reconstruct the requested weight.\n // TODO(cais): Use `decodeWeights` for implementation.\n\n const fetchWeights = (fetchUrls: string[]) =>\n loadWeightsAsArrayBuffer(fetchUrls, {requestInit});\n const loadWeights = weightsLoaderFactory(fetchWeights);\n\n return loadWeights(manifest, filePathPrefix, weightNames);\n}\n\n/**\n * Creates a function, which reads a weights manifest JSON configuration,\n * fetches the weight files using the specified function and returns them as\n * `Tensor`s.\n *\n * ```js\n * // example for creating a nodejs weight loader, which reads the weight files\n * // from disk using fs.readFileSync\n *\n * import * as fs from 'fs'\n *\n * const fetchWeightsFromDisk = (filePaths: string[]) =>\n * filePaths.map(filePath => fs.readFileSync(filePath).buffer)\n *\n * const loadWeights = tf.io.weightsLoaderFactory(fetchWeightsFromDisk)\n *\n * const manifest = JSON.parse(\n * fs.readFileSync('./my_model-weights_manifest').toString()\n * )\n * const weightMap = await loadWeights(manifest, './')\n * ```\n * @param fetchWeightsFunction The function used for fetching the weight files.\n * @returns Weight loading function.\n */\nexport function weightsLoaderFactory(\n fetchWeightsFunction: (fetchUrls: string[]) => Promise):\n (manifest: WeightsManifestConfig, filePathPrefix?: string,\n weightNames?: string[]) => Promise {\n return async(\n manifest: WeightsManifestConfig, filePathPrefix = '',\n weightNames?: string[]): Promise => {\n // Collect all the groups, weights, and their relative offsets to be\n // fetched.\n const groupIndicesToFetchMap = manifest.map(() => false);\n const groupWeightsToFetch: {\n [group: number]: Array<{\n manifestEntry: WeightsManifestEntry; groupOffset: number;\n sizeBytes: number;\n }>\n } = {};\n const weightsFound =\n weightNames != null ? weightNames.map(() => false) : [];\n const allManifestWeightNames: string[] = [];\n manifest.forEach((manifestGroupConfig, groupIndex) => {\n let groupOffset = 0;\n manifestGroupConfig.weights.forEach(weightsEntry => {\n const rawDtype = ('quantization' in weightsEntry) ?\n weightsEntry.quantization.dtype :\n weightsEntry.dtype;\n\n const weightsBytes = DTYPE_VALUE_SIZE_MAP[rawDtype] *\n util.sizeFromShape(weightsEntry.shape);\n\n const enqueueWeightsForFetchingFn = () => {\n groupIndicesToFetchMap[groupIndex] = true;\n if (groupWeightsToFetch[groupIndex] == null) {\n groupWeightsToFetch[groupIndex] = [];\n }\n\n groupWeightsToFetch[groupIndex].push({\n manifestEntry: weightsEntry,\n groupOffset,\n sizeBytes: weightsBytes\n });\n };\n\n if (weightNames != null) {\n weightNames.forEach((weightName, weightIndex) => {\n if (weightName === weightsEntry.name) {\n enqueueWeightsForFetchingFn();\n weightsFound[weightIndex] = true;\n }\n });\n } else {\n enqueueWeightsForFetchingFn();\n }\n\n allManifestWeightNames.push(weightsEntry.name);\n groupOffset += weightsBytes;\n });\n });\n\n if (!weightsFound.every(found => found)) {\n const weightsNotFound = weightNames.filter((_, i) => !weightsFound[i]);\n throw new Error(\n `Could not find weights in manifest with names: ` +\n `${weightsNotFound.join(', ')}. \\n` +\n `Manifest JSON has weights with names: ` +\n `${allManifestWeightNames.join(', ')}.`);\n }\n\n // Convert the one-hot boolean groupId => shouldFetch map to a list of group\n // IDs.\n const groupIndicesToFetch =\n groupIndicesToFetchMap.reduce((accumulator, shouldFetch, i) => {\n if (shouldFetch) {\n accumulator.push(i);\n }\n return accumulator;\n }, []);\n\n const fetchUrls: string[] = [];\n groupIndicesToFetch.forEach(i => {\n manifest[i].paths.forEach(filepath => {\n const fetchUrl = filePathPrefix +\n (!filePathPrefix.endsWith('/') ? '/' : '') + filepath;\n fetchUrls.push(fetchUrl);\n });\n });\n const buffers = await fetchWeightsFunction(fetchUrls);\n\n const weightsTensorMap: NamedTensorMap = {};\n let bufferIndexOffset = 0;\n groupIndicesToFetch.forEach(i => {\n const numBuffers = manifest[i].paths.length;\n\n let groupBytes = 0;\n for (let i = 0; i < numBuffers; i++) {\n groupBytes += buffers[bufferIndexOffset + i].byteLength;\n }\n\n // Create a buffer for the whole group.\n const groupBuffer = new ArrayBuffer(groupBytes);\n const groupByteBuffer = new Uint8Array(groupBuffer);\n let groupBufferOffset = 0;\n for (let i = 0; i < numBuffers; i++) {\n const buffer = new Uint8Array(buffers[bufferIndexOffset + i]);\n groupByteBuffer.set(buffer, groupBufferOffset);\n groupBufferOffset += buffer.byteLength;\n }\n\n const weightsEntries = groupWeightsToFetch[i];\n weightsEntries.forEach(weightsEntry => {\n const byteBuffer = groupBuffer.slice(\n weightsEntry.groupOffset,\n weightsEntry.groupOffset + weightsEntry.sizeBytes);\n const nameToTensorMap =\n decodeWeights(byteBuffer, [weightsEntry.manifestEntry]);\n for (const name in nameToTensorMap) {\n weightsTensorMap[name] = nameToTensorMap[name];\n }\n });\n\n bufferIndexOffset += numBuffers;\n });\n\n return weightsTensorMap;\n };\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * IOHandler implementations based on HTTP requests in the web browser.\n *\n * Uses [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).\n */\n\nimport {env} from '../environment';\n\nimport {assert} from '../util';\nimport {concatenateArrayBuffers, getModelArtifactsForJSON, getModelArtifactsInfoForJSON, getModelJSONForModelArtifacts} from './io_utils';\nimport {IORouter, IORouterRegistry} from './router_registry';\nimport {IOHandler, LoadOptions, ModelArtifacts, ModelJSON, OnProgressCallback, SaveResult, WeightsManifestConfig, WeightsManifestEntry} from './types';\nimport {loadWeightsAsArrayBuffer} from './weights_loader';\n\nconst OCTET_STREAM_MIME_TYPE = 'application/octet-stream';\nconst JSON_TYPE = 'application/json';\nexport class HTTPRequest implements IOHandler {\n protected readonly path: string;\n protected readonly requestInit: RequestInit;\n\n private readonly fetch: Function;\n private readonly weightUrlConverter: (weightName: string) => Promise;\n\n readonly DEFAULT_METHOD = 'POST';\n\n static readonly URL_SCHEME_REGEX = /^https?:\\/\\//;\n\n private readonly weightPathPrefix: string;\n private readonly onProgress: OnProgressCallback;\n\n constructor(path: string, loadOptions?: LoadOptions) {\n if (loadOptions == null) {\n loadOptions = {};\n }\n this.weightPathPrefix = loadOptions.weightPathPrefix;\n this.onProgress = loadOptions.onProgress;\n this.weightUrlConverter = loadOptions.weightUrlConverter;\n\n if (loadOptions.fetchFunc != null) {\n assert(\n typeof loadOptions.fetchFunc === 'function',\n () => 'Must pass a function that matches the signature of ' +\n '`fetch` (see ' +\n 'https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)');\n this.fetch = loadOptions.fetchFunc;\n } else {\n this.fetch = env().platform.fetch;\n }\n\n assert(\n path != null && path.length > 0,\n () => 'URL path for http must not be null, undefined or ' +\n 'empty.');\n\n if (Array.isArray(path)) {\n assert(\n path.length === 2,\n () => 'URL paths for http must have a length of 2, ' +\n `(actual length is ${path.length}).`);\n }\n this.path = path;\n\n if (loadOptions.requestInit != null &&\n loadOptions.requestInit.body != null) {\n throw new Error(\n 'requestInit is expected to have no pre-existing body, but has one.');\n }\n this.requestInit = loadOptions.requestInit || {};\n }\n\n async save(modelArtifacts: ModelArtifacts): Promise {\n if (modelArtifacts.modelTopology instanceof ArrayBuffer) {\n throw new Error(\n 'BrowserHTTPRequest.save() does not support saving model topology ' +\n 'in binary formats yet.');\n }\n\n const init = Object.assign({method: this.DEFAULT_METHOD}, this.requestInit);\n init.body = new FormData();\n\n const weightsManifest: WeightsManifestConfig = [{\n paths: ['./model.weights.bin'],\n weights: modelArtifacts.weightSpecs,\n }];\n const modelTopologyAndWeightManifest: ModelJSON =\n getModelJSONForModelArtifacts(modelArtifacts, weightsManifest);\n\n init.body.append(\n 'model.json',\n new Blob(\n [JSON.stringify(modelTopologyAndWeightManifest)],\n {type: JSON_TYPE}),\n 'model.json');\n\n if (modelArtifacts.weightData != null) {\n init.body.append(\n 'model.weights.bin',\n new Blob([modelArtifacts.weightData], {type: OCTET_STREAM_MIME_TYPE}),\n 'model.weights.bin');\n }\n\n const response = await this.fetch(this.path, init);\n\n if (response.ok) {\n return {\n modelArtifactsInfo: getModelArtifactsInfoForJSON(modelArtifacts),\n responses: [response],\n };\n } else {\n throw new Error(\n `BrowserHTTPRequest.save() failed due to HTTP response status ` +\n `${response.status}.`);\n }\n }\n\n /**\n * Load model artifacts via HTTP request(s).\n *\n * See the documentation to `tf.io.http` for details on the saved\n * artifacts.\n *\n * @returns The loaded model artifacts (if loading succeeds).\n */\n async load(): Promise {\n const modelConfigRequest = await this.fetch(this.path, this.requestInit);\n\n if (!modelConfigRequest.ok) {\n throw new Error(\n `Request to ${this.path} failed with status code ` +\n `${modelConfigRequest.status}. Please verify this URL points to ` +\n `the model JSON of the model to load.`);\n }\n let modelJSON: ModelJSON;\n try {\n modelJSON = await modelConfigRequest.json();\n } catch (e) {\n let message = `Failed to parse model JSON of response from ${this.path}.`;\n // TODO(nsthorat): Remove this after some time when we're comfortable that\n // .pb files are mostly gone.\n if (this.path.endsWith('.pb')) {\n message += ' Your path contains a .pb file extension. ' +\n 'Support for .pb models have been removed in TensorFlow.js 1.0 ' +\n 'in favor of .json models. You can re-convert your Python ' +\n 'TensorFlow model using the TensorFlow.js 1.0 conversion scripts ' +\n 'or you can convert your.pb models with the \\'pb2json\\'' +\n 'NPM script in the tensorflow/tfjs-converter repository.';\n } else {\n message += ' Please make sure the server is serving valid ' +\n 'JSON for this request.';\n }\n throw new Error(message);\n }\n\n // We do not allow both modelTopology and weightsManifest to be missing.\n const modelTopology = modelJSON.modelTopology;\n const weightsManifest = modelJSON.weightsManifest;\n if (modelTopology == null && weightsManifest == null) {\n throw new Error(\n `The JSON from HTTP path ${this.path} contains neither model ` +\n `topology or manifest for weights.`);\n }\n\n return getModelArtifactsForJSON(\n modelJSON, (weightsManifest) => this.loadWeights(weightsManifest));\n }\n\n private async loadWeights(weightsManifest: WeightsManifestConfig):\n Promise<[WeightsManifestEntry[], ArrayBuffer]> {\n const weightPath = Array.isArray(this.path) ? this.path[1] : this.path;\n const [prefix, suffix] = parseUrl(weightPath);\n const pathPrefix = this.weightPathPrefix || prefix;\n\n const weightSpecs = [];\n for (const entry of weightsManifest) {\n weightSpecs.push(...entry.weights);\n }\n\n const fetchURLs: string[] = [];\n const urlPromises: Array> = [];\n for (const weightsGroup of weightsManifest) {\n for (const path of weightsGroup.paths) {\n if (this.weightUrlConverter != null) {\n urlPromises.push(this.weightUrlConverter(path));\n } else {\n fetchURLs.push(pathPrefix + path + suffix);\n }\n }\n }\n\n if (this.weightUrlConverter) {\n fetchURLs.push(...await Promise.all(urlPromises));\n }\n\n const buffers = await loadWeightsAsArrayBuffer(fetchURLs, {\n requestInit: this.requestInit,\n fetchFunc: this.fetch,\n onProgress: this.onProgress\n });\n return [weightSpecs, concatenateArrayBuffers(buffers)];\n }\n}\n\n/**\n * Extract the prefix and suffix of the url, where the prefix is the path before\n * the last file, and suffix is the search params after the last file.\n * ```\n * const url = 'http://tfhub.dev/model/1/tensorflowjs_model.pb?tfjs-format=file'\n * [prefix, suffix] = parseUrl(url)\n * // prefix = 'http://tfhub.dev/model/1/'\n * // suffix = '?tfjs-format=file'\n * ```\n * @param url the model url to be parsed.\n */\nexport function parseUrl(url: string): [string, string] {\n const lastSlash = url.lastIndexOf('/');\n const lastSearchParam = url.lastIndexOf('?');\n const prefix = url.substring(0, lastSlash);\n const suffix =\n lastSearchParam > lastSlash ? url.substring(lastSearchParam) : '';\n return [prefix + '/', suffix];\n}\n\nexport function isHTTPScheme(url: string): boolean {\n return url.match(HTTPRequest.URL_SCHEME_REGEX) != null;\n}\n\nexport const httpRouter: IORouter =\n (url: string, loadOptions?: LoadOptions) => {\n if (typeof fetch === 'undefined' &&\n (loadOptions == null || loadOptions.fetchFunc == null)) {\n // `http` uses `fetch` or `node-fetch`, if one wants to use it in\n // an environment that is not the browser or node they have to setup a\n // global fetch polyfill.\n return null;\n } else {\n let isHTTP = true;\n if (Array.isArray(url)) {\n isHTTP = url.every(urlItem => isHTTPScheme(urlItem));\n } else {\n isHTTP = isHTTPScheme(url);\n }\n if (isHTTP) {\n return http(url, loadOptions);\n }\n }\n return null;\n };\nIORouterRegistry.registerSaveRouter(httpRouter);\nIORouterRegistry.registerLoadRouter(httpRouter);\n\n/**\n * Creates an IOHandler subtype that sends model artifacts to HTTP server.\n *\n * An HTTP request of the `multipart/form-data` mime type will be sent to the\n * `path` URL. The form data includes artifacts that represent the topology\n * and/or weights of the model. In the case of Keras-style `tf.Model`, two\n * blobs (files) exist in form-data:\n * - A JSON file consisting of `modelTopology` and `weightsManifest`.\n * - A binary weights file consisting of the concatenated weight values.\n * These files are in the same format as the one generated by\n * [tfjs_converter](https://js.tensorflow.org/tutorials/import-keras.html).\n *\n * The following code snippet exemplifies the client-side code that uses this\n * function:\n *\n * ```js\n * const model = tf.sequential();\n * model.add(\n * tf.layers.dense({units: 1, inputShape: [100], activation: 'sigmoid'}));\n *\n * const saveResult = await model.save(tf.io.http(\n * 'http://model-server:5000/upload', {requestInit: {method: 'PUT'}}));\n * console.log(saveResult);\n * ```\n *\n * If the default `POST` method is to be used, without any custom parameters\n * such as headers, you can simply pass an HTTP or HTTPS URL to `model.save`:\n *\n * ```js\n * const saveResult = await model.save('http://model-server:5000/upload');\n * ```\n *\n * The following GitHub Gist\n * https://gist.github.com/dsmilkov/1b6046fd6132d7408d5257b0976f7864\n * implements a server based on [flask](https://github.com/pallets/flask) that\n * can receive the request. Upon receiving the model artifacts via the requst,\n * this particular server reconsistutes instances of [Keras\n * Models](https://keras.io/models/model/) in memory.\n *\n *\n * @param path A URL path to the model.\n * Can be an absolute HTTP path (e.g.,\n * 'http://localhost:8000/model-upload)') or a relative path (e.g.,\n * './model-upload').\n * @param requestInit Request configurations to be used when sending\n * HTTP request to server using `fetch`. It can contain fields such as\n * `method`, `credentials`, `headers`, `mode`, etc. See\n * https://developer.mozilla.org/en-US/docs/Web/API/Request/Request\n * for more information. `requestInit` must not have a body, because the\n * body will be set by TensorFlow.js. File blobs representing the model\n * topology (filename: 'model.json') and the weights of the model (filename:\n * 'model.weights.bin') will be appended to the body. If `requestInit` has a\n * `body`, an Error will be thrown.\n * @param loadOptions Optional configuration for the loading. It includes the\n * following fields:\n * - weightPathPrefix Optional, this specifies the path prefix for weight\n * files, by default this is calculated from the path param.\n * - fetchFunc Optional, custom `fetch` function. E.g., in Node.js,\n * the `fetch` from node-fetch can be used here.\n * - onProgress Optional, progress callback function, fired periodically\n * before the load is completed.\n * @returns An instance of `IOHandler`.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Loading',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nexport function http(path: string, loadOptions?: LoadOptions): IOHandler {\n return new HTTPRequest(path, loadOptions);\n}\n\n/**\n * Deprecated. Use `tf.io.http`.\n * @param path\n * @param loadOptions\n */\nexport function browserHTTPRequest(\n path: string, loadOptions?: LoadOptions): IOHandler {\n return http(path, loadOptions);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * IOHandlers that pass through the in-memory ModelArtifacts format.\n */\n\nimport {IOHandler, ModelArtifacts, SaveResult, TrainingConfig, WeightsManifestEntry} from './types';\n\nclass PassthroughLoader implements IOHandler {\n constructor(private readonly modelArtifacts?: ModelArtifacts) {}\n\n async load(): Promise {\n return this.modelArtifacts;\n }\n}\n\nclass PassthroughSaver implements IOHandler {\n constructor(\n private readonly saveHandler:\n (artifacts: ModelArtifacts) => Promise) {}\n\n async save(modelArtifacts: ModelArtifacts) {\n return this.saveHandler(modelArtifacts);\n }\n}\n\n/**\n * Creates an IOHandler that loads model artifacts from memory.\n *\n * When used in conjunction with `tf.loadLayersModel`, an instance of\n * `tf.LayersModel` (Keras-style) can be constructed from the loaded artifacts.\n *\n * ```js\n * const model = await tf.loadLayersModel(tf.io.fromMemory(\n * modelTopology, weightSpecs, weightData));\n * ```\n *\n * @param modelArtifacts a object containing model topology (i.e., parsed from\n * the JSON format).\n * @param weightSpecs An array of `WeightsManifestEntry` objects describing the\n * names, shapes, types, and quantization of the weight data.\n * @param weightData A single `ArrayBuffer` containing the weight data,\n * concatenated in the order described by the weightSpecs.\n * @param trainingConfig Model training configuration. Optional.\n *\n * @returns A passthrough `IOHandler` that simply loads the provided data.\n */\nexport function fromMemory(\n modelArtifacts: {}|ModelArtifacts, weightSpecs?: WeightsManifestEntry[],\n weightData?: ArrayBuffer, trainingConfig?: TrainingConfig): IOHandler {\n if (arguments.length === 1) {\n const isModelArtifacts =\n (modelArtifacts as ModelArtifacts).modelTopology != null ||\n (modelArtifacts as ModelArtifacts).weightSpecs != null;\n if (isModelArtifacts) {\n return new PassthroughLoader(modelArtifacts as ModelArtifacts);\n } else {\n // Legacy support: with only modelTopology.\n // TODO(cais): Remove this deprecated API.\n console.warn(\n 'Please call tf.io.fromMemory() with only one argument. ' +\n 'The argument should be of type ModelArtifacts. ' +\n 'The multi-argument signature of tf.io.fromMemory() has been ' +\n 'deprecated and will be removed in a future release.');\n return new PassthroughLoader({modelTopology: modelArtifacts as {}});\n }\n } else {\n // Legacy support.\n // TODO(cais): Remove this deprecated API.\n console.warn(\n 'Please call tf.io.fromMemory() with only one argument. ' +\n 'The argument should be of type ModelArtifacts. ' +\n 'The multi-argument signature of tf.io.fromMemory() has been ' +\n 'deprecated and will be removed in a future release.');\n return new PassthroughLoader({\n modelTopology: modelArtifacts as {},\n weightSpecs,\n weightData,\n trainingConfig\n });\n }\n}\n\n/**\n * Creates an IOHandler that passes saved model artifacts to a callback.\n *\n * ```js\n * function handleSave(artifacts) {\n * // ... do something with the artifacts ...\n * return {modelArtifactsInfo: {...}, ...};\n * }\n *\n * const saveResult = model.save(tf.io.withSaveHandler(handleSave));\n * ```\n *\n * @param saveHandler A function that accepts a `ModelArtifacts` and returns a\n * `SaveResult`.\n */\nexport function withSaveHandler(\n saveHandler: (artifacts: ModelArtifacts) =>\n Promise): IOHandler {\n return new PassthroughSaver(saveHandler);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * Exports under the tf.math.* namespace.\n */\n\nimport {confusionMatrix} from './ops/confusion_matrix';\n\nexport {confusionMatrix};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {BatchMatMul, BatchMatMulAttrs, BatchMatMulInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the dot product of two matrices, A * B. These must be matrices.\n *\n * ```js\n * const a = tf.tensor2d([1, 2], [1, 2]);\n * const b = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * a.matMul(b).print(); // or tf.matMul(a, b)\n * ```\n * @param a First matrix in dot product operation.\n * @param b Second matrix in dot product operation.\n * @param transposeA If true, `a` is transposed before multiplication.\n * @param transposeB If true, `b` is transposed before multiplication.\n *\n * @doc {heading: 'Operations', subheading: 'Matrices'}\n */\nfunction matMul_(\n a: Tensor|TensorLike, b: Tensor|TensorLike, transposeA = false,\n transposeB = false): T {\n let $a = convertToTensor(a, 'a', 'matMul');\n let $b = convertToTensor(b, 'b', 'matMul');\n [$a, $b] = makeTypesMatch($a, $b);\n\n const inputs: BatchMatMulInputs = {a: $a, b: $b};\n const attrs: BatchMatMulAttrs = {transposeA, transposeB};\n\n return ENGINE.runKernel(\n BatchMatMul, inputs as {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const matMul = op({matMul_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {OneHot, OneHotAttrs, OneHotInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Creates a one-hot `tf.Tensor`. The locations represented by `indices` take\n * value `onValue` (defaults to 1), while all other locations take value\n * `offValue` (defaults to 0). If `indices` is rank `R`, the output has rank\n * `R+1` with the last axis of size `depth`.\n *\n * ```js\n * tf.oneHot(tf.tensor1d([0, 1], 'int32'), 3).print();\n * ```\n *\n * @param indices `tf.Tensor` of indices with dtype `int32`.\n * @param depth The depth of the one hot dimension.\n * @param onValue A number used to fill in the output when the index matches\n * the location.\n * @param offValue A number used to fill in the output when the index does\n * not match the location.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction oneHot_(\n indices: Tensor|TensorLike, depth: number, onValue = 1,\n offValue = 0): Tensor {\n if (depth < 2) {\n throw new Error(`Error in oneHot: depth must be >=2, but it is ${depth}`);\n }\n const $indices = convertToTensor(indices, 'indices', 'oneHot', 'int32');\n\n const inputs: OneHotInputs = {indices: $indices};\n const attrs: OneHotAttrs = {depth, onValue, offValue};\n\n return ENGINE.runKernel(\n OneHot, inputs as unknown as NamedTensorMap,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const oneHot = op({oneHot_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Transpose, TransposeAttrs, TransposeInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Transposes the `tf.Tensor`. Permutes the dimensions according to `perm`.\n *\n * The returned `tf.Tensor`'s dimension `i` will correspond to the input\n * dimension `perm[i]`. If `perm` is not given, it is set to `[n-1...0]`,\n * where `n` is the rank of the input `tf.Tensor`. Hence by default, this\n * operation performs a regular matrix transpose on 2-D input `tf.Tensor`s.\n *\n * ```js\n * const a = tf.tensor2d([1, 2, 3, 4, 5, 6], [2, 3]);\n *\n * a.transpose().print(); // or tf.transpose(a)\n * ```\n *\n * @param x The tensor to transpose.\n * @param perm The permutation of the dimensions of a.\n *\n * @doc {heading: 'Operations', subheading: 'Matrices'}\n */\nfunction transpose_(x: T|TensorLike, perm?: number[]): T {\n const $x = convertToTensor(x, 'x', 'transpose');\n\n if (perm == null) {\n perm = $x.shape.map((s, i) => i).reverse();\n }\n util.assert(\n $x.rank === perm.length,\n () => `Error in transpose: rank of input ${$x.rank} ` +\n `must match length of perm ${perm}.`);\n perm.forEach(axis => {\n util.assert(\n axis >= 0 && axis < $x.rank,\n () => `All entries in 'perm' must be between 0 and ${$x.rank - 1}` +\n ` but got ${perm}`);\n });\n\n if ($x.rank <= 1) {\n return $x.clone();\n }\n\n const inputs: TransposeInputs = {x: $x};\n const attrs: TransposeAttrs = {perm};\n\n return ENGINE.runKernel(\n Transpose, inputs as {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const transpose = op({transpose_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor1D, Tensor2D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {cast} from './cast';\nimport {matMul} from './mat_mul';\nimport {oneHot} from './one_hot';\nimport {op} from './operation';\nimport {transpose} from './transpose';\n\n/**\n * Computes the confusion matrix from true labels and predicted labels.\n *\n * ```js\n * const labels = tf.tensor1d([0, 1, 2, 1, 0], 'int32');\n * const predictions = tf.tensor1d([0, 2, 2, 1, 0], 'int32');\n * const numClasses = 3;\n * const out = tf.math.confusionMatrix(labels, predictions, numClasses);\n * out.print();\n * // Expected output matrix:\n * // [[2, 0, 0],\n * // [0, 1, 1],\n * // [0, 0, 1]]\n * ```\n *\n * @param labels The target labels, assumed to be 0-based integers\n * for the classes. The shape is `[numExamples]`, where\n * `numExamples` is the number of examples included.\n * @param predictions The predicted classes, assumed to be\n * 0-based integers for the classes. Must have the same shape as `labels`.\n * @param numClasses Number of all classes, as an integer.\n * Its value must be larger than the largest element in `labels` and\n * `predictions`.\n * @returns The confusion matrix as a int32-type 2D tensor. The value at\n * row `r` and column `c` is the number of times examples of actual class\n * `r` were predicted as class `c`.\n *\n * @doc {heading: 'Operations', subheading: 'Evaluation'}\n */\nexport function confusionMatrix_(\n labels: Tensor1D|TensorLike, predictions: Tensor1D|TensorLike,\n numClasses: number): Tensor2D {\n const $labels = convertToTensor(labels, 'labels', 'confusionMatrix');\n const $predictions =\n convertToTensor(predictions, 'predictions', 'confusionMatrix');\n\n util.assert(\n numClasses == null || numClasses > 0 && Number.isInteger(numClasses),\n () => `If provided, numClasses must be a positive integer, ` +\n `but got ${numClasses}`);\n util.assert(\n $labels.rank === 1,\n () => `Expected the rank of labels to be 1, but got ${$labels.rank}`);\n util.assert(\n $predictions.rank === 1,\n () => `Expected the rank of predictions to be 1, ` +\n `but got ${$predictions.rank}`);\n util.assert(\n $labels.shape[0] === $predictions.shape[0],\n () => `Mismatch in the number of examples: ` +\n `${$labels.shape[0]} vs. ${$predictions.shape[0]}. ` +\n `Labels and predictions should have the same number of elements.`);\n util.assert(\n numClasses > 0 && Number.isInteger(numClasses),\n () => `numClasses is required to be a positive integer, but got ` +\n `${numClasses}`);\n // TODO(cais): In the future, if oneHot supports tensors inputs for\n // `numClasses`, `confusionMatrix` can make `numClasses` optional.\n\n const oneHotLabels = oneHot(cast($labels, 'int32'), numClasses) as Tensor2D;\n const oneHotPredictions =\n oneHot(cast($predictions, 'int32'), numClasses) as Tensor2D;\n const oneHotLabelsT: Tensor2D = transpose(oneHotLabels);\n const product: Tensor2D = matMul(oneHotLabelsT, oneHotPredictions);\n return cast(product, 'int32');\n}\n\nexport const confusionMatrix = op({confusionMatrix_});\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {env} from '../environment';\nimport {FromPixels, FromPixelsAttrs, FromPixelsInputs} from '../kernel_names';\nimport {getKernel, NamedAttrMap} from '../kernel_registry';\nimport {Tensor, Tensor2D, Tensor3D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {PixelData, TensorLike} from '../types';\n\nimport {cast} from './cast';\nimport {op} from './operation';\nimport {tensor3d} from './tensor3d';\n\nlet fromPixels2DContext: CanvasRenderingContext2D;\n\n/**\n * Creates a `tf.Tensor` from an image.\n *\n * ```js\n * const image = new ImageData(1, 1);\n * image.data[0] = 100;\n * image.data[1] = 150;\n * image.data[2] = 200;\n * image.data[3] = 255;\n *\n * tf.browser.fromPixels(image).print();\n * ```\n *\n * @param pixels The input image to construct the tensor from. The\n * supported image types are all 4-channel. You can also pass in an image\n * object with following attributes:\n * `{data: Uint8Array; width: number; height: number}`\n * @param numChannels The number of channels of the output tensor. A\n * numChannels value less than 4 allows you to ignore channels. Defaults to\n * 3 (ignores alpha channel of input image).\n *\n * @returns A Tensor3D with the shape `[height, width, numChannels]`.\n *\n * @doc {heading: 'Browser', namespace: 'browser', ignoreCI: true}\n */\nfunction fromPixels_(\n pixels: PixelData|ImageData|HTMLImageElement|HTMLCanvasElement|\n HTMLVideoElement|ImageBitmap,\n numChannels = 3): Tensor3D {\n // Sanity checks.\n if (numChannels > 4) {\n throw new Error(\n 'Cannot construct Tensor with more than 4 channels from pixels.');\n }\n if (pixels == null) {\n throw new Error('pixels passed to tf.browser.fromPixels() can not be null');\n }\n let isPixelData = false;\n let isImageData = false;\n let isVideo = false;\n let isImage = false;\n let isCanvasLike = false;\n let isImageBitmap = false;\n if ((pixels as PixelData).data instanceof Uint8Array) {\n isPixelData = true;\n } else if (\n typeof (ImageData) !== 'undefined' && pixels instanceof ImageData) {\n isImageData = true;\n } else if (\n typeof (HTMLVideoElement) !== 'undefined' &&\n pixels instanceof HTMLVideoElement) {\n isVideo = true;\n } else if (\n typeof (HTMLImageElement) !== 'undefined' &&\n pixels instanceof HTMLImageElement) {\n isImage = true;\n // tslint:disable-next-line: no-any\n } else if ((pixels as any).getContext != null) {\n isCanvasLike = true;\n } else if (\n typeof (ImageBitmap) !== 'undefined' && pixels instanceof ImageBitmap) {\n isImageBitmap = true;\n } else {\n throw new Error(\n 'pixels passed to tf.browser.fromPixels() must be either an ' +\n `HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData ` +\n `in browser, or OffscreenCanvas, ImageData in webworker` +\n ` or {data: Uint32Array, width: number, height: number}, ` +\n `but was ${(pixels as {}).constructor.name}`);\n }\n if (isVideo) {\n const HAVE_CURRENT_DATA_READY_STATE = 2;\n if (isVideo &&\n (pixels as HTMLVideoElement).readyState <\n HAVE_CURRENT_DATA_READY_STATE) {\n throw new Error(\n 'The video element has not loaded data yet. Please wait for ' +\n '`loadeddata` event on the