var faceapi=(()=>{var Hs=Object.defineProperty,Vb=Object.prototype.hasOwnProperty,zs=Object.assign,At=(e,t)=>()=>(t||(t={exports:{}},e(t.exports,t)),t.exports),mu=e=>Hs(e,"__esModule",{value:!0}),Re=(e,t)=>{mu(e);for(var n in t)Hs(e,n,{get:t[n],enumerable:!0})},Kb=(e,t)=>{if(mu(e),typeof t=="object"||typeof t=="function")for(let n in t)!Vb.call(e,n)&&n!=="default"&&Hs(e,n,{get:()=>t[n],enumerable:!0});return e},fu=e=>e&&e.__esModule?e:Kb(Hs({},"default",{value:e,enumerable:!0}),e);var bu=At((gu,mc)=>{(function(e,t,n){function r(s){var c=this,p=a();c.next=function(){var l=2091639*c.s0+c.c*23283064365386963e-26;return c.s0=c.s1,c.s1=c.s2,c.s2=l-(c.c=l|0)},c.c=1,c.s0=p(" "),c.s1=p(" "),c.s2=p(" "),c.s0-=p(s),c.s0<0&&(c.s0+=1),c.s1-=p(s),c.s1<0&&(c.s1+=1),c.s2-=p(s),c.s2<0&&(c.s2+=1),p=null}function o(s,c){return c.c=s.c,c.s0=s.s0,c.s1=s.s1,c.s2=s.s2,c}function i(s,c){var p=new r(s),l=c&&c.state,h=p.next;return h.int32=function(){return p.next()*4294967296|0},h.double=function(){return h()+(h()*2097152|0)*11102230246251565e-32},h.quick=h,l&&(typeof l=="object"&&o(l,p),h.state=function(){return o(p,{})}),h}function a(){var s=4022871197,c=function(p){p=p.toString();for(var l=0;l
>>0,h-=s,h*=s,s=h>>>0,h-=s,s+=h*4294967296}return(s>>>0)*23283064365386963e-26};return c}t&&t.exports?t.exports=i:n&&n.amd?n(function(){return i}):this.alea=i})(gu,typeof mc=="object"&&mc,typeof define=="function"&&define)});var xu=At((wu,fc)=>{(function(e,t,n){function r(a){var s=this,c="";s.x=0,s.y=0,s.z=0,s.w=0,s.next=function(){var l=s.x^s.x<<11;return s.x=s.y,s.y=s.z,s.z=s.w,s.w^=s.w>>>19^l^l>>>8},a===(a|0)?s.x=a:c+=a;for(var p=0;p>>0)/4294967296};return l.double=function(){do var h=c.next()>>>11,d=(c.next()>>>0)/4294967296,b=(h+d)/(1<<21);while(b===0);return b},l.int32=c.next,l.quick=l,p&&(typeof p=="object"&&o(p,c),l.state=function(){return o(c,{})}),l}t&&t.exports?t.exports=i:n&&n.amd?n(function(){return i}):this.xor128=i})(wu,typeof fc=="object"&&fc,typeof define=="function"&&define)});var Lu=At((yu,gc)=>{(function(e,t,n){function r(a){var s=this,c="";s.next=function(){var l=s.x^s.x>>>2;return s.x=s.y,s.y=s.z,s.z=s.w,s.w=s.v,(s.d=s.d+362437|0)+(s.v=s.v^s.v<<4^(l^l<<1))|0},s.x=0,s.y=0,s.z=0,s.w=0,s.v=0,a===(a|0)?s.x=a:c+=a;for(var p=0;p>>4),s.next()}function o(a,s){return s.x=a.x,s.y=a.y,s.z=a.z,s.w=a.w,s.v=a.v,s.d=a.d,s}function i(a,s){var c=new r(a),p=s&&s.state,l=function(){return(c.next()>>>0)/4294967296};return l.double=function(){do var h=c.next()>>>11,d=(c.next()>>>0)/4294967296,b=(h+d)/(1<<21);while(b===0);return b},l.int32=c.next,l.quick=l,p&&(typeof p=="object"&&o(p,c),l.state=function(){return o(c,{})}),l}t&&t.exports?t.exports=i:n&&n.amd?n(function(){return i}):this.xorwow=i})(yu,typeof gc=="object"&&gc,typeof define=="function"&&define)});var Su=At((vu,bc)=>{(function(e,t,n){function r(a){var s=this;s.next=function(){var p=s.x,l=s.i,h,d,b;return h=p[l],h^=h>>>7,d=h^h<<24,h=p[l+1&7],d^=h^h>>>10,h=p[l+3&7],d^=h^h>>>3,h=p[l+4&7],d^=h^h<<7,h=p[l+7&7],h=h^h<<13,d^=h^h<<9,p[l]=d,s.i=l+1&7,d};function c(p,l){var h,d,b=[];if(l===(l|0))d=b[0]=l;else for(l=""+l,h=0;h0;--h)p.next()}c(s,a)}function o(a,s){return s.x=a.x.slice(),s.i=a.i,s}function i(a,s){a==null&&(a=+new Date());var c=new r(a),p=s&&s.state,l=function(){return(c.next()>>>0)/4294967296};return l.double=function(){do var h=c.next()>>>11,d=(c.next()>>>0)/4294967296,b=(h+d)/(1<<21);while(b===0);return b},l.int32=c.next,l.quick=l,p&&(p.x&&o(p,c),l.state=function(){return o(c,{})}),l}t&&t.exports?t.exports=i:n&&n.amd?n(function(){return i}):this.xorshift7=i})(vu,typeof bc=="object"&&bc,typeof define=="function"&&define)});var Tu=At((Iu,wc)=>{(function(e,t,n){function r(a){var s=this;s.next=function(){var p=s.w,l=s.X,h=s.i,d,b;return s.w=p=p+1640531527|0,b=l[h+34&127],d=l[h=h+1&127],b^=b<<13,d^=d<<17,b^=b>>>15,d^=d>>>12,b=l[h]=b^d,s.i=h,b+(p^p>>>16)|0};function c(p,l){var h,d,b,x,w,L=[],S=128;for(l===(l|0)?(d=l,l=null):(l=l+"\0",d=0,S=Math.max(S,l.length)),b=0,x=-32;x>>15,d^=d<<4,d^=d>>>13,x>=0&&(w=w+1640531527|0,h=L[x&127]^=d+w,b=h==0?b+1:0);for(b>=128&&(L[(l&&l.length||0)&127]=-1),b=127,x=4*128;x>0;--x)d=L[b+34&127],h=L[b=b+1&127],d^=d<<13,h^=h<<17,d^=d>>>15,h^=h>>>12,L[b]=d^h;p.w=w,p.X=L,p.i=b}c(s,a)}function o(a,s){return s.i=a.i,s.w=a.w,s.X=a.X.slice(),s}function i(a,s){a==null&&(a=+new Date());var c=new r(a),p=s&&s.state,l=function(){return(c.next()>>>0)/4294967296};return l.double=function(){do var h=c.next()>>>11,d=(c.next()>>>0)/4294967296,b=(h+d)/(1<<21);while(b===0);return b},l.int32=c.next,l.quick=l,p&&(p.X&&o(p,c),l.state=function(){return o(c,{})}),l}t&&t.exports?t.exports=i:n&&n.amd?n(function(){return i}):this.xor4096=i})(Iu,typeof wc=="object"&&wc,typeof define=="function"&&define)});var Nu=At((Au,xc)=>{(function(e,t,n){function r(a){var s=this,c="";s.next=function(){var l=s.b,h=s.c,d=s.d,b=s.a;return l=l<<25^l>>>7^h,h=h-d|0,d=d<<24^d>>>8^b,b=b-l|0,s.b=l=l<<20^l>>>12^h,s.c=h=h-d|0,s.d=d<<16^h>>>16^b,s.a=b-l|0},s.a=0,s.b=0,s.c=2654435769|0,s.d=1367130551,a===Math.floor(a)?(s.a=a/4294967296|0,s.b=a|0):c+=a;for(var p=0;p>>0)/4294967296};return l.double=function(){do var h=c.next()>>>11,d=(c.next()>>>0)/4294967296,b=(h+d)/(1<<21);while(b===0);return b},l.int32=c.next,l.quick=l,p&&(typeof p=="object"&&o(p,c),l.state=function(){return o(c,{})}),l}t&&t.exports?t.exports=i:n&&n.amd?n(function(){return i}):this.tychei=i})(Au,typeof xc=="object"&&xc,typeof define=="function"&&define)});var Ru=At(()=>{});var _u=At((kT,Ys)=>{(function(e,t){var n=this,r=256,o=6,i=52,a="random",s=t.pow(r,o),c=t.pow(2,i),p=c*2,l=r-1,h;function d(N,A,E){var M=[];A=A==!0?{entropy:!0}:A||{};var D=L(w(A.entropy?[N,I(e)]:N==null?S():N,3),M),$=new b(M),B=function(){for(var j=$.g(o),te=s,re=0;j=p;)j/=2,te/=2,re>>>=1;return(j+re)/te};return B.int32=function(){return $.g(4)|0},B.quick=function(){return $.g(4)/4294967296},B.double=B,L(I($.S),e),(A.pass||E||function(j,te,re,he){return he&&(he.S&&x(he,$),j.state=function(){return x($,{})}),re?(t[a]=j,te):j})(B,D,"global"in A?A.global:this==t,A.state)}t["seed"+a]=d;function b(N){var A,E=N.length,M=this,D=0,$=M.i=M.j=0,B=M.S=[];for(E||(N=[E++]);D{var Jb=bu(),Xb=xu(),Zb=Lu(),Qb=Su(),ew=Tu(),tw=Nu(),An=_u();An.alea=Jb;An.xor128=Xb;An.xorwow=Zb;An.xorshift7=Qb;An.xor4096=ew;An.tychei=tw;Cu.exports=An});var ku=At((nw,Ou)=>{Re(nw,{isNodejs:()=>rw});function rw(){return typeof global=="object"&&!0&&typeof Ou!="undefined"&&typeof process!="undefined"&&!!process.version}});var fd=At(ow=>{Re(ow,{AgeGenderNet:()=>La,BoundingBox:()=>Rr,Box:()=>de,ComposableTask:()=>xt,ComputeAllFaceDescriptorsTask:()=>hn,ComputeFaceDescriptorsTaskBase:()=>pa,ComputeSingleFaceDescriptorTask:()=>un,DetectAllFaceLandmarksTask:()=>aa,DetectAllFacesTask:()=>lo,DetectFaceLandmarksTaskBase:()=>sa,DetectFacesTaskBase:()=>oa,DetectSingleFaceLandmarksTask:()=>ca,DetectSingleFaceTask:()=>ia,Dimensions:()=>Qe,FACE_EXPRESSION_LABELS:()=>ua,FaceDetection:()=>fe,FaceDetectionNet:()=>Wu,FaceExpressionNet:()=>da,FaceExpressions:()=>fn,FaceLandmark68Net:()=>Sr,FaceLandmark68TinyNet:()=>ha,FaceLandmarkNet:()=>pd,FaceLandmarks:()=>st,FaceLandmarks5:()=>md,FaceLandmarks68:()=>Nr,FaceMatch:()=>wo,FaceMatcher:()=>Ac,FaceRecognitionNet:()=>vr,Gender:()=>Bt,LabeledBox:()=>bo,LabeledFaceDescriptors:()=>xn,NetInput:()=>Jt,NeuralNetwork:()=>Ue,ObjectDetection:()=>On,Point:()=>J,PredictedBox:()=>dd,Rect:()=>Ar,SsdMobilenetv1:()=>Nn,SsdMobilenetv1Options:()=>bt,TinyFaceDetector:()=>yr,TinyFaceDetectorOptions:()=>Qs,TinyYolov2:()=>xr,TinyYolov2Options:()=>Wt,TinyYolov2SizeType:()=>Zs,allFaces:()=>id,allFacesSsdMobilenetv1:()=>Tc,allFacesTinyYolov2:()=>od,awaitMediaLoaded:()=>ya,bufferToImage:()=>xa,computeFaceDescriptor:()=>qu,createCanvas:()=>En,createCanvasFromMedia:()=>Tr,createFaceDetectionNet:()=>Uu,createFaceRecognitionNet:()=>cd,createSsdMobilenetv1:()=>yc,createTinyFaceDetector:()=>Mu,createTinyYolov2:()=>Fu,detectAllFaces:()=>po,detectFaceLandmarks:()=>Sc,detectFaceLandmarksTiny:()=>Pu,detectLandmarks:()=>nd,detectSingleFace:()=>rd,draw:()=>Ks,env:()=>se,euclideanDistance:()=>ma,extendWithAge:()=>fo,extendWithFaceDescriptor:()=>mo,extendWithFaceDetection:()=>mn,extendWithFaceExpressions:()=>uo,extendWithFaceLandmarks:()=>Rn,extendWithGender:()=>ho,extractFaceTensors:()=>Cn,extractFaces:()=>_n,fetchImage:()=>ud,fetchJson:()=>wa,fetchNetWeights:()=>hd,fetchOrThrow:()=>wn,getContext2dOrThrow:()=>qe,getMediaDimensions:()=>bn,imageTensorToCanvas:()=>ba,imageToSquare:()=>ga,inverseSigmoid:()=>$u,iou:()=>ra,isMediaElement:()=>go,isMediaLoaded:()=>Ir,isWithAge:()=>ad,isWithFaceDetection:()=>Nt,isWithFaceExpressions:()=>la,isWithFaceLandmarks:()=>dn,isWithGender:()=>sd,loadAgeGenderModel:()=>Qu,loadFaceDetectionModel:()=>ed,loadFaceExpressionModel:()=>Zu,loadFaceLandmarkModel:()=>Ku,loadFaceLandmarkTinyModel:()=>Ju,loadFaceRecognitionModel:()=>Xu,loadSsdMobilenetv1Model:()=>Ic,loadTinyFaceDetectorModel:()=>Yu,loadTinyYolov2Model:()=>Vu,loadWeightMap:()=>fa,locateFaces:()=>td,matchDimensions:()=>ld,minBbox:()=>na,nets:()=>oe,nonMaxSuppression:()=>ta,normalize:()=>wt,padToSquare:()=>ea,predictAgeAndGender:()=>zu,recognizeFaceExpressions:()=>Hu,resizeResults:()=>Lc,resolveInput:()=>gn,shuffleArray:()=>Bu,sigmoid:()=>Lr,ssdMobilenetv1:()=>vc,test:()=>Du,tf:()=>Vs,tinyFaceDetector:()=>ju,tinyYolov2:()=>Gu,toNetInput:()=>ue,utils:()=>Js,validateConfig:()=>Xs});const Du="test"});const gd="tfjsflags";class Nc{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.populateURLFlags()}setPlatform(e,t){this.platform!=null&&console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${t}.`),this.platformName=e,this.platform=t}registerFlag(e,t,n){if(this.flagRegistry[e]={evaluationFn:t,setHook:n},this.urlFlags[e]!=null){const r=this.urlFlags[e];console.warn(`Setting feature override from URL ${e}: ${r}.`),this.set(e,r)}}async getAsync(e){return e in this.flags?this.flags[e]:(this.flags[e]=await this.evaluateFlag(e),this.flags[e])}get(e){if(e in this.flags)return this.flags[e];const t=this.evaluateFlag(e);if(t instanceof Promise)throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[e]=t,this.flags[e]}getNumber(e){return this.get(e)}getBool(e){return this.get(e)}getFlags(){return this.flags}get features(){return this.flags}set(e,t){if(this.flagRegistry[e]==null)throw new Error(`Cannot set flag ${e} as it has not been registered.`);this.flags[e]=t,this.flagRegistry[e].setHook!=null&&this.flagRegistry[e].setHook(t)}evaluateFlag(e){if(this.flagRegistry[e]==null)throw new Error(`Cannot evaluate flag '${e}': no evaluation function found.`);return this.flagRegistry[e].evaluationFn()}setFlags(e){this.flags=Object.assign({},e)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if(typeof this.global=="undefined"||typeof this.global.location=="undefined"||typeof this.global.location.search=="undefined")return;const e=iw(this.global.location.search);if(gd in e){const t=e[gd].split(",");t.forEach(n=>{const[r,o]=n.split(":");this.urlFlags[r]=sw(r,o)})}}}function iw(e){const t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(n,...r)=>(aw(t,r[0],r[1]),r.join("="))),t}function aw(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}function sw(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 pe(){return Rc}let Rc=null;function bd(e){Rc=e}let _c;function Cc(){if(_c==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");_c=e}return _c}function cw(){const e=Cc();return e._tfGlobals==null&&(e._tfGlobals=new Map()),e._tfGlobals}function Ec(e,t){const n=cw();if(n.has(e))return n.get(e);{const r=t();return n.set(e,r),n.get(e)}}const xo="Abs",yo="Acos",Lo="Acosh",kn="Add",vo="AddN",Oc="All",kc="Any",So="ArgMax",Io="ArgMin",To="Asin",Ao="Asinh",No="Atan",Ro="Atanh",_o="Atan2",Co="AvgPool",Dc="AvgPoolBackprop",Eo="AvgPool3D",Fc="AvgPool3DBackprop",Oo="BatchMatMul",ko="BatchToSpaceND",Do="BroadcastTo",Dn="Cast",Fo="Ceil",Mo="ClipByValue",Mc="Complex",Uo="Concat",Wo="Conv2D",Uc="Conv2DBackpropFilter",Bo="Conv2DBackpropInput",$o="Conv3D",Wc="Conv3DBackpropFilterV2",Bc="Conv3DBackpropInputV2",jo="Cos",Go="Cosh",Po="Cumsum",$c="CropAndResize",jc="DepthToSpace",qo="DepthwiseConv2dNative",Gc="DepthwiseConv2dNativeBackpropFilter",Pc="DepthwiseConv2dNativeBackpropInput",qc="Diag",Ho="Dilation2D",Hc="Dilation2DBackpropInput",zc="Dilation2DBackpropFilter",zo="Div",Yo="Elu",Yc="EluGrad",Vo="Erf",Vc="Equal",Ko="Exp",Jo="Expm1",Kc="FFT",Jc="Fill",Xc="FlipLeftRight",Xo="Floor",Zo="FloorDiv",Qo="FusedBatchNorm",ei="GatherV2",Zc="GatherNd",Qc="Greater",ti="GreaterEqual",ni="Identity",ep="IFFT",tp="Imag",ri="IsFinite",oi="IsInf",ii="IsNan",np="Less",rp="LessEqual",op="LinSpace",si="Log",ai="Log1p",ip="LogicalAnd",sp="LogicalNot",ap="LogicalOr",ci="LogSoftmax",pi="LRN",cp="LRNBackprop",li="Max",hi="Maximum",ui="MaxPool",pp="MaxPoolBackprop",di="MaxPool3D",lp="MaxPool3DBackprop",hp="MaxPoolWithArgmax",pw="Mean",mi="Min",fi="Minimum",gi="Mod",bi="Multiply",wi="Negate",up="NotEqual",dp="NonMaxSuppressionV3",mp="NonMaxSuppressionV4",fp="NonMaxSuppressionV5",xi="OnesLike",yi="OneHot",Li="PadV2",lw="Pool",vi="Pow",Si="Prelu",gp="Prod",bp="Range",wp="Real",Ii="Reciprocal",Ti="Relu",Ai="Reshape",Ni="ResizeNearestNeighbor",xp="ResizeNearestNeighborGrad",Ri="ResizeBilinear",yp="ResizeBilinearGrad",_i="Relu6",Ci="Reverse",Ei="Round",Oi="Rsqrt",Lp="ScatterNd",ki="SelectV2",Di="Selu",Fi="Slice",Mi="Sin",Ui="Sinh",Wi="Sign",Bi="Sigmoid",$i="Softplus",ji="Sqrt",Gi="Sum",Pi="SpaceToBatchND",qi="SplitV",Hi="Softmax",zi="SquaredDifference",vp="Square",Yi="Sub",Sp="SparseToDense",Ip="StridedSlice",Vi="Tan",Ki="Tanh",Ji="Tile",Tp="TopK",Xi="Transpose",Zi="Unpack",Qi="UnsortedSegmentSum",es="ZerosLike",ts="Step",va="FromPixels",Ap="RotateWithOffset",Sa="_FusedMatMul",Ia="FusedConv2D",Ta="FusedDepthwiseConv2D";const _r=Ec("kernelRegistry",()=>new Map()),ns=Ec("gradRegistry",()=>new Map());function rs(e,t){const n=Np(e,t);return _r.get(n)}function Aa(e){return ns.get(e)}function Na(e){const t=_r.entries(),n=[];for(;;){const{done:r,value:o}=t.next();if(r)break;const[i,a]=o,[s]=i.split("_");s===e&&n.push(a)}return n}function hw(e){const{kernelName:t,backendName:n}=e,r=Np(t,n);_r.has(r)&&console.warn(`The kernel '${t}' for backend '${n}' is already registered`),_r.set(r,e)}function Rp(e){const{kernelName:t}=e;ns.has(t)&&(pe().getBool("DEBUG")&&console.warn(`Overriding the gradient for '${t}'`)),ns.set(t,e)}function uw(e,t){const n=Np(e,t);if(!_r.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);_r.delete(n)}function dw(e){if(!ns.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);ns.delete(e)}function Np(e,t){return`${t}_${e}`}const wd={};Re(wd,{arraysEqual:()=>Te,assert:()=>f,assertNonNegativeIntegerDimensions:()=>ss,assertNonNull:()=>at,assertShapesMatch:()=>P,bytesFromStringArray:()=>Fp,bytesPerElement:()=>Dp,checkConversionForErrors:()=>yd,clamp:()=>Cr,computeStrides:()=>Gt,createShuffledIndices:()=>Lw,decodeString:()=>_a,distSquared:()=>bw,encodeString:()=>Mp,fetch:()=>Tw,flatten:()=>$t,getArrayFromDType:()=>Ep,getTypedArrayFromDType:()=>Er,hasEncodingLoss:()=>kp,indexToLoc:()=>Nw,inferDtype:()=>Or,inferFromImplicitShape:()=>_p,isBoolean:()=>Ld,isFunction:()=>jt,isInt:()=>X,isNumber:()=>vd,isScalarShape:()=>ww,isString:()=>Rt,isTypedArray:()=>_e,isValidDtype:()=>Op,locToIndex:()=>Aw,makeOnesTypedArray:()=>is,makeZerosNestedTypedArray:()=>Iw,makeZerosTypedArray:()=>Pt,nearestDivisor:()=>kr,nearestLargerEven:()=>mw,now:()=>Ra,parseAxisParam:()=>z,randUniform:()=>gw,repeatedTry:()=>vw,rightPad:()=>Fn,shuffle:()=>xd,sizeFromShape:()=>Q,sizeToSquarishShape:()=>yw,squeezeShape:()=>Cp,sum:()=>fw,tanh:()=>xw,toNestedArray:()=>Mn,toTypedArray:()=>os});function xd(e){let t=e.length,n=0,r=0;for(;t>0;)r=Math.random()*t|0,t--,n=e[t],e[t]=e[r],e[r]=n}function Cr(e,t,n){return Math.max(e,Math.min(t,n))}function mw(e){return e%2===0?e:e+1}function fw(e){let t=0;for(let n=0;nn+` Shapes ${e} and ${t} must match`)}function at(e){f(e!=null,()=>"The input to the tensor constructor must be a non-null value.")}function $t(e,t=[],n=!1){if(t==null&&(t=[]),Array.isArray(e)||_e(e)&&!n)for(let r=0;r0,n){return new Promise((r,o)=>{let i=0;const a=()=>{if(e()){r();return}i++;const s=t(i);if(n!=null&&i>=n){o();return}setTimeout(a,s)};a()})}function _p(e,t){let n=1,r=-1;for(let i=0;i=0)n*=e[i];else if(e[i]===-1){if(r!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${r} and dim ${i}`);r=i}else if(e[i]<0)throw Error(`Shapes can not be < 0. Found ${e[i]} at dim ${i}`);if(r===-1){if(t>0&&t!==n)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(n===0)throw Error(`Cannot infer the missing size in [${e}] when there are 0 elements`);if(t%n!==0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${n}`);const o=e.slice();return o[r]=t/n,o}function z(e,t){const n=t.length;return e=e==null?t.map((r,o)=>o):[].concat(e),f(e.every(r=>r>=-n&&r`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`),f(e.every(r=>X(r)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(r=>r<0?n+r:r)}function Cp(e,t){const n=[],r=[],o=t!=null&&Array.isArray(t)&&t.length===0,i=t==null||o?null:z(t,e).sort();let a=0;for(let s=0;ss)&&e[s]===1&&(n.push(e[s]),r.push(s)),i[a]<=s&&a++}e[s]!==1&&(n.push(e[s]),r.push(s))}return{newShape:n,keptDims:r}}function Er(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 Ep(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 yd(e,t){for(let n=0;nt+=n.length),t}function Rt(e){return typeof e=="string"||e instanceof String}function Ld(e){return typeof e=="boolean"}function vd(e){return typeof e=="number"}function Or(e){return Array.isArray(e)?Or(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array?"int32":vd(e)?"float32":Rt(e)?"string":Ld(e)?"bool":"float32"}function jt(e){return!!(e&&e.constructor&&e.call&&e.apply)}function kr(e,t){for(let n=t;n=0;--r)n[r]=n[r+1]*e[r+1];return n}function os(e,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=$t(e)),pe().getBool("DEBUG")&&yd(e,t),Sw(e,t))return e;if(t==null||t==="float32"||t==="complex64")return new Float32Array(e);if(t==="int32")return new Int32Array(e);if(t==="bool"){const n=new Uint8Array(e.length);for(let r=0;rs*c);for(let s=0;sr*o);if(n===0)return[];if(n!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}.`);return Sd(0,e,t)}function Sw(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function is(e,t){const n=Pt(e,t);for(let r=0;rr*o,1);if(t==null||t==="float32")return Mn(e,new Float32Array(n));if(t==="int32")return Mn(e,new Int32Array(n));if(t==="bool")return Mn(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function Ra(){return pe().platform.now()}function ss(e){e.forEach(t=>{f(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function Tw(e,t){return pe().platform.fetch(e,t)}function Mp(e,t="utf-8"){return t=t||"utf-8",pe().platform.encode(e,t)}function _a(e,t="utf-8"){return t=t||"utf-8",pe().platform.decode(e,t)}function Aw(e,t,n){if(t===0)return 0;if(t===1)return e[0];let r=e[e.length-1];for(let o=0;o{r=n()},i=this.backendTimer.time(o);r.map(s=>{s.data().then(c=>{Rw(c,s.dtype,e)})});const a={kernelName:e,outputs:r,inputs:t,timeMs:i.then(s=>s.kernelMs),extraInfo:i.then(s=>s.getExtraProfileInfo!=null?s.getExtraProfileInfo():"")};return a}logKernelProfile(e){const{kernelName:t,outputs:n,timeMs:r,inputs:o,extraInfo:i}=e;n.forEach(a=>{Promise.all([a.data(),r,i]).then(s=>{this.logger.logKernelProfile(t,a,s[0],s[1],o,s[2])})})}}function Rw(e,t,n){if(t!=="float32")return!1;for(let r=0;r0?x:""} `}}console.log(`%c${s} %c${a} %c${c}D ${l} %c${p} %c${h} %c${i}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}function Td(e,t,n){const r={},o={};for(let c=0;cr[w.id]=!0),b=!0,o[p.id]=!0;break}if(b)break}}const i={};i[n.id]=!0;const a={};for(let c=e.length-1;c>=0;c--){const p=e[c],l=p.inputs;for(let h=0;h=0;o--){const i=t[o],a=[];if(i.outputs.forEach(c=>{const p=e[c.id];p!=null?a.push(p):a.push(null)}),i.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${i.kernelName}.`);const s=i.gradient(a);for(const c in i.inputs){if(!(c in s))throw new Error(`Cannot backprop through input ${c}. Available gradients found: ${Object.keys(s)}.`);const p=n(()=>s[c]());if(p.dtype!=="float32")throw new Error(`Error in gradient for op ${i.kernelName}. The gradient of input ${c} must have 'float32' dtype, but has '${p.dtype}'`);const l=i.inputs[c];if(!Te(p.shape,l.shape))throw new Error(`Error in gradient for op ${i.kernelName}. The gradient of input '${c}' has shape '${p.shape}', which does not match the shape of the input '${l.shape}'`);if(e[l.id]==null)e[l.id]=p;else{const h=e[l.id];e[l.id]=r(h,p),h.dispose()}}}}const Nd=20,as=3,Up=7;function Rd(e,t,n,r){const o=Gt(t),i=Cw(e,t,n,o),a=t.length,s=Ca(e,t,n,o,i),c=["Tensor"];return r&&(c.push(` dtype: ${n}`),c.push(` rank: ${a}`),c.push(` shape: [${t}]`),c.push(" values:")),c.push(s.map(p=>" "+p).join(`
`)),c.join(`
`)}function Cw(e,t,n,r){const o=Q(t),i=r[r.length-1],a=new Array(i).fill(0),s=t.length,c=n==="complex64"?ps(e):e;if(s>1)for(let p=0;pNd){const L=as*a;let S=Array.from(e.slice(0,L)),I=Array.from(e.slice((s-as)*a,s*a));return n==="complex64"&&(S=ps(S),I=ps(I)),["["+S.map((N,A)=>cs(N,o[A],n)).join(", ")+", ..., "+I.map((N,A)=>cs(N,o[s-as+A],n)).join(", ")+"]"]}const w=n==="complex64"?ps(e):Array.from(e);return["["+w.map((L,S)=>cs(L,o[S],n)).join(", ")+"]"]}const p=t.slice(1),l=r.slice(1),h=r[0]*a,d=[];if(s>Nd){for(let w=0;w`Length of values '${r}' does not match the size inferred by the shape '${this.size}'.`)}if(t==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||Ep(t,this.size),this.strides=Gt(e)}set(e,...t){t.length===0&&(t=[0]),f(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);const n=this.locToIndex(t);this.values[n]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(const r of e){if(r<0||r>=this.shape[t]){const o=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(o)}t++}let n=e[e.length-1];for(let r=0;r_a(n))}catch(n){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataSync(){this.throwIfDisposed();const e=qt().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>_a(t))}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e}async bytes(){this.throwIfDisposed();const e=await qt().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){if(this.isDisposed)return;qt().disposeTensor(this),this.isDisposedInternal=!0}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Fr.print(this,e)}clone(){return this.throwIfDisposed(),Fr.clone(this)}toString(e=!1){const t=this.dataSync();return Rd(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Fr.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),qt().makeVariable(this,e,t,n)}}Object.defineProperty(ee,Symbol.hasInstance,{value:e=>!!e&&e.dataId!=null&&e.shape!=null&&e.dtype!=null});class Ht extends ee{constructor(e,t,n,r){super(e.shape,e.dtype,e.dataId,r);this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!Te(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);qt().disposeTensor(this),this.dataId=e.dataId,qt().incRef(this,null)}dispose(){qt().disposeVariable(this),this.isDisposedInternal=!0}}Object.defineProperty(Ht,Symbol.hasInstance,{value:e=>e instanceof ee&&e.assign!=null&&e.assign instanceof Function});var Wp;(function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"})(Wp||(Wp={}));var Bp;(function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"})(Bp||(Bp={}));var $p;(function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"})($p||($p={}));var jp;(function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"})(jp||(jp={}));var Gp;(function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"})(Gp||(Gp={}));const Ow={float32:jp,int32:Bp,bool:$p,complex64:Gp};function Mr(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return Ow[e][t]}function kw(e){return Mr(e,"int32")}const kd={};Re(kd,{assertTypesMatch:()=>Pp,getTensorsInContainer:()=>ls,isTensorInList:()=>Dw,makeTypesMatch:()=>V});function V(e,t){if(e.dtype===t.dtype)return[e,t];const n=Mr(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function Pp(e,t){f(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function Dw(e,t){return t.some(n=>n.id===e.id)}function ls(e){const t=[],n=new Set();return Dd(e,t,n),t}function Dd(e,t,n){if(e==null)return;if(e instanceof ee){t.push(e);return}if(!Fw(e))return;const r=e;for(const o in r){const i=r[o];n.has(i)||(n.add(i),Dd(i,t,n))}}function Fw(e){return Array.isArray(e)||typeof e=="object"}class Fd{constructor(){this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.gradientDepth=0,this.kernelDepth=0,this.scopeStack=[],this.numDataMovesStack=[],this.nextScopeId=0,this.tensorInfo=new WeakMap(),this.profiling=!1,this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null}}dispose(){for(const e in this.registeredVariables)this.registeredVariables[e].dispose()}}class hs{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new Fd()}async ready(){if(this.pendingBackendInit!=null)return this.pendingBackendInit.then(()=>{});if(this.backendInstance!=null)return;const e=this.getSortedBackends();for(let t=0;t{t.setupFunc!=null&&t.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){const t=Na(e);t.forEach(n=>{n.disposeFunc!=null&&n.disposeFunc(this.registry[e])})}initializeBackend(e){const t=this.registryFactory[e];if(t==null)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{const n=t.factory();if(Promise.resolve(n)===n){const r=++this.pendingBackendInitId,o=n.then(i=>r(rthis.registryFactory[t].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){const e=this.getSortedBackends();for(let t=0;tthis.startScope(n),()=>this.endScope(r),()=>(r=t(),r instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),r))}scopedRun(e,t,n){e();try{const r=n();return t(),r}catch(r){throw t(),r}}nextTensorId(){return hs.nextTensorId++}nextVariableId(){return hs.nextVariableId++}clone(e){const t=this.makeTensorFromDataId(e.dataId,e.shape,e.dtype),n={x:e},r=i=>({x:()=>{const a="float32",s={x:i},c={dtype:a};return g.runKernelFunc(p=>p.cast(i,a),s,null,Dn,c)}}),o=[];return this.addTapeNode(this.state.activeScope.name,n,[t],r,o,{}),t}runKernel(e,t,n,r,o){const i=null,a=null;return this.runKernelFunc(i,t,a,e,n,r,o)}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){const r=this.backend.numDataIds();let o=0;n.forEach(s=>{o+=s.dtype==="complex64"?3:1});const i=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],a=r-t-o-i;if(a>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${a} data ids) after running '${e}'`)}runKernelFunc(e,t,n,r,o,i,a){let s,c=[];const p=this.isTapeOn();r==null&&(r=this.state.activeScope!=null?this.state.activeScope.name:"");const l=this.state.numBytes,h=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let d;const b=rs(r,this.backendName);let x;if(b!=null)d=()=>{const L=this.backend.numDataIds();x=b.kernelFunc({inputs:t,attrs:o,backend:this.backend});const S=Array.isArray(x)?x:[x];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(r,L,S);const I=S.map(({dataId:N,shape:A,dtype:E})=>this.makeTensorFromDataId(N,A,E));if(p){let N=this.getTensorsForGradient(r,t,I);if(N==null){a==null&&(a=[]);const A=I.filter((E,M)=>a[M]);N=(i||[]).slice().concat(A)}c=this.saveTensorsForBackwardMode(N)}return I};else{const L=S=>{if(!p)return;c=S.map(I=>this.keep(this.clone(I)))};d=()=>{const S=this.backend.numDataIds();x=this.tidy(()=>e(this.backend,L));const I=Array.isArray(x)?x:[x];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(r,S,I),I}}let w;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?s=d():(w=this.profiler.profileKernel(r,t,()=>d()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(w),s=w.outputs)}),p&&this.addTapeNode(r,t,s,n,c,o),this.state.profiling&&this.state.activeProfile.kernels.push({name:r,bytesAdded:this.state.numBytes-l,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-h,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(t).map(L=>t[L]!=null?t[L].shape:null),outputShapes:s.map(L=>L.shape),kernelTimeMs:w.timeMs,extraInfo:w.extraInfo}),Array.isArray(x)?s:s[0]}saveTensorsForBackwardMode(e){const t=e.map(n=>this.keep(this.clone(n)));return t}getTensorsForGradient(e,t,n){const r=Aa(e);if(r!=null){const o=r.inputsToSave||[],i=r.outputsToSave||[];let a;r.saveAllInputs?(f(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),a=Object.keys(t).map(c=>t[c])):a=o.map(c=>t[c]);const s=n.filter((c,p)=>i[p]);return a.concat(s)}return null}makeTensor(e,t,n,r){if(e==null)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",r=r||this.backend;let o=e;n==="string"&&Rt(e[0])&&(o=e.map(s=>Mp(s)));const i=r.write(o,t,n),a=new ee(t,n,i,this.nextTensorId());if(this.incRef(a,r),n==="string"){const s=this.state.tensorInfo.get(i),c=Fp(o);this.state.numBytes+=c-s.bytes,s.bytes=c}return a}makeTensorFromDataId(e,t,n,r){n=n||"float32";const o=new ee(t,n,e,this.nextTensorId());return this.incRef(o,r),o}makeVariable(e,t=!0,n,r){n=n||this.nextVariableId().toString(),r!=null&&r!==e.dtype&&(e=e.cast(r));const o=new Ht(e,t,n,this.nextTensorId());if(this.state.registeredVariables[o.name]!=null)throw new Error(`Variable with name ${o.name} was already registered`);return this.state.registeredVariables[o.name]=o,this.incRef(o,this.backend),o}incRef(e,t){const n=this.state.tensorInfo.has(e.dataId)?this.state.tensorInfo.get(e.dataId).refCount:0;if(this.state.numTensors++,e.dtype==="string"&&this.state.numStringTensors++,n===0){this.state.numDataBuffers++;let r=0;e.dtype!=="complex64"&&e.dtype!=="string"&&(r=e.size*Dp(e.dtype)),this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:r,refCount:0}),this.state.numBytes+=r}this.state.tensorInfo.get(e.dataId).refCount++,e instanceof Ht||this.track(e)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;this.state.numTensors--,e.dtype==="string"&&this.state.numStringTensors--;const t=this.state.tensorInfo.get(e.dataId),n=t.refCount;n<=1?(e.dtype!=="complex64"&&(this.state.numBytes-=t.bytes),this.state.numDataBuffers--,t.backend.disposeData(e.dataId),this.state.tensorInfo.delete(e.dataId)):this.state.tensorInfo.get(e.dataId).refCount--}disposeVariables(){for(const e in this.state.registeredVariables){const t=this.state.registeredVariables[e];this.disposeVariable(t)}}disposeVariable(e){this.disposeTensor(e),this.state.registeredVariables[e.name]!=null&&delete this.state.registeredVariables[e.name]}memory(){const e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,e.reasons==null&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e}async profile(e){this.state.profiling=!0;const t=this.state.numBytes,n=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map(r=>r.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(const r of this.state.activeProfile.kernels)r.kernelTimeMs=await r.kernelTimeMs,r.extraInfo=await r.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(e,t,n,r,o,i){const a={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:o},s=Aa(e);s!=null&&(r=s.gradFunc),r!=null&&(a.gradient=c=>(c=c.map((p,l)=>{if(p==null){const h=n[l],d=Pt(h.size,h.dtype);return this.makeTensor(d,h.shape,h.dtype)}return p}),r(c.length>1?c:c[0],o,i))),this.state.activeTape.push(a)}keep(e){return e.kept=!0,e}startTape(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){const t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){const t=ls(e),n=new Set(t.map(o=>o.id));for(let o=0;o{!o.kept&&o.scopeId===r.id&&this.track(o)})}gradients(e,t,n,r=!1){if(f(t.length>0,()=>"gradients() received an empty list of xs."),n!=null&&n.dtype!=="float32")throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`);const o=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));f(o instanceof ee,()=>"The result y returned by f() must be a tensor.");const i=Td(this.state.activeTape,t,o);if(!r&&i.length===0&&t.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",()=>{const a={};a[o.id]=n==null?Mw(o.shape):n,Ad(a,i,c=>this.tidy(c),Uw);const s=t.map(c=>a[c.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(c=>{for(const p of c.saved)p.dispose()}),this.state.activeTape=null),{value:o,grads:s}})}customGrad(e){return f(jt(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{f(t.every(o=>o instanceof ee),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let n;const r={};return t.forEach((o,i)=>{r[i]=o}),this.runKernelFunc((o,i)=>(n=e(...t,i),f(n.value instanceof ee,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),f(jt(n.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),n.value),r,(o,i)=>{const a=n.gradFunc(o,i),s=Array.isArray(a)?a:[a];f(s.length===t.length,()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."),f(s.every(p=>p instanceof ee),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");const c={};return s.forEach((p,l)=>{c[l]=()=>p}),c})}}readSync(e){const t=this.state.tensorInfo.get(e);return t.backend.readSync(e)}read(e){const t=this.state.tensorInfo.get(e);return t.backend.read(e)}async time(e){const t=Ra(),n=await this.backend.time(e);return n.wallMs=Ra()-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 Fd();for(const e in this.registry)this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}}hs.nextTensorId=0;hs.nextVariableId=0;function Mw(e){const t=is(Q(e),"float32");return g.makeTensor(t,e,"float32")}function Ww(){const e=Cc();if(e._tfengine==null){const t=new Nc(e);e._tfengine=new hs(t)}return bd(e._tfengine.ENV),Cd(()=>e._tfengine),e._tfengine}const g=Ww();function Uw(e,t){const n={a:e,b:t};return g.runKernelFunc((r,o)=>{const i=r.add(e,t);return o([e,t]),i},n,null,kn)}const Md={};Re(Md,{isBrowser:()=>qp,isMobile:()=>$w});function Bw(){return typeof navigator!="undefined"&&navigator!=null}function $w(){if(Bw()){const e=navigator.userAgent||navigator.vendor||window.opera;return/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4))}return!1}function qp(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}const Xt=pe();Xt.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.")});Xt.registerFlag("IS_BROWSER",()=>qp());Xt.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");Xt.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));Xt.registerFlag("PROD",()=>!1);Xt.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Xt.getBool("DEBUG"));Xt.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);Xt.registerFlag("IS_TEST",()=>!1);function We(e,t){let n=e;if(_e(e))return t==="string"?[]:[e.length];if(!Array.isArray(e))return[];const r=[];for(;Array.isArray(n)||_e(n)&&t!=="string";)r.push(n.length),n=n[0];return Array.isArray(e)&&pe().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&Ud(e,r,[]),r}function Ud(e,t,n){if(n=n||[],!Array.isArray(e)&&!_e(e)){f(t.length===0,()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}f(t.length>0,()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`),f(e.length===t[0],()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`);const r=t.slice(1);for(let o=0;o=0&&(o=r),Wd(r,o,t,n),e==null||!_e(e)&&!Array.isArray(e)&&typeof e!="number"&&typeof e!="boolean"&&typeof e!="string"){const c=e==null?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${n}' must be a Tensor or TensorLike, but got '${c}'`)}const i=We(e,o);!_e(e)&&!Array.isArray(e)&&(e=[e]);const a=!0,s=o!=="string"?os(e,o):$t(e,[],a);return g.makeTensor(s,i,o)}function Zt(e,t,n,r="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);const o=e;return o.map((i,a)=>u(i,`${t}[${a}]`,n),r)}function m(e){const t=Object.keys(e);if(t.length!==1)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${t.length} keys.`);let n=t[0];const r=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1));const o=(...i)=>{g.startScope(n);try{const a=r(...i);return a instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),g.endScope(a),a}catch(a){throw g.endScope(null),a}};return Object.defineProperty(o,"name",{value:n,configurable:!0}),o}function jw(e){const t=u(e,"x","abs"),n={x:t};return g.runKernelFunc((r,o)=>(o([t]),t.dtype==="complex64"?r.complexAbs(t):r.abs(t)),n,null,xo)}const Ee=m({abs_:jw});function Gw(e){const t=u(e,"x","acos"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.acos(t);return o([t]),i},n,null,yo)}const Hp=m({acos_:Gw});function Pw(e){const t=u(e,"x","acosh"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.acosh(t);return o([t]),i},n,null,Lo)}const zp=m({acosh_:Pw});function qw(e,t){let n=u(e,"a","add"),r=u(t,"b","add");[n,r]=V(n,r);const o=(a,s)=>{const c=a.add(n,r);return s([n,r]),c},i={a:n,b:r};return g.runKernelFunc(o,i,null,kn)}const R=m({add_:qw});function Hw(e){f(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),f(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);const t=e.map((i,a)=>u(i,`tensors${a}`,"addN")),n=t[0];t.forEach(i=>{if(i.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(i=>{if(!Te(i.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});const r=(i,a)=>{const s=i.addN(t);return a(t),s},o=t;return g.runKernelFunc(r,o,null,vo)}const Yp=m({addN_:Hw});function Vp(e,t){for(let n=0;ne[i]);return[n,o]}function we(e,t){const n=t.map(r=>1);return Bd(e,n,t)}function zw(e,t,n){f(Vp(t,n),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`)}function ge(e,t){if(Vp(e,t))return null;const n=[];for(let r=0;rn.push(r)),n}function Un(e){return e.map((t,n)=>[n,t]).sort((t,n)=>t[1]-n[1]).map(t=>t[0])}function De(e,t){const n=[];for(let r=t-e;r"new shape and old shape must have the same number of elements.");const r={x:n},o={shape:t},i=(a,s)=>(s([n]),a.reshape(n,t));return g.runKernelFunc(i,r,null,Ai,o)}const y=m({reshape_:Yw});function Vw(e,t){const n=u(e,"x","transpose");if(t==null&&(t=n.shape.map((i,a)=>a).reverse()),f(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of perm ${t}.`),t.forEach(i=>{f(i>=0&&i`All entries in 'perm' must be between 0 and ${n.rank-1} but got ${t}`)}),n.rank<=1)return n.clone();const r={x:n},o={perm:t};return g.runKernelFunc(i=>i.transpose(n,t),r,null,Xi,o)}const K=m({transpose_:Vw});function Kw(e,t=null,n=!1){let r=u(e,"x","all","bool");const o=s=>{const c=z(t,r.shape);let p=c;const l=ge(p,r.rank);l!=null&&(r=K(r,l),p=De(p.length,r.rank));const h=s.all(r,p);if(n){const d=we(h.shape,c);return y(h,d)}return h},i={x:r},a={axis:t,keepDims:n};return g.runKernelFunc(o,i,null,Oc,a)}const Jp=m({all_:Kw});function Jw(e,t=null,n=!1){let r=u(e,"x","any","bool");const o=s=>{const c=z(t,r.shape);let p=c;const l=ge(p,r.rank);l!=null&&(r=K(r,l),p=De(p.length,r.rank));const h=s.any(r,p);if(n){const d=we(h.shape,c);return y(h,d)}return h},i={x:r},a={axis:t,keepDims:n};return g.runKernelFunc(o,i,null,kc,a)}const Xp=m({any_:Jw});function Xw(e,t=0){let n=u(e,"x","argMax");const r=(a,s)=>{s([n]);let c=z(t,n.shape);const p=ge(c,n.rank);return p!=null&&(n=K(n,p),c=De(c.length,n.rank)),a.argMax(n,c[0])},o={x:n},i={axis:t};return g.runKernelFunc(r,o,null,So,i)}const Zp=m({argMax_:Xw});function Zw(e,t=0){let n=u(e,"x","argMin");const r=(a,s)=>{s([n]),t==null&&(t=0);let c=z(t,n.shape);const p=ge(c,n.rank);return p!=null&&(n=K(n,p),c=De(c.length,n.rank)),a.argMin(n,c[0])},o={x:n},i={axis:t};return g.runKernelFunc(r,o,null,Io,i)}const Qp=m({argMin_:Zw});function Qw(e){const t=u(e,"x","asin"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.asin(t);return o([t]),i},n,null,To)}const el=m({asin_:Qw});function ex(e){const t=u(e,"x","asinh"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.asinh(t);return o([t]),i},n,null,Ao)}const tl=m({asinh_:ex});function tx(e){const t=u(e,"x","atan"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.atan(t);return o([t]),i},n,null,No)}const nl=m({atan_:tx});function nx(e,t){let n=u(e,"a","atan2"),r=u(t,"b","atan2");[n,r]=V(n,r);const o=(a,s)=>{const c=a.atan2(n,r);return s([n,r]),c},i={a:n,b:r};return g.runKernelFunc(o,i,null,_o)}const rl=m({atan2_:nx});function rx(e){const t=u(e,"x","atanh"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.atanh(t);return o([t]),i},n,null,Ro)}const ol=m({atanh_:rx});function ox(e,t){const n=u(e,"x","cast");if(!Op(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if(t==="string"&&n.dtype!=="string"||t!=="string"&&n.dtype==="string")throw new Error("Only strings can be casted to strings");const r={x:n},o={dtype:t};return g.runKernelFunc(i=>i.cast(n,t),r,null,Dn,o)}const C=m({cast_:ox});function ix(e,t,n,r,o="NHWC",i){const a=e[3],s=[...t,a],c=yn(o);return je(e,s,n,i,r,null,null,c)}function _t(e,t,n,r,o,i,a="channelsLast"){const[s,c]=Ea(t);let p;if(a==="channelsLast")p=[s,c,e[3],e[3]];else if(a==="channelsFirst")p=[s,c,e[1],e[1]];else throw new Error(`Unknown dataFormat ${a}`);return je(e,p,n,r,o,i,!1,a)}function Qt(e,t,n,r,o,i,a="NDHWC"){const[s,c,p]=il(t);let l,h;if(a==="NDHWC")h="channelsLast",l=[s,c,p,e[4],e[4]];else if(a==="NCDHW")h="channelsFirst",l=[s,c,p,e[1],e[1]];else throw new Error(`Unknown dataFormat ${a}`);return Ln(e,l,n,r,o,!1,h,i)}function je(e,t,n,r,o,i,a=!1,s="channelsLast"){let[c,p,l,h]=[-1,-1,-1,-1];if(s==="channelsLast")[c,p,l,h]=e;else if(s==="channelsFirst")[c,h,p,l]=e;else throw new Error(`Unknown dataFormat ${s}`);const[d,b,,x]=t,[w,L]=Ea(n),[S,I]=Ea(r),N=Ur(d,S),A=Ur(b,I),{padInfo:E,outHeight:M,outWidth:D}=sx(o,p,l,w,L,N,A,i,s),$=a?x*h:x;let B;return s==="channelsFirst"?B=[c,$,M,D]:s==="channelsLast"&&(B=[c,M,D,$]),{batchSize:c,dataFormat:s,inHeight:p,inWidth:l,inChannels:h,outHeight:M,outWidth:D,outChannels:$,padInfo:E,strideHeight:w,strideWidth:L,filterHeight:d,filterWidth:b,effectiveFilterHeight:N,effectiveFilterWidth:A,dilationHeight:S,dilationWidth:I,inShape:e,outShape:B,filterShape:t}}function Ln(e,t,n,r,o,i=!1,a="channelsLast",s){let[c,p,l,h,d]=[-1,-1,-1,-1,-1];if(a==="channelsLast")[c,p,l,h,d]=e;else if(a==="channelsFirst")[c,d,p,l,h]=e;else throw new Error(`Unknown dataFormat ${a}`);const[b,x,w,,L]=t,[S,I,N]=il(n),[A,E,M]=il(r),D=Ur(b,A),$=Ur(x,E),B=Ur(w,M),{padInfo:j,outDepth:te,outHeight:re,outWidth:he}=ax(o,p,l,h,S,I,N,D,$,B,s),ye=i?L*d:L;let Me;return a==="channelsFirst"?Me=[c,ye,te,re,he]:a==="channelsLast"&&(Me=[c,te,re,he,ye]),{batchSize:c,dataFormat:a,inDepth:p,inHeight:l,inWidth:h,inChannels:d,outDepth:te,outHeight:re,outWidth:he,outChannels:ye,padInfo:j,strideDepth:S,strideHeight:I,strideWidth:N,filterDepth:b,filterHeight:x,filterWidth:w,effectiveFilterDepth:D,effectiveFilterHeight:$,effectiveFilterWidth:B,dilationDepth:A,dilationHeight:E,dilationWidth:M,inShape:e,outShape:Me,filterShape:t}}function cx(e,t,n,r,o){r==null&&(r=sl(e,t,n));const i=e[0],a=e[1],s=Wn((i-t+2*r)/n+1,o);f(X(s),()=>`The output # of rows (${s}) must be an integer. Change the stride and/or zero pad parameters`);const c=Wn((a-t+2*r)/n+1,o);return f(X(c),()=>`The output # of columns (${c}) must be an integer. Change the stride and/or zero pad parameters`),[s,c]}function px(e,t,n,r,o,i){o==null&&(o=sl(e,t,r));const a=e[0],s=e[1],c=e[2],p=Wn((a-t+2*o)/r+1,i);f(X(p),()=>`The output # of depths (${p}) must be an integer. Change the stride and/or zero pad parameters`);const l=Wn((s-t+2*o)/r+1,i);f(X(l),()=>`The output # of rows (${l}) must be an integer. Change the stride and/or zero pad parameters`);const h=Wn((c-t+2*o)/r+1,i);return f(X(h),()=>`The output # of columns (${h}) must be an integer. Change the stride and/or zero pad parameters`),[p,l,h,n]}function sl(e,t,n,r=1){const o=Ur(t,r);return Math.floor((e[0]*(n-1)-n+o)/2)}function Ea(e){return typeof e=="number"?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function il(e){return typeof e=="number"?[e,e,e]:e}function Ur(e,t){return t<=1?e:e+(e-1)*(t-1)}function sx(e,t,n,r,o,i,a,s,c){let p,l,h;if(typeof e=="number"){const d=e===0?"VALID":"NUMBER";p={top:e,bottom:e,left:e,right:e,type:d};const b=cx([t,n],i,r,e,s);l=b[0],h=b[1]}else if(e==="same"){l=Math.ceil(t/r),h=Math.ceil(n/o);const d=Math.max(0,(l-1)*r+i-t),b=Math.max(0,(h-1)*o+a-n),x=Math.floor(d/2),w=d-x,L=Math.floor(b/2),S=b-L;p={top:x,bottom:w,left:L,right:S,type:"SAME"}}else if(e==="valid")p={top:0,bottom:0,left:0,right:0,type:"VALID"},l=Math.ceil((t-i+1)/r),h=Math.ceil((n-a+1)/o);else if(typeof e=="object"){const d=c==="channelsLast"?e[1][0]:e[2][0],b=c==="channelsLast"?e[1][1]:e[2][1],x=c==="channelsLast"?e[2][0]:e[3][0],w=c==="channelsLast"?e[2][1]:e[3][1],L=d===0&&b===0&&x===0&&w===0?"VALID":"EXPLICIT";p={top:d,bottom:b,left:x,right:w,type:L},l=Wn((t-i+d+b)/r+1,s),h=Wn((n-a+x+w)/o+1,s)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:p,outHeight:l,outWidth:h}}function ax(e,t,n,r,o,i,a,s,c,p,l){let h,d,b,x;if(typeof e=="number"){const w=e===0?"VALID":"NUMBER";h={top:e,bottom:e,left:e,right:e,front:e,back:e,type:w};const L=px([t,n,r,1],s,1,o,e,l);d=L[0],b=L[1],x=L[2]}else if(e==="same"){d=Math.ceil(t/o),b=Math.ceil(n/i),x=Math.ceil(r/a);const w=(d-1)*o+s-t,L=(b-1)*i+c-n,S=(x-1)*a+p-r,I=Math.floor(w/2),N=w-I,A=Math.floor(L/2),E=L-A,M=Math.floor(S/2),D=S-M;h={top:A,bottom:E,left:M,right:D,front:I,back:N,type:"SAME"}}else if(e==="valid")h={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},d=Math.ceil((t-s+1)/o),b=Math.ceil((n-c+1)/i),x=Math.ceil((r-p+1)/a);else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:h,outDepth:d,outHeight:b,outWidth:x}}function Wn(e,t){if(!t)return e;switch(t){case"round":return Math.round(e);case"ceil":return Math.ceil(e);case"floor":return Math.floor(e);default:throw new Error(`Unknown roundingMode ${t}`)}}function ct(e){const[t,n,r]=Ea(e);return t===1&&n===1&&r===1}function le(e,t){return ct(e)||ct(t)}function yn(e){if(e==="NHWC")return"channelsLast";if(e==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function lx(e,t,n,r,o){const i=u(e,"x","avgPool","float32"),a=1;f(le(n,a),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`);let s=i,c=!1;i.rank===3&&(c=!0,s=y(i,[1,i.shape[0],i.shape[1],i.shape[2]])),f(s.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${s.rank}.`),o!=null&&f(X(r),()=>`Error in avgPool: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);const p=(b,x)=>{const w=_t(s.shape,t,n,1,r,o);return x([s]),w.filterWidth===1&&w.filterHeight===1&&Te(w.inShape,w.outShape)?s.clone():b.avgPool(s,w)},l={x:s},h={filterSize:t,strides:n,pad:r,dimRoundingMode:o};let d=g.runKernelFunc(p,l,null,Co,h);return d=C(d,i.dtype),c?y(d,[d.shape[1],d.shape[2],d.shape[3]]):d}const pt=m({avgPool_:lx});function hx(){pe().set("PROD",!0)}function ux(){pe().set("DEBUG",!0)}function dx(){pe().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function Le(e){pe().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}Od(Le);function mx(){g.disposeVariables()}function fx(){return g}function gx(){return g.memory()}function bx(e){return g.profile(e)}function k(e,t){return g.tidy(e,t)}function ve(e){const t=ls(e);t.forEach(n=>n.dispose())}function al(e){return g.keep(e)}function wx(e){return g.time(e)}function xx(e){return g.setBackend(e)}function yx(){return g.ready()}function Lx(){return g.backendName}function vx(e){g.removeBackend(e)}function Sx(e){return g.findBackend(e)}function Ix(e){return g.findBackendFactory(e)}function Tx(e,t,n=1){return g.registerBackend(e,t,n)}function Ax(){return g.backend}function Nx(e,t){pe().setPlatform(e,t)}function Rx(e,t,n,r,o,i="NDHWC",a){a==null?a=[1,1,1]:Le("dilations is deprecated, this field will be gone in v3.0.0.");const s=u(e,"x","avgPool3d","float32");let c=s,p=!1;s.rank===4&&(p=!0,c=y(s,[1,s.shape[0],s.shape[1],s.shape[2],s.shape[3]])),f(c.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${c.rank}.`),f(i==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${i}`),f(le(n,a),()=>`Error in avgPool3d: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),o!=null&&f(X(r),()=>`Error in avgPool3d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);const l=(x,w)=>{a==null&&(a=[1,1,1]);const L=Qt(c.shape,t,n,a,r,o,i);return w([c]),x.avgPool3d(c,L)},h={x:c},d={filterSize:t,strides:n,pad:r,dimRoundingMode:o,dataFormat:i,dilations:a};let b=g.runKernelFunc(l,h,null,Eo,d);return b=C(b,c.dtype),p?y(b,[b.shape[1],b.shape[2],b.shape[3],b.shape[4]]):b}const cl=m({avgPool3d_:Rx});function pl(e,t){const n=e[0].length;e.forEach((o,i)=>{f(o.length===n,()=>`Error in concat${n}D: rank of tensors[${i}] must be the same as the rank of the rest (${n})`)}),f(t>=0&&t`Error in concat${n}D: axis must be between 0 and ${n-1}.`);const r=e[0];e.forEach((o,i)=>{for(let a=0;a`Error in concat${n}D: Shape of tensors[${i}] (${o}) does not match the shape of the rest (${r}) along the non-concatenated axis ${i}.`)})}function ll(e,t){const n=e[0].slice();for(let r=1;r`Based on the provided shape, [${t}], the tensor should have ${o} values but has ${i}`);for(let a=0;a`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `)}}return!_e(e)&&!Array.isArray(e)&&(e=[e]),t=t||n,e=r!=="string"?os(e,r):$t(e,[],!0),g.makeTensor(e,t,r)}function ze(e,t,n){const r=We(e,n);return He(e,t,r,n)}function _x(e,t=0){f(e.length>=1,()=>"Pass at least one tensor to concat");let n=Zt(e,"tensors","concat");n[0].dtype==="complex64"&&n.forEach(p=>{if(p.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor
with dtype ${p.dtype}. `)});const r=z(t,n[0].shape)[0],o=ll(n.map(p=>p.shape),r);if(Q(o)===0)return ze([],o);if(n=n.filter(p=>p.size>0),n.length===1)return n[0];const i=n.map(p=>p.shape);pl(i,r);const a=(p,l)=>{const h=p.concat(n,r);return l(n),h},s=n,c={axis:t};return g.runKernelFunc(a,s,null,Uo,c)}const Z=m({concat_:_x});function Cx(e,t,n=!1,r=!1){let o=u(e,"a","matMul"),i=u(t,"b","matMul");[o,i]=V(o,i),f(o.rank>=2&&i.rank>=2&&o.rank===i.rank,()=>`Error in matMul: inputs must have the same rank of at least 2, got ranks ${o.rank} and ${i.rank}.`);const a=n?o.shape[o.rank-2]:o.shape[o.rank-1],s=r?i.shape[i.rank-1]:i.shape[i.rank-2],c=n?o.shape[o.rank-1]:o.shape[o.rank-2],p=r?i.shape[i.rank-2]:i.shape[i.rank-1],l=o.shape.slice(0,-2),h=i.shape.slice(0,-2),d=Q(l),b=Q(h);f(Te(l,h),()=>`Error in matMul: outer dimensions (${l}) and (${h}) of Tensors with shapes ${o.shape} and ${i.shape} must match.`),f(a===s,()=>`Error in matMul: inner shapes (${a}) and (${s}) of Tensors with shapes ${o.shape} and ${i.shape} and transposeA=${n} and transposeB=${r} must match.`);const x=o.shape.slice(0,-2).concat([c,p]),w=n?y(o,[d,a,c]):y(o,[d,c,a]),L=r?y(i,[b,p,s]):y(i,[b,s,p]),S=(E,M)=>(M([w,L]),E.batchMatMul(w,L,n,r)),I={a:w,b:L},N={transposeA:n,transposeB:r},A=g.runKernelFunc(S,I,null,Oo,N);return y(A,x)}const Y=m({matMul_:Cx});function Ex(e,t){let n=u(e,"a","mul"),r=u(t,"b","mul");[n,r]=V(n,r);const o=(a,s)=>{const c=a.multiply(n,r);return s([n,r]),c},i={a:n,b:r};return g.runKernelFunc(o,i,null,bi)}const v=m({mul_:Ex});function Ox(e){const t=u(e,"x","sigmoid"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.sigmoid(t);return o([i]),i},n,null,Bi)}const lt=m({sigmoid_:Ox});const $d={};Re($d,{assertParamsValid:()=>hl,computeFlatOffset:()=>Dx,computeOutShape:()=>ul,isSliceContinous:()=>kx,maskToAxes:()=>us,parseSliceParams:()=>ds,startForAxis:()=>bl,startIndicesWithElidedDims:()=>ml,stopForAxis:()=>wl,stopIndicesWithElidedDims:()=>fl,stridesForAxis:()=>gl,stridesWithElidedDims:()=>dl});function hl(e,t,n){f(e.rank===t.length,()=>`Error in slice${e.rank}D: Length of begin ${t} must match the rank of the array (${e.rank}).`),f(e.rank===n.length,()=>`Error in slice${e.rank}D: Length of size ${n} must match the rank of the array (${e.rank}).`);for(let r=0;r`Error in slice${e.rank}D: begin[${r}] + size[${r}] (${t[r]+n[r]}) would overflow input.shape[${r}] (${e.shape[r]})`)}function us(e){const t=[];let n=0;for(;e>0;)e&1&&t.push(n),e/=2,n++;return t}function ul(e,t,n){const r=[];for(let o=0;o-1)i[s]=0;else{const c=jd(t,n,s);let p=r[c];e&1<-1)i[s]=Number.MAX_SAFE_INTEGER;else{const c=jd(t,n,s);let p=r[c];e&1<0?a=Number.MIN_SAFE_INTEGER:a=Number.MAX_SAFE_INTEGER);const c=r[o];return a<0&&(a+=c),a=Cr(0,a,c-1),a}function wl(e,t,n,r,o,i){let a=t[o];const s=n[o]||1;(e&1<0?a=Number.MAX_SAFE_INTEGER:a=Number.MIN_SAFE_INTEGER);const c=r[o];return a<0&&(a+=c),s>0?a=Cr(0,a,c):a=Cr(-1,a,c-1),a}function kx(e,t,n){let r=n.length;for(let o=0;o1){r=o;break}for(let o=r+1;o0||n[o]!==e[o])return!1;return!0}function Dx(e,t){let n=e.length>0?e[e.length-1]:1;for(let r=0;r{f(i!==-1,()=>"slice() does not support negative begin indexing.")});let o;return n==null?o=new Array(e.rank).fill(-1):typeof n=="number"?o=[n,...new Array(e.rank-1).fill(-1)]:n.lengthi>=0?i:(f(i===-1,()=>`Negative size values should be exactly -1 but got ${i} for the slice() size at index ${a}.`),e.shape[a]-r[a])),[r,o]}function Fx(e,t,n){const r=u(e,"x","slice");if(r.rank===0)throw new Error("Slicing scalar is not possible");const[o,i]=ds(r,t,n);hl(r,o,i);const a=(p,l)=>(l([r]),p.slice(r,o,i)),s={x:r},c={begin:t,size:n};return g.runKernelFunc(a,s,null,Fi,c)}const G=m({slice_:Fx});function Mx(e){const t=u(e,"x","tanh"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.tanh(t);return o([i]),i},n,null,Ki)}const Wr=m({tanh_:Mx});function Ux(e,t,n,r,o,i){const a=u(e,"forgetBias","basicLSTMCell"),s=u(t,"lstmKernel","basicLSTMCell"),c=u(n,"lstmBias","basicLSTMCell"),p=u(r,"data","basicLSTMCell"),l=u(o,"c","basicLSTMCell"),h=u(i,"h","basicLSTMCell"),d=Z([p,h],1),b=Y(d,s),x=R(b,c),w=x.shape[0],L=x.shape[1]/4,S=[w,L],I=G(x,[0,0],S),N=G(x,[0,L],S),A=G(x,[0,L*2],S),E=G(x,[0,L*3],S),M=R(v(lt(I),Wr(N)),v(l,lt(R(a,A)))),D=v(Wr(M),lt(E));return[M,D]}const xl=m({basicLSTMCell_:Ux});function Wx(e,t,n){const r=u(e,"x","batchToSpaceND"),o=t.reduce((c,p)=>c*p);f(r.rank>=1+t.length,()=>`input rank is ${r.rank} but should be > than blockShape.length ${t.length}`),f(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),f(r.shape[0]%o===0,()=>`input tensor batch is ${r.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${o}`);const i=c=>c.batchToSpaceND(r,t,n),a={x:r},s={blockShape:t,crops:n};return g.runKernelFunc(i,a,null,ko,s)}const Bn=m({batchToSpaceND_:Wx});function Pd(e){let t;return e.rank===0||e.rank===1?t=y(e,[1,1,1,e.size]):e.rank===2?t=y(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=y(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function Bx(e,t,n,r,o,i){i==null&&(i=.001);const a=u(e,"x","batchNorm"),s=u(t,"mean","batchNorm"),c=u(n,"variance","batchNorm");let p;o!=null&&(p=u(o,"scale","batchNorm"));let l;r!=null&&(l=u(r,"offset","batchNorm")),f(s.rank===c.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),f(l==null||s.rank===l.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),f(p==null||s.rank===p.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");const h=Pd(a),d=(L,S)=>(S([h,s,c,p]),L.batchNorm(h,Oa(s),Oa(c),Oa(l),Oa(p),i)),b={x:h,scale:p,offset:l,mean:s,variance:c},x={varianceEpsilon:i},w=g.runKernelFunc(d,b,null,Qo,x);return y(w,a.shape)}function Oa(e){return e==null?null:e.rank===0?y(e,[e.size]):e.rank===1?e:e.rank===2?y(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?y(e,[1,e.shape[0],e.shape[1],e.shape[2]]):e}const Ct=m({batchNorm_:Bx});function $x(e,t,n,r,o,i){const a=u(e,"x","batchNorm"),s=u(t,"mean","batchNorm"),c=u(n,"variance","batchNorm");let p;o!=null&&(p=u(o,"scale","batchNorm"));let l;return r!=null&&(l=u(r,"offset","batchNorm")),f(a.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${a.rank}.`),f(s.rank===2||s.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${s.rank}.`),f(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${c.rank}.`),p!=null&&f(p.rank===2||p.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${p.rank}.`),l!=null&&f(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${l.rank}.`),Ct(a,s,c,l,p,i)}const yl=m({batchNorm2d_:$x});function jx(e,t,n,r,o,i){const a=u(e,"x","batchNorm"),s=u(t,"mean","batchNorm"),c=u(n,"variance","batchNorm");let p;o!=null&&(p=u(o,"scale","batchNorm"));let l;return r!=null&&(l=u(r,"offset","batchNorm")),f(a.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${a.rank}.`),f(s.rank===3||s.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${s.rank}.`),f(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${c.rank}.`),p!=null&&f(p.rank===3||p.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${p.rank}.`),l!=null&&f(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${l.rank}.`),Ct(a,s,c,l,p,i)}const Ll=m({batchNorm3d_:jx});function Gx(e,t,n,r,o,i){const a=u(e,"x","batchNorm"),s=u(t,"mean","batchNorm"),c=u(n,"variance","batchNorm");let p;o!=null&&(p=u(o,"scale","batchNorm"));let l;return r!=null&&(l=u(r,"offset","batchNorm")),f(a.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${a.rank}.`),f(s.rank===4||s.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${s.rank}.`),f(c.rank===4||c.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${c.rank}.`),p!=null&&f(p.rank===4||p.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${p.rank}.`),l!=null&&f(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${l.rank}.`),Ct(a,s,c,l,p,i)}const vl=m({batchNorm4d_:Gx});function Px(e){const t=u(e,"x","clone",null),n=()=>g.makeTensorFromDataId(t.dataId,t.shape,t.dtype),r={x:t};return g.runKernelFunc(n,r,null,ni)}const Et=m({clone_:Px});function qx(e,t){let n=u(e,"broadcastTo","x");const r=n.shape;if(t.some(l=>!(l>0)||l%1!==0))throw new Error(`broadcastTo(): Invalid broadcast shape [${t}].`);if(t.lengthn.rank){const l=n.shape.slice();for(;l.length=0;l--)if(o[l]===t[l])i[l]=1;else if(n.shape[l]!==1)throw new Error(`broadcastTo(): [${r}] cannot be broadcast to [${t}].`);const a=i.map((l,h)=>l>1?h:-1).filter(l=>l>=0);if(a.length===0)return Et(n);const s=l=>l.tile(n,i),c={x:n},p={shape:t,inputShape:o};return g.runKernelFunc(s,c,null,Do,p)}const Br=m({broadcastTo_:qx});function Be(e,t="float32",n){return t=t||"float32",ss(e),new Dr(e,t,n)}function Hx(e){const t=u(e,"x","ceil"),n={x:t};return g.runKernelFunc(r=>r.ceil(t),n,null,Fo)}const Sl=m({ceil_:Hx});function zx(e,t,n){const r=u(e,"x","clipByValue");f(t<=n,()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`);const o={x:r},i={clipValueMin:t,clipValueMax:n};return g.runKernelFunc((a,s)=>{const c=a.clip(r,t,n);return s([r]),c},o,null,Mo,i)}const $n=m({clipByValue_:zx});function Yx(e,t){const n=u(e,"real","complex"),r=u(t,"imag","complex");P(n.shape,r.shape,`real and imag shapes, ${n.shape} and ${r.shape}, must match in call to tf.complex().`);const o=a=>a.complex(n,r),i={real:n,imag:r};return g.runKernelFunc(o,i,null,Mc)}const Ye=m({complex_:Yx});function Vx(e){return Z(e,0)}const Il=m({concat1d_:Vx});function Kx(e,t){return Z(e,t)}const Tl=m({concat2d_:Kx});function Jx(e,t){return Z(e,t)}const Al=m({concat3d_:Jx});function Xx(e,t){return Z(e,t)}const Nl=m({concat4d_:Xx});function Zx(e,t,n,r,o="NHWC",i=[1,1],a){const s=u(e,"x","conv2d"),c=u(t,"filter","conv2d");let p=s,l=!1;s.rank===3&&(l=!0,p=y(s,[1,s.shape[0],s.shape[1],s.shape[2]])),f(p.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${p.rank}.`),f(c.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${c.rank}.`),a!=null&&f(X(r),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${r}.`);const h=o==="NHWC"?p.shape[3]:p.shape[1];f(h===c.shape[2],()=>`Error in conv2d: depth of input (${h}) must match input depth for filter ${c.shape[2]}.`),f(le(n,i),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'`);const d=(L,S)=>{const I=yn(o),N=je(p.shape,c.shape,n,i,r,a,!1,I),A=L.conv2d(p,c,N);return S([p,c]),A},b={x:p,filter:c},x={strides:n,pad:r,dataFormat:o,dilations:i,dimRoundingMode:a},w=g.runKernelFunc(d,b,null,Wo,x);return l?y(w,[w.shape[1],w.shape[2],w.shape[3]]):w}const xe=m({conv2d_:Zx});function Qx(e,t,n,r,o="NWC",i=1,a){const s=u(e,"x","conv1d"),c=u(t,"filter","conv1d");let p=s,l=!1;s.rank===2&&(l=!0,p=y(s,[1,s.shape[0],s.shape[1]])),f(p.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${p.rank}.`),f(c.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${c.rank}.`),a!=null&&f(X(r),()=>`Error in conv1d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${r}.`),f(p.shape[2]===c.shape[1],()=>`Error in conv1d: depth of input (${p.shape[2]}) must match input depth for filter ${c.shape[1]}.`),f(le(n,i),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${i}'`),f(o==="NWC",()=>`Error in conv1d: got dataFormat of ${o} but only NWC is currently supported.`);const h=y(c,[1,c.shape[0],c.shape[1],c.shape[2]]),d=y(p,[p.shape[0],1,p.shape[1],p.shape[2]]),b=[1,n],x=[1,i],w="NHWC",L=xe(d,h,b,r,w,x,a);return l?y(L,[L.shape[2],L.shape[3]]):y(L,[L.shape[0],L.shape[2],L.shape[3]])}const Rl=m({conv1d_:Qx});function ey(e,t,n,r,o,i="NHWC",a){f(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let s=e,c=t,p=!1;t.rank===3&&(p=!0,c=y(t,[1,t.shape[0],t.shape[1],t.shape[2]]),s=[1,e[0],e[1],e[2]]),f(s.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${s.length}.`),f(c.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${c.rank}`),f(n.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`);const l=i==="NHWC"?s[3]:s[1],h=i==="NHWC"?c.shape[3]:c.shape[1];f(l===n.shape[2],()=>`Error in conv2dDerInput: depth of input (${l}) must match input depth for filter ${n.shape[2]}.`),f(h===n.shape[3],()=>`Error in conv2dDerInput: depth of output (${h}) must match output depth for filter ${n.shape[3]}.`),a!=null&&f(X(o),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`);const d=(L,S)=>{const I=1,N=yn(i),A=je(s,n.shape,r,I,o,a,!1,N),E=L.conv2dDerInput(c,n,A);return S([c,n]),E},b={dy:c,filter:n},x={strides:r,pad:o,dataFormat:i,dimRoundingMode:a,inputShape:s},w=g.runKernelFunc(d,b,null,Bo,x);return p?y(w,[w.shape[1],w.shape[2],w.shape[3]]):w}const $r=m({conv2DBackpropInput_:ey});function ty(e,t,n,r,o,i){const a=u(e,"x","conv2dTranspose"),s=u(t,"filter","conv2dTranspose");return $r(n,a,s,r,o,"NHWC",i)}const _l=m({conv2dTranspose_:ty});function ny(e,t,n,r,o="NDHWC",i=[1,1,1]){const a=u(e,"x","conv3d"),s=u(t,"filter","conv3d");let c=a,p=!1;a.rank===4&&(p=!0,c=y(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),f(c.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${c.rank}.`),f(s.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${s.rank}.`),f(c.shape[4]===s.shape[3],()=>`Error in conv3d: depth of input (${c.shape[4]}) must match input depth for filter ${s.shape[3]}.`),f(le(n,i),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'`),f(o==="NDHWC",()=>`Error in conv3d: got dataFormat of ${o} but only NDHWC is currently supported.`);const l=(x,w)=>{const L=Ln(c.shape,s.shape,n,i,r),S=x.conv3d(c,s,L);return w([c,s]),S},h={x:c,filter:s},d={strides:n,pad:r,dataFormat:o,dilations:i},b=g.runKernelFunc(l,h,null,$o,d);return p?y(b,[b.shape[1],b.shape[2],b.shape[3],b.shape[4]]):b}const Cl=m({conv3d_:ny});function ry(e,t,n,r,o){f(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let i=e,a=t,s=!1;t.rank===4&&(s=!0,a=y(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),i=[1,e[0],e[1],e[2],e[3]]);const c=i[4],p=a.shape[4];f(i.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${i.length}.`),f(a.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${a.rank}`),f(n.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`),f(c===n.shape[3],()=>`Error in conv3dDerInput: depth of input (${c}) must match input depth for filter ${n.shape[3]}.`),f(p===n.shape[4],()=>`Error in conv3dDerInput: depth of output (${p}) must match output depth for filter ${n.shape[4]}.`);const l=x=>{const w=1,L=Ln(i,n.shape,r,w,o);return x.conv3dDerInput(a,n,L)},h={dy:a},d={pad:o},b=g.runKernelFunc(l,h,null,Bc,d);return s?y(b,[b.shape[1],b.shape[2],b.shape[3],b.shape[4]]):b}const ka=m({conv3DBackpropInput_:ry});function oy(e,t,n,r,o){const i=u(e,"x","conv3dTranspose"),a=u(t,"filter","conv3dTranspose");return ka(n,i,a,r,o)}const El=m({conv3dTranspose_:oy});function iy(e){const t=u(e,"x","cos"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.cos(t);return o([t]),i},n,null,jo)}const jn=m({cos_:iy});function sy(e){const t=u(e,"x","cosh"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.cosh(t);return o([t]),i},n,null,Go)}const ms=m({cosh_:sy});function ay(e,t=0,n=!1,r=!1){const o=u(e,"x","cumsum"),i=(c,p)=>{const l=ge([t],o.rank);let h=o;l!=null&&(h=K(o,l));const d=De(1,o.rank)[0];let b=c.cumsum(h,d,n,r);if(p([o]),l!=null){const x=Un(l);b=K(b,x)}return b},a={x:o},s={axis:t,exclusive:n,reverse:r};return g.runKernelFunc(i,a,null,Po,s)}const fs=m({cumsum_:ay});function cy(e,t,n="NHWC"){const r=u(e,"x","depthToSpace"),o=n==="NHWC"?r.shape[1]:r.shape[2],i=n==="NHWC"?r.shape[2]:r.shape[3],a=n==="NHWC"?r.shape[3]:r.shape[1];f(o*t>=0,()=>`Negative dimension size caused by overflow when multiplying
${o} and ${t} for depthToSpace with input shape
${r.shape}`),f(i*t>=0,()=>`Negative dimension size caused by overflow when multiplying
${i} and ${t} for depthToSpace with input shape
${r.shape}`),f(a%(t*t)===0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${a} for depthToSpace with input shape ${r.shape}`);const s=l=>l.depthToSpace(r,t,n),c={x:r},p={blockSize:t,dataFormat:n};return g.runKernelFunc(s,c,null,jc,p)}const Ol=m({depthToSpace_:cy});function py(e,t,n,r,o="NHWC",i=[1,1],a){const s=u(e,"x","depthwiseConv2d"),c=u(t,"filter","depthwiseConv2d");let p=s,l=!1;s.rank===3&&(l=!0,p=y(s,[1,s.shape[0],s.shape[1],s.shape[2]])),f(p.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${p.rank}.`),f(c.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${c.rank}.`),f(p.shape[3]===c.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${p.shape[3]}) must match the inChannels dimension in filter ${c.shape[2]}.`),a!=null&&f(X(r),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${r}.`);const h=(w,L)=>{i==null&&(i=[1,1]),f(le(n,i),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'`);const S=je(p.shape,c.shape,n,i,r,a,!0),I=w.depthwiseConv2D(p,c,S);return L([p,c]),I},d={x:p,filter:c},b={strides:n,pad:r,dataFormat:o,dilations:i,dimRoundingMode:a},x=g.runKernelFunc(h,d,null,qo,b);return l?y(x,[x.shape[1],x.shape[2],x.shape[3]]):x}const en=m({depthwiseConv2d_:py});function ly(e){const t=u(e,"x","diag"),n=o=>{const i=y(t,[t.size]),a=o.diag(i),s=[...e.shape,...e.shape];return y(a,s)},r={x:t};return g.runKernelFunc(n,r,null,qc)}const kl=m({diag_:ly});function hy(e,t,n,r,o=[1,1],i="NHWC"){const a=u(e,"x","dilation2d"),s=u(t,"filter","dilation2d");f(a.rank===3||a.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${a.rank}.`),f(s.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${s.rank}.`),f(i==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${i}`);let c=a,p=!1;a.rank===3&&(c=y(a,[1,a.shape[0],a.shape[1],a.shape[2]]),p=!0);const l={x:c,filter:s},h={strides:n,pad:r,dilations:o},d=g.runKernel(Ho,l,h);return p?y(d,[d.shape[1],d.shape[2],d.shape[3]]):d}const Dl=m({dilation2d_:hy});function uy(e,t){let n=u(e,"a","floorDiv"),r=u(t,"b","floorDiv");[n,r]=V(n,r);const o=(a,s)=>{const c=a.floorDiv(n,r);return s([n,r]),c},i={a:n,b:r};return g.runKernelFunc(o,i,null,Zo)}const gs=m({floorDiv_:uy});function dy(e,t){let n=u(e,"a","div"),r=u(t,"b","div");if([n,r]=V(n,r),n.dtype==="int32"&&r.dtype==="int32")return gs(n,r);const o=(s,c)=>{const p=s.realDivide(n,r);return c([n,r]),p},i={a:n,b:r},a={};return g.runKernelFunc(o,i,null,zo,a)}const F=m({div_:dy});function my(e,t){const n=e.length,r=[];for(let o=0;o1&&a===1&&r.unshift(i)}return r}function ae(e,t){const n=[];for(let r=0;r1)&&n.unshift(i)}return n}function q(e,t){const n=[],r=Math.max(e.length,t.length);for(let o=0;oa.equal(n,r),i={a:n,b:r};return g.runKernelFunc(o,i,null,Vc)}const tn=m({equal_:fy});function gy(e,t,n){const r=u(t,"a","where"),o=u(n,"b","where"),i=u(e,"condition","where","bool"),a=q(r.shape,o.shape),s=Br(r,a),c=Br(o,a);i.rank===1&&f(i.shape[0]===r.shape[0],()=>"The first dimension of `a` must match the size of `condition`."),i.rank!==1&&P(i.shape,c.shape,"Error in where: ");const p=(h,d)=>{const b=h.select(i,s,c);return d([i]),b},l={condition:i,t:s,e:c};return g.runKernelFunc(p,l,null,ki)}const Oe=m({where_:gy});function by(e){const t=u(e,"x","zerosLike"),n={x:t};return g.runKernelFunc(r=>r.zerosLike(t),n,null,es)}const W=m({zerosLike_:by});function wy(e,t){let n=u(e,"a","div"),r=u(t,"b","div");[n,r]=V(n,r);const o=F(n,r),i=W(o),a=tn(r,i);return Oe(a,i,o)}const Fl=m({divNoNan_:wy});function xy(e,t){const n=u(e,"t1","dot"),r=u(t,"t2","dot");f((n.rank===1||n.rank===2)&&(r.rank===1||r.rank===2),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${r.rank}.`);const o=n.rank===1?n.size:n.shape[1],i=r.rank===1?r.size:r.shape[0];if(f(o===i,()=>`Error in dot: inner dimensions of inputs must match, but got ${o} and ${i}.`),n.rank===1&&r.rank===1){const a=y(n,[1,-1]),s=y(r,[-1,1]),c=Y(a,s);return y(c,[])}else if(n.rank===1&&r.rank===2){const a=y(n,[1,-1]),s=y(r,[r.shape[0],r.shape[1]]),c=Y(a,s);return y(c,[c.size])}else if(n.rank===2&&r.rank===1){const a=y(r,[-1,1]),s=Y(n,a);return y(s,[s.size])}else{const a=y(r,[r.shape[0],r.shape[1]]),s=Y(n,a);return s}}const Ml=m({dot_:xy});function yy(e){const t=u(e,"x","elu"),n=(o,i)=>{const a=o.elu(t);return i([a]),a},r={x:t};return g.runKernelFunc(n,r,null,Yo)}const bs=m({elu_:yy});function Ly(e){let t=u(e,"x","erf");f(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),t.dtype==="int32"&&(t=C(t,"float32"));const n={x:t};return g.runKernelFunc((r,o)=>{const i=r.erf(t);return o([t]),i},n,null,Vo)}const Ul=m({erf_:Ly});function vy(e){const t=u(e,"x","exp"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.exp(t);return o([i]),i},n,null,Ko)}const Se=m({exp_:vy});function Sy(e,t=0){const n=null,r=u(e,"x","expandDims",n);f(t<=r.rank,()=>"Axis must be <= rank of the tensor");const o=r.shape.slice();return t<0&&(f(-(r.rank+1)<=t,()=>`Axis must be in the interval [${-(r.rank+1)}, ${r.rank}]`),t=r.rank+t+1),o.splice(t,0,1),y(r,o)}const et=m({expandDims_:Sy});function Iy(e){const t=u(e,"x","expm1"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.expm1(t);return o([t]),i},n,null,Jo)}const Wl=m({expm1_:Iy});function Ty(e,t){const n=null,r=u(e,"x","tile",n);f(r.rank===t.length,()=>`Error in transpose: rank of input ${r.rank} must match length of reps ${t}.`);const o=(c,p)=>{const l=c.tile(r,t);return p([r]),l},i=[r],a={x:r},s={reps:t};return g.runKernelFunc(o,a,null,Ji,s,i)}const Ot=m({tile_:Ty});function Ay(e,t,n,r="float32"){t==null&&(t=e);const o=Be([e,t],r),i=e<=t?e:t;for(let s=0;s`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);const t={input:e};return g.runKernelFunc(n=>{const r=e.shape[e.shape.length-1],o=e.size/r,i=e.as2D(o,r),a=n.fft(i);return a.reshape(e.shape)},t,null,Kc)}const Gn=m({fft_:Ny});function Ge(e,t,n){const r={shape:e,value:t,dtype:n};return g.runKernelFunc(o=>o.fill(e,t,n),{},null,Jc,r)}function Ry(e){const t=u(e,"x","floor"),n={x:t};return g.runKernelFunc(r=>r.floor(t),n,null,Xo)}const Pn=m({floor_:Ry});const Da=30;function _y(e){return e<=Da?e:kr(e,Math.floor(Math.sqrt(e)))}const qd={};Re(qd,{collectGatherOpShapeInfo:()=>Bl,computeOutShape:()=>Ey,segOpComputeOptimalWindowSize:()=>Cy});function Cy(e,t){let n=!1,r;for(e<=Da?(r=e,n=!0):r=kr(e,Math.floor(Math.sqrt(e)));!n;)r>t||r===e?n=!0:r=kr(e,r+1);return r}function Ey(e,t,n){const r=[],o=e.length;for(let i=0;i{const l=z(n,r.shape)[0],h=Bl(r,o,l),d=c.gather(r,y(o,[o.size]),l);return p([r,o]),y(d,h.outputShape)};return g.runKernelFunc(s,i,null,ei,a)}const qn=m({gather_:Oy});function ky(e,t){let n=u(e,"a","greater"),r=u(t,"b","greater");[n,r]=V(n,r),q(n.shape,r.shape);const o=a=>a.greater(n,r),i={a:n,b:r};return g.runKernelFunc(o,i,null,Qc)}const tt=m({greater_:ky});function Dy(e,t){let n=u(e,"a","greaterEqual"),r=u(t,"b","greaterEqual");[n,r]=V(n,r),q(n.shape,r.shape);const o=(a,s)=>{const c=a.greaterEqual(n,r);return s([n,r]),c},i={a:n,b:r};return g.runKernelFunc(o,i,null,ti)}const ht=m({greaterEqual_:Dy});function Fy(e){f(e.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);const t={input:e};return g.runKernelFunc(n=>{const r=e.shape[e.shape.length-1],o=e.size/r,i=y(e,[o,r]),a=n.ifft(i);return y(a,e.shape)},t,null,ep)}const vn=m({ifft_:Fy});function My(e){const t=u(e,"input","imag"),n=o=>o.imag(t),r={input:t};return g.runKernelFunc(n,r,null,tp)}const nn=m({imag_:My});function Uy(e){const t=u(e,"input","real"),n=o=>o.real(t),r={input:t};return g.runKernelFunc(n,r,null,wp)}const zt=m({real_:Uy});function Wy(e,t){const n=u(e,"x","reverse"),r=a=>{const s=z(t,n.shape);if(n.rank===0)return Et(n);const c=a.reverse(n,s);return y(c,n.shape)},o={x:n},i={dims:t};return g.runKernelFunc(r,o,null,Ci,i)}const Ve=m({reverse_:Wy});function _(e,t){if((_e(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"&&_e(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");const n=[],r=[];return He(e,n,r,t)}function By(e){const t=e.shape[e.shape.length-1],n=e.size/t;let r;if(t<=2){const o=y(e,[n,t]);r=vn(o)}else{const o=[n,2*(t-1)],i=y(zt(e),[n,t]),a=y(nn(e),[n,t]),s=Ve(G(i,[0,1],[n,t-2]),1),c=v(Ve(G(a,[0,1],[n,t-2]),1),_(-1)),p=Z([i,s],1),l=Z([a,c],1),h=y(Ye(p,l),[o[0],o[1]]);r=vn(h)}if(r=zt(r),e.rank===3&&e.shape[0]!==0){const o=r,i=e.shape[0];r=y(r,[i,r.shape[0]/i,r.shape[1]]),o.dispose()}return r}const xs=m({irfft_:By});function $y(e){const t=u(e,"x","isFinite"),n={x:t};return g.runKernelFunc(r=>r.isFinite(t),n,null,ri)}const $l=m({isFinite_:$y});function jy(e){const t=u(e,"x","isInf"),n={x:t};return g.runKernelFunc(r=>r.isInf(t),n,null,oi)}const jl=m({isInf_:jy});function Gy(e){const t=u(e,"x","isNaN"),n={x:t};return g.runKernelFunc(r=>r.isNaN(t),n,null,ii)}const Gl=m({isNaN_:Gy});function Py(e,t){let n=u(e,"a","maximum"),r=u(t,"b","maximum");[n,r]=V(n,r),n.dtype==="bool"&&(n=C(n,"int32"),r=C(r,"int32")),q(n.shape,r.shape);const o=(a,s)=>{const c=a.maximum(n,r);return s([n,r]),c},i={a:n,b:r};return g.runKernelFunc(o,i,null,hi)}const kt=m({maximum_:Py});function qy(e,t=.2){const n=u(e,"x","leakyRelu");return kt(v(_(t),n),n)}const Pl=m({leakyRelu_:qy});function Hy(e,t){let n=u(e,"a","less"),r=u(t,"b","less");[n,r]=V(n,r),q(n.shape,r.shape);const o=a=>a.less(n,r),i={a:n,b:r};return g.runKernelFunc(o,i,null,np)}const Hn=m({less_:Hy});function zy(e,t){let n=u(e,"a","lessEqual"),r=u(t,"b","lessEqual");[n,r]=V(n,r),q(n.shape,r.shape);const o=(a,s)=>{const c=a.lessEqual(n,r);return s([n,r]),c},i={a:n,b:r};return g.runKernelFunc(o,i,null,rp)}const ut=m({lessEqual_:zy});function ql(e,t,n){if(n<=0)throw new Error("The number of values should be positive.");const r={start:e,stop:t,num:n};return g.runKernelFunc(o=>o.linspace(e,t,n),{},null,op,r)}function Yy(e,t=5,n=1,r=1,o=.5){const i=u(e,"x","localResponseNormalization");f(i.rank===4||i.rank===3,()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got
rank ${i.rank}.`),f(X(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let a=i,s=!1;i.rank===3&&(s=!0,a=y(i,[1,i.shape[0],i.shape[1],i.shape[2]]));const c=(d,b)=>{const x=d.localResponseNormalization4D(a,t,n,r,o);return b([a,x]),x},p={x:a},l={depthRadius:t,bias:n,alpha:r,beta:o},h=g.runKernelFunc(c,p,null,pi,l);return s?y(h,[h.shape[1],h.shape[2],h.shape[3]]):h}const Hl=m({localResponseNormalization_:Yy});function Vy(e){const t=u(e,"x","log"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.log(t);return o([t]),i},n,null,si)}const yt=m({log_:Vy});function Ky(e){const t=u(e,"x","log1p"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.log1p(t);return o([t]),i},n,null,ai)}const ys=m({log1p_:Ky});function Jy(e){return f(jt(e),()=>"The f passed in grad(f) must be a function"),(t,n)=>{const r=u(t,"x","tf.grad",null),o=n!=null?u(n,"dy","tf.grad"):null;return g.tidy(()=>{const{value:i,grads:a}=g.gradients(()=>e(r),[r],o);return o!=null&&P(i.shape,o.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Fa(a),a[0]})}}function Xy(e){return f(jt(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{f(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");const r=Zt(t,"args","tf.grads",null),o=n!=null?u(n,"dy","tf.grads"):null;return g.tidy(()=>{const{value:i,grads:a}=g.gradients(()=>e(...r),r,o);return o!=null&&P(i.shape,o.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Fa(a),a})}}function Zy(e){return f(jt(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{f(t instanceof ee,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),f(n==null||n instanceof ee,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");const{grads:r,value:o}=g.gradients(()=>e(t),[t],n);return Fa(r),{grad:r[0],value:o}}}function Qy(e){return f(jt(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{f(Array.isArray(t)&&t.every(o=>o instanceof ee),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),f(n==null||n instanceof ee,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");const r=g.gradients(()=>e(...t),t,n);return n!=null&&P(r.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Fa(r.grads),r}}function zl(e,t){f(jt(e),()=>"The f passed in variableGrads(f) must be a function"),f(t==null||Array.isArray(t)&&t.every(p=>p instanceof Ht),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");const n=t!=null;if(!n){t=[];for(const p in g.registeredVariables)t.push(g.registeredVariables[p])}const r=n?t.filter(p=>!p.trainable):null,o=t.length;t=t.filter(p=>p.trainable),f(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${o} variables is trainable.`);const i=!0,{value:a,grads:s}=g.gradients(e,t,null,i);f(s.some(p=>p!=null),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),f(a.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${a.rank} tensor`);const c={};return t.forEach((p,l)=>{s[l]!=null&&(c[p.name]=s[l])}),r!=null&&r.forEach(p=>c[p.name]=null),{value:a,grads:c}}function Ke(e){return g.customGrad(e)}function Fa(e){const t=e.filter(n=>n==null).length;if(t>0)throw new Error(`Cannot compute gradient of y=f(x) with respect to x. Make sure that
the f you passed encloses all operations that lead from x to y.`)}function eL(e){const t=u(e,"x","neg"),n={x:t};return g.runKernelFunc(r=>r.neg(t),n,null,wi)}const ne=m({neg_:eL});function tL(e){const t=u(e,"x","softplus"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.softplus(t);return o([t]),i},n,null,$i)}const Ls=m({softplus_:tL});function nL(e){const t=u(e,"x","logSigmoid"),n=Ke(r=>{const o=ne(Ls(ne(r))),i=a=>{const s=v(a,lt(ne(r)));return s};return{value:o,gradFunc:i}});return n(t)}const Yl=m({logSigmoid_:nL});function rL(e,t=null,n=!1){const r=u(e,"x","max"),o=(s,c)=>{const p=z(t,r.shape);let l=p;const h=ge(l,r.rank);let d=r;h!=null&&(d=K(r,h),l=De(l.length,d.rank));const b=s.max(d,l);h!=null&&d.dispose();let x=b;if(n){const w=we(x.shape,z(t,r.shape));x=y(x,w),b.dispose()}return c([r,x]),x},i={x:r},a={reductionIndices:t,keepDims:n};return g.runKernelFunc(o,i,null,li,a)}const dt=m({max_:rL});function oL(e,t){let n=u(e,"a","sub"),r=u(t,"b","sub");[n,r]=V(n,r);const o=(a,s)=>{const c=a.subtract(n,r);return s([n,r]),c},i={a:n,b:r};return g.runKernelFunc(o,i,null,Yi)}const O=m({sub_:oL});function iL(e,t=null,n=!1){let r=u(e,"x","sum");r.dtype==="bool"&&(r=C(r,"int32"));const o=(s,c)=>{c([r]);const p=z(t,r.shape),l=ge(p,r.rank);let h=p,d=r;l!=null&&(d=K(r,l),h=De(h.length,r.rank));let b=s.sum(d,h);if(n){const x=we(b.shape,p);b=y(b,x)}return b},i={x:r},a={axis:t,keepDims:n};return g.runKernelFunc(o,i,null,Gi,a)}const U=m({sum_:iL});function sL(e,t=-1){const n=u(e,"logits","logSoftmax");if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and axis was ${t}`);const r=(a,s)=>{const c=!0,p=dt(e,t,!0),l=O(e,p),h=O(C(l,"float32"),yt(U(Se(l),t,c)));return s([h]),h},o={logits:n},i={axis:t};return g.runKernelFunc(r,o,null,ci,i)}const Vl=m({logSoftmax_:sL});function aL(e,t=null,n=!1){const r=u(e,"x","logSumExp"),o=z(t,r.shape),i=dt(r,o,!0),a=O(r,i),s=Se(a),c=U(s,o),p=yt(c),l=R(y(i,p.shape),p);if(n){const h=we(l.shape,o);return y(l,h)}return l}const vs=m({logSumExp_:aL});function cL(e,t){const n=u(e,"a","logicalAnd","bool"),r=u(t,"b","logicalAnd","bool");q(n.shape,r.shape);const o={a:n,b:r};return g.runKernelFunc(i=>i.logicalAnd(n,r),o,null,ip)}const Lt=m({logicalAnd_:cL});function pL(e){const t=u(e,"x","logicalNot","bool"),n={x:t};return g.runKernelFunc(r=>r.logicalNot(t),n,null,sp)}const zn=m({logicalNot_:pL});function lL(e,t){const n=u(e,"a","logicalOr","bool"),r=u(t,"b","logicalOr","bool");q(n.shape,r.shape);const o={a:n,b:r};return g.runKernelFunc(i=>i.logicalOr(n,r),o,null,ap)}const Ss=m({logicalOr_:lL});function hL(e,t){const n=u(e,"a","logicalXor","bool"),r=u(t,"b","logicalXor","bool");return q(n.shape,r.shape),Lt(Ss(e,t),zn(Lt(e,t)))}const Kl=m({logicalXor_:hL});function uL(e,t,n,r,o){const i=u(e,"x","maxPool"),a=1;let s=i,c=!1;i.rank===3&&(c=!0,s=y(i,[1,i.shape[0],i.shape[1],i.shape[2]])),f(s.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${s.rank}.`),f(le(n,a),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),o!=null&&f(X(r),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);const p=(b,x)=>{const w=_t(s.shape,t,n,1,r,o);let L;return w.filterWidth===1&&w.filterHeight===1&&Te(w.inShape,w.outShape)?L=s.clone():L=b.maxPool(s,w),x([s,L]),L},l={x:s},h={filterSize:t,strides:n,pad:r,dimRoundingMode:o},d=g.runKernelFunc(p,l,null,ui,h);return c?y(d,[d.shape[1],d.shape[2],d.shape[3]]):d}const Ae=m({maxPool_:uL});function dL(e,t=[1,1,1],n,r,o,i="NDHWC",a){a==null?a=[1,1,1]:Le("dilations is deprecated, this field will be gone in v3.0.0.");const s=u(e,"x","maxPool3d");let c=s,p=!1;s.rank===4&&(p=!0,c=y(s,[1,s.shape[0],s.shape[1],s.shape[2],s.shape[3]])),f(c.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${c.rank}.`),f(i==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${i}`),f(le(n,a),()=>`Error in maxPool3d: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),o!=null&&f(X(r),()=>`Error in maxPool3d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);const l=(x,w)=>{a==null&&(a=[1,1,1]);const L=Qt(c.shape,t,n,a,r,o,i),S=x.maxPool3d(c,L);return w([c,S]),S},h={x:c},d={filterSize:t,strides:n,pad:r,dimRoundingMode:o,dataFormat:i,dilations:a},b=g.runKernelFunc(l,h,null,di,d);return p?y(b,[b.shape[1],b.shape[2],b.shape[3],b.shape[4]]):b}const Jl=m({maxPool3d_:dL});function mL(e,t,n,r,o=!1){const i=u(e,"x","maxPoolWithArgmax"),a={x:i},s={filterSize:t,strides:n,pad:r,includeBatchInIndex:o},c=g.runKernel(hp,a,s);return{result:c[0],indexes:c[1]}}const Xl=m({maxPoolWithArgmax_:mL});function Ce(e,t="float32"){if(t==="complex64"){const r=Ce(e,"float32"),o=Ce(e,"float32");return Ye(r,o)}const n=Pt(Q(e),t);return g.makeTensor(n,e,t)}function vt(e,t="float32"){if(t==="complex64"){const r=vt(e,"float32"),o=Ce(e,"float32");return Ye(r,o)}const n=is(Q(e),t);return g.makeTensor(n,e,t)}function fL(e,t=null,n=!1){const r=u(e,"x","mean"),o=z(t,r.shape),i=Kp(r.shape,o),a=i[1],s=Q(a),c=Ke(p=>{const l=_(s),h=l.dtype===p.dtype?p:C(p,l.dtype),d=F(h,l),b=U(d,t,n),x=w=>{const L=p.shape.slice();o.forEach(N=>{L[N]=1});const S=y(w,L),I=F(v(S,vt(p.shape,"float32")),s);return I};return{value:b,gradFunc:x}});return c(r)}const Sn=m({mean_:fL});function gL(e,t=null,n=!1){const r=u(e,"x","min"),o=(s,c)=>{const p=z(t,r.shape);let l=p;const h=ge(l,r.rank);let d=r;h!=null&&(d=K(r,h),l=De(l.length,r.rank));const b=s.min(d,l);h!=null&&d.dispose();let x=b;if(n){const w=we(x.shape,p);x=y(b,w),b.dispose()}return c([r,x]),x},i={x:r},a={axis:t,keepDims:n};return g.runKernelFunc(o,i,null,mi,a)}const In=m({min_:gL});function bL(e,t){let n=u(e,"a","minimum"),r=u(t,"b","minimum");[n,r]=V(n,r),n.dtype==="bool"&&(n=C(n,"int32"),r=C(r,"int32")),q(n.shape,r.shape);const o=(a,s)=>{const c=a.minimum(n,r);return s([n,r]),c},i={a:n,b:r};return g.runKernelFunc(o,i,null,fi)}const Yn=m({minimum_:bL});function wL(e,t){let n=u(e,"a","mod"),r=u(t,"b","mod");[n,r]=V(n,r);const o=(a,s)=>{const c=a.mod(n,r);return s([n,r]),c},i={a:n,b:r};return g.runKernelFunc(o,i,null,gi)}const Is=m({mod_:wL});function xL(e){const t=u(e,"x","square"),n={},r=[t],o=[];return g.runKernelFunc((i,a)=>(a([t]),i.square(t)),{x:t},null,"Square",n,r,o)}const H=m({square_:xL});function yL(e,t=null,n=!1){e=u(e,"x","moments");const r=z(t,e.shape),o=Sn(e,r,n);let i=o.shape;n||(i=we(o.shape,r));const a=H(O(C(e,"float32"),y(o,i))),s=Sn(a,r,n);return{mean:o,variance:s}}const Zl=m({moments_:yL});function LL(e,t,n,r){const o=u(t,"data","multiRNNCell"),i=Zt(n,"c","multiRNNCell"),a=Zt(r,"h","multiRNNCell");let s=o;const c=[];for(let h=0;h2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${a}`);n=n||Math.random();const s=a===1?y(o,[1,-1]):o,c=g.runKernelFunc(p=>p.multinomial(s,r,t,n),{logits2D:s});return a===1?y(c,[c.size]):c}const eh=m({multinomial_:vL});function SL(e,t){let n=u(e,"a","notEqual"),r=u(t,"b","notEqual");[n,r]=V(n,r),q(n.shape,r.shape);const o=a=>a.notEqual(n,r),i={a:n,b:r};return g.runKernelFunc(o,i,null,up)}const Vn=m({notEqual_:SL});function IL(e,t,n=1,r=0){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);const o=u(e,"indices","oneHot","int32"),i=[...o.shape,t],a=(p,l)=>(l([o]),y(p.oneHot(y(o,[o.size]),t,n,r),i)),s={indices:o},c={depth:t,onValue:n,offValue:r};return g.runKernelFunc(a,s,null,yi,c)}const jr=m({oneHot_:IL});function TL(e){const t=u(e,"x","onesLike"),n=(o,i)=>{if(t.dtype==="complex64"){const a=Ma(zt(t)),s=W(nn(t));return Ye(a,s)}return o.onesLike(t)},r={x:t};return g.runKernelFunc(n,r,null,xi)}const Ma=m({onesLike_:TL});function AL(e,t){const n=u(e,"v1","outerProduct"),r=u(t,"v2","outerProduct");f(n.rank===1&&r.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${r.rank}.`);const o=y(n,[-1,1]),i=y(r,[1,-1]);return Y(o,i)}const th=m({outerProduct_:AL});function NL(e,t,n=0){const r=u(e,"x","pad");if(r.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");const o=(s,c)=>(c([r]),s.pad(r,t,n)),i={paddings:t,constantValue:n},a={x:r};return g.runKernelFunc(o,a,null,Li,i)}const Pe=m({pad_:NL});function RL(e,t,n=0){return f(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),Pe(e,[t],n)}const nh=m({pad1d_:RL});function _L(e,t,n=0){return f(t.length===2&&t[0].length===2&&t[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Pe(e,t,n)}const rh=m({pad2d_:_L});function CL(e,t,n=0){return f(t.length===3&&t[0].length===2&&t[1].length===2&&t[2].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Pe(e,t,n)}const oh=m({pad3d_:CL});function EL(e,t,n=0){return f(t.length===4&&t[0].length===2&&t[1].length===2&&t[2].length===2&&t[3].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Pe(e,t,n)}const ih=m({pad4d_:EL});function OL(e,t,n){const r=u(e,"x","spaceToBatchND");f(r.rank>=1+t.length,()=>`input rank ${r.rank} should be > than [blockShape] ${t.length}`),f(n.length===t.length,()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`),f(r.shape.reduce((s,c,p)=>p>0&&p<=t.length?s&&(c+n[p-1][0]+n[p-1][1])%t[p-1]===0:s,!0),()=>`input spatial dimensions ${r.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`);const o=s=>s.spaceToBatchND(r,t,n),i={x:r},a={blockShape:t,paddings:n};return g.runKernelFunc(o,i,null,Pi,a)}const Kn=m({spaceToBatchND_:OL});function FL(e,t,n,r,o,i){o==null&&(o=[1,1]),i==null&&(i=1),r===0&&(r="valid");const a=u(e,"x","maxPool");let s=a,c=!1;a.rank===3&&(c=!0,s=y(a,[1,a.shape[0],a.shape[1],a.shape[2]])),f(le(i,o),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${i} and dilations '${o}'`);const p=_t(s.shape,t,i,o,r),l=[p.dilationHeight,p.dilationWidth];let h;r==="same"?h=DL([p.filterHeight,p.filterWidth],l):h=[[0,0],[0,0]];const d=l[0]===1&&l[1]===1,[b,x]=kL([p.inHeight,p.inWidth],l,h),w=d?r:"valid",L=d?s:Kn(s,l,b),S=n==="avg"?()=>pt(L,t,i,w):()=>Ae(L,t,i,w),I=S(),N=d?I:Bn(I,l,x);return c?y(N,[N.shape[1],N.shape[2],N.shape[3]]):N}function kL(e,t,n){const r=n.map(l=>l[0]),o=n.map(l=>l[1]),i=e.concat(r,o),a=t.map((l,h)=>(l-i[h]%l)%l),s=o.map((l,h)=>l+a[h]),c=t.map((l,h)=>[r[h],s[h]]),p=t.map((l,h)=>[0,a[h]]);return[c,p]}function DL(e,t){const n=e.map((a,s)=>a+(a-1)*(t[s]-1)),r=n.map(a=>a-1),o=r.map(a=>Math.floor(a/2)),i=r.map((a,s)=>a-o[s]);return r.map((a,s)=>[o[s],i[s]])}const sh=m({pool_:FL});function ML(e,t){let n=u(e,"base","pow"),r=u(t,"exp","pow");[n,r]=V(n,r);const o={a:n,b:r},i=(a,s)=>{const c=a.pow(n,r);return s([n,r,c]),c};return g.runKernelFunc(i,o,null,vi)}const Je=m({pow_:ML});function UL(e,t){const n=u(e,"x","prelu"),r=u(t,"alpha","prelu"),o=(a,s)=>{const c=a.prelu(n,r);return s([n,r]),c},i={x:n,alpha:r};return g.runKernelFunc(o,i,null,Si)}const Ts=m({prelu_:UL});function ah(e,t=!1){console.log(e.toString(t))}function WL(e,t=null,n=!1){let r=u(e,"x","prod");const o=s=>{r.dtype==="bool"&&(r=C(r,"int32"));const c=z(t,r.shape),p=ge(c,r.rank);let l=c,h=r;p!=null&&(h=K(r,p),l=De(l.length,r.rank));let d=s.prod(h,l);if(n){const b=we(d.shape,c);d=y(d,b)}return d},i={x:r},a={axis:t,keepDims:n};return g.runKernelFunc(o,i,null,gp,a)}const ch=m({prod_:WL});function BL(e,t,n){const r=Q(e);let o=null;if(n==null||n==="float32")o=new Float32Array(r);else if(n==="int32")o=new Int32Array(r);else if(n==="bool")o=new Uint8Array(r);else throw new Error(`Unknown data type ${n}`);for(let i=0;izd,expectArrayBuffersEqual:()=>zL,expectArraysClose:()=>jL,expectArraysEqual:()=>PL,expectNumbersClose:()=>qL,expectPromiseToFail:()=>GL,expectValuesInRange:()=>HL,testEpsilon:()=>lh});const $L=.001,zd=.1;function jL(e,t,n){return n==null&&(n=lh()),hh(e,t,(r,o)=>uh(r,o,n))}function lh(){return g.backend.floatPrecision()===32?$L:zd}function hh(e,t,n){let r=!0;if((_e(e)||_e(t))&&(r=!1),_e(e)&&_e(t)&&(r=!0),r){const a=e.constructor.name,s=t.constructor.name;if(a!==s)throw new Error(`Arrays are of different type. Actual: ${a}. Expected: ${s}`)}if(Array.isArray(e)&&Array.isArray(t)){const a=We(e),s=We(t);if(!Te(a,s))throw new Error(`Arrays have different shapes. Actual: [${a}]. Expected: [${s}]`)}const o=_e(e)?e:$t(e),i=_e(t)?t:$t(t);if(o.length!==i.length)throw new Error(`Arrays have different lengths actual: ${o.length} vs expected: ${i.length}.
Actual: ${o}.
Expected: ${i}.`);for(let a=0;at.fail(),()=>t())}function PL(e,t){const n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return Rt(e)||Rt(e[0])||Rt(t)||Rt(t[0])?hh(e,n,(r,o)=>r==o):hh(e,t,(r,o)=>uh(r,o,0))}function qL(e,t,n){if(n==null&&(n=lh()),!uh(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function uh(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function HL(e,t,n){for(let r=0;rn)throw new Error(`Value out of range:${e[r]} low: ${t}, high: ${n}`)}function zL(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}const Ua=fu(Eu());class As{constructor(e,t,n,r,o){this.mean=e,this.stdDev=t,this.dtype=n,this.nextVal=NaN,this.truncated=r,this.truncated&&(this.upper=this.mean+this.stdDev*2,this.lower=this.mean-this.stdDev*2);const i=o||Math.random();this.random=Ua.alea(i.toString())}nextValue(){if(!isNaN(this.nextVal)){const r=this.nextVal;return this.nextVal=NaN,r}let e,t,n=!1;for(;!n;){let r,o,i;do r=2*this.random()-1,o=2*this.random()-1,i=r*r+o*o;while(i>=1||i===0);const a=Math.sqrt(-2*Math.log(i)/i);e=this.mean+this.stdDev*r*a,t=this.mean+this.stdDev*o*a,(!this.truncated||this.isValidTruncated(e))&&(n=!0)}return(!this.truncated||this.isValidTruncated(t))&&(this.nextVal=this.convertValue(t)),this.convertValue(e)}convertValue(e){return this.dtype==null||this.dtype==="float32"?e:Math.round(e)}isValidTruncated(e){return e<=this.upper&&e>=this.lower}}class Yd{constructor(e,t,n,r){this.alpha=e,this.beta=1/t,this.dtype=n;const o=r||Math.random();this.randu=Ua.alea(o.toString()),this.randn=new As(0,1,n,!1,this.randu()),e<1?this.d=e+2/3:this.d=e-1/3,this.c=1/Math.sqrt(9*this.d)}nextValue(){let e,t,n,r,o,i;for(;;){do r=this.randn.nextValue(),i=1+this.c*r;while(i<=0);if(i*=i*i,e=r*r,t=1-.331*e*e,n=.5*e+this.d*(1-i+Math.log(i)),o=this.randu(),othis.dtype==null||this.dtype==="float32",this.min=e,this.range=t-e,this.dtype=n,r==null&&(r=Math.random()),typeof r=="number"&&(r=r.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=Ua.alea(r)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}function YL(e,t,n=1,r="float32",o){if(n==null&&(n=1),r==null&&(r="float32"),r!=="float32"&&r!=="int32")throw new Error(`Unsupported data type ${r}`);const i=new Yd(t,n,r,o),a=Be(e,r);for(let s=0;s{const a=e===t,s=e1;if(a||s||c)return Ce([0],r);const p=Math.abs(Math.ceil((t-e)/n)),l=Pt(p,r);t{const i=r.reciprocal(t);return o([t]),i},n,null,Ii)}const fh=m({reciprocal_:JL});function XL(e){const t=u(e,"x","relu"),n=(o,i)=>(i([t]),t.dtype==="bool"?C(t,"int32"):o.relu(t)),r={x:t};return g.runKernelFunc(n,r,null,Ti)}const ie=m({relu_:XL});function ZL(e){const t=u(e,"x","relu6"),n=(o,i)=>(i([t]),t.dtype==="bool"?C(t,"int32"):o.relu6(t)),r={x:t};return g.runKernelFunc(n,r,null,_i)}const Rs=m({relu6_:ZL});function QL(e){const t=u(e,"x","reverse");return f(t.rank===1,()=>`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),Ve(t,0)}const gh=m({reverse1d_:QL});function ev(e,t){const n=u(e,"x","reverse");return f(n.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`),Ve(n,t)}const bh=m({reverse2d_:ev});function tv(e,t){const n=u(e,"x","reverse");return f(n.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`),Ve(n,t)}const wh=m({reverse3d_:tv});function nv(e,t){const n=u(e,"x","reverse");return f(n.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`),Ve(n,t)}const xh=m({reverse4d_:nv});function yh(e,t,n=0){let r=[];if(typeof t=="number")f(e.shape[n]%t===0,()=>"Number of splits must evenly divide the axis."),r=new Array(t).fill(e.shape[n]/t);else{const o=t.reduce((a,s)=>(s===-1&&(a+=1),a),0);f(o<=1,()=>"There should be only one negative value in split array.");const i=t.indexOf(-1);if(i!==-1){const a=t.reduce((s,c)=>c>0?s+c:s);t[i]=e.shape[n]-a}f(e.shape[n]===t.reduce((a,s)=>a+s),()=>"The sum of sizes must match the size of the axis dimension."),r=t}return r}function rv(e,t,n=0){const r=u(e,"x","split"),o=(s,c)=>{const p=z(n,r.shape)[0],l=yh(r,t,p);return s.split(r,l,p)},i={x:r},a={numOrSizeSplits:t,axis:n};return g.runKernelFunc(o,i,null,qi,a)}const Yt=m({split_:rv});function ov(e,t){f(e.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${e.dtype}`);let n=e.shape[e.shape.length-1];const r=e.size/n;let o;if(t!=null&&t0),w=e.shape.map(L=>L);w[e.shape.length-1]=t,o=G(e,x,w),n=t}else if(t!=null&&t>n){const x=e.shape.map(w=>w);x[e.shape.length-1]=t-n,o=Z([e,Ce(x)],e.shape.length-1),n=t}else o=e;const i=W(o),a=y(Ye(o,i),[r,n]),s=Gn(a),c=Math.floor(n/2)+1,p=zt(s),l=nn(s),h=Yt(p,[c,n-c],p.shape.length-1),d=Yt(l,[c,n-c],l.shape.length-1),b=o.shape.slice();return b[o.shape.length-1]=c,y(Ye(h[0],d[0]),b)}const Jn=m({rfft_:ov});function iv(e){const t=u(e,"x","round"),n={x:t};return g.runKernelFunc(r=>r.round(t),n,null,Ei)}const Lh=m({round_:iv});function sv(e){const t=u(e,"x","rsqrt"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.rsqrt(t);return o([t]),i},n,null,Oi)}const _s=m({rsqrt_:sv});function av(e){const t=u(e,"x","selu"),n=(o,i)=>{const a=o.selu(t);return i([t]),a},r={x:t};return g.runKernelFunc(n,r,null,Di)}const vh=m({selu_:av});function cv(e,t,n,r,o,i=[1,1],a="NHWC"){const s=u(e,"x","separableConv2d"),c=u(t,"depthwiseFilter","separableConv2d"),p=u(n,"pointwiseFilter","separableConv2d");let l=s,h=!1;if(s.rank===3&&(h=!0,l=y(s,[1,s.shape[0],s.shape[1],s.shape[2]])),a==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");f(l.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${l.rank}.`),f(c.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${c.rank}.`),f(p.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${c.rank}.`),f(p.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${p.shape[0]}.`),f(p.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${p.shape[1]}.`);const d=c.shape[2],b=c.shape[3];f(p.shape[2]===d*b,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${d*b}, but got ${p.shape[2]}.`);const x=en(l,c,r,o,a,i),w=1,L=xe(x,p,w,"valid",a);return h?y(L,[L.shape[1],L.shape[2],L.shape[3]]):L}const Xn=m({separableConv2d_:cv});async function pv(e,t){const n=u(e,"x","setdiff1d"),r=u(t,"y","setdiff1d");f(n.dtype===r.dtype,()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${r.dtype}).`),f(n.rank===1,()=>`x should be 1D tensor, but got x (${n.shape}).`),f(r.rank===1,()=>`y should be 1D tensor, but got y (${r.shape}).`);const o=await n.data(),i=await r.data(),a=new Set(i);let s=0;for(let l=0;lr.sign(t),n,null,Wi)}const Ih=m({sign_:lv});function hv(e){const t=u(e,"x","sin"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.sin(t);return o([t]),i},n,null,Mi)}const Cs=m({sin_:hv});function uv(e){const t=u(e,"x","sinh"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.sinh(t);return o([t]),i},n,null,Ui)}const Es=m({sinh_:uv});function dv(e,t,n){const r=u(e,"x","slice1d");return f(r.rank===1,()=>`slice1d expects a rank-1 tensor, but got a rank-${r.rank} tensor`),G(r,[t],[n])}const Th=m({slice1d_:dv});function mv(e,t,n){const r=u(e,"x","slice2d");return f(r.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${r.rank} tensor`),G(r,t,n)}const Ah=m({slice2d_:mv});function fv(e,t,n){const r=u(e,"x","slice3d");return f(r.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${r.rank} tensor`),G(r,t,n)}const Os=m({slice3d_:fv});function gv(e,t,n){const r=u(e,"x","slice4d");return f(r.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${r.rank} tensor`),G(r,t,n)}const Nh=m({slice4d_:gv});function bv(e,t=-1){const n=u(e,"logits","softmax","float32");if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and dim was ${t}`);const r={logits:n},o={dim:t};return g.runKernelFunc((i,a)=>{const s=i.softmax(n,t);return a([s]),s},r,null,Hi,o)}const rn=m({softmax_:bv});function wv(e){const t=u(e,"x","sqrt"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.sqrt(t);return o([t]),i},n,null,ji)}const me=m({sqrt_:wv});function xv(e,t){let n=u(e,"a","squaredDifference"),r=u(t,"b","squaredDifference");[n,r]=V(n,r),q(n.shape,r.shape);const o=(s,c)=>{const p=s.squaredDifference(n,r);return c([n,r]),p},i={a:n,b:r},a={};return g.runKernelFunc(o,i,null,zi,a)}const Zn=m({squaredDifference_:xv});function yv(e,t){const n=u(e,"x","squeeze");return y(n,Cp(n.shape,t).newShape)}const Qn=m({squeeze_:yv});function Lv(e,t=0){const n=Zt(e,"tensors","stack");if(f(n.length>=1,()=>"Pass at least one tensor to tf.stack"),n.length===1)return et(n[0],t);const r=n[0].rank,o=n[0].shape,i=n[0].dtype;f(t<=r,()=>"Axis must be <= rank of the tensor"),n.forEach(s=>{P(o,s.shape,"All tensors passed to stack must have matching shapes"),f(i===s.dtype,()=>"All tensors passed to stack must have matching dtypes")});const a=n.map(s=>et(s,t));return Z(a,t)}const ke=m({stack_:Lv});function vv(e,t=0){const n=u(e,"x","step"),r={x:n},o={alpha:t};return g.runKernelFunc(i=>i.step(n,t),r,null,ts,o)}const Dt=m({step_:vv});function Sv(e,t,n,r,o=0,i=0,a=0,s=0,c=0){r==null&&(r=new Array(t.length));let p=u(e,"x","stridedSlice");const l=b=>{const x=us(a);if(x.length>1)throw new Error("Multiple ellipses in slice is not allowed.");if(a!==0&&s!==0)throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");if(a!==0&&c!==0)throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");const w=p.rank-t.length,L=us(s),S=p.shape.slice();if(L.forEach(D=>{t[D]=0,n[D]=1,S.splice(D,0,1)}),p=y(p,S),x.length&&w>0){const D=x[0],$=w+1;t=ml(o,D,$,t,p.shape),n=fl(i,D,$,n,p.shape),r=dl(r,D,$,p.shape)}else for(let D=0;D{n[D]=t[D]+1,r[D]=1});const N=ul(t,n,r),A=N.filter((D,$)=>I.indexOf($)===-1),E=r.every(D=>D===1);if(E)return y(G(p,t,N),A);const M=b.stridedSlice(p,t,n,r);return y(M,A)},h={x:p},d={begin:t,end:n,strides:r,beginMask:o,endMask:i,ellipsisMask:a,newAxisMask:s,shrinkAxisMask:c};return g.runKernelFunc(l,h,null,Ip,d)}const Rh=m({stridedSlice_:Sv});function Iv(e){const t=u(e,"x","tan"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.tan(t);return o([t]),i},n,null,Vi)}const _h=m({tan_:Iv});function mt(e,t,n){if(at(e),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");const r=We(e,n);if(r.length!==2&&r.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(r.length===1&&t==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return He(e,t,r,n)}function er(e,t,n){if(at(e),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");const r=We(e,n);if(r.length!==3&&r.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(r.length===1&&t==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return He(e,t,r,n)}function ft(e,t,n){if(at(e),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");const r=We(e,n);if(r.length!==4&&r.length!==1)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(r.length===1&&t==null)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return He(e,t,r,n)}function Ch(e,t,n){if(at(e),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");const r=We(e,n);if(r.length!==5&&r.length!==1)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(r.length===1&&t==null)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return He(e,t,r,n)}function Eh(e,t,n){if(at(e),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");const r=We(e,n);if(r.length!==6&&r.length!==1)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(r.length===1&&t==null)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return t=t||r,He(e,t,r,n)}function Tv(e,t=1,n=!0){const r=u(e,"x","topk");if(r.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");const o=r.shape[r.shape.length-1];if(t>o)throw new Error(`'k' passed to topk() must be <= the last dimension (${o}) but got ${t}`);const i={x:r},a={k:t,sorted:n},[s,c]=g.runKernelFunc(p=>p.topk(r,t,n),i,null,Tp,a);return{values:s,indices:c}}const Oh=m({topk_:Tv});function Av(e,t=0,n=1,r,o){if(r!=null&&r==="bool")throw new Error("Unsupported data type $ { dtype }");const i=new As(t,n,r,!0,o),a=Be(e,r);for(let s=0;s"numSegments must be of dtype int");const i={x:r,segmentIds:o},a={numSegments:n},s=(c,p)=>{const l=c.unsortedSegmentSum(r,o,n);return p([o]),l};return g.runKernelFunc(s,i,null,Qi,a)}const ks=m({unsortedSegmentSum_:Nv});function Rv(e,t=0){const n=u(e,"x","unstack");f(t>=-n.shape.length&&t`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`),t<0&&(t+=n.shape.length);const r={value:n},o={axis:t},i=a=>a.unstack(n,t);return g.runKernelFunc(i,r,null,Zi,o)}const Ie=m({unstack_:Rv});function Dh(e,t=!0,n,r){return g.makeVariable(e,t,n,r)}function Wa(e,t){const n=[];for(let i=0;i0,()=>"mask cannot be scalar"),P(s.slice(i,i+a),o.shape,"mask's shape must match the first K dimensions of tensor's shape,");let c=1;for(let w=i;w"Shape mismatch in v and x");const c=_(1),p=O(c,s);let l=v(O(a,i),p);if(o){f(r!=null,()=>"When using zeroDebias: true, step is required.");const h=u(r,"step","movingAverage");l=F(l,O(c,Je(s,h)))}return R(i,l)}const um=m({movingAverage_:Yv});const dm={};Re(dm,{calculateShapes:()=>mm,validateInput:()=>Ba,validateUpdateShape:()=>Fh});function Fh(e,t,n){const r=t.rank>1?t.shape[t.rank-1]:1,o=t.rank>1?t.rank-1:1,i=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${n.shape}, indices.shape: ${t.shape}, shape: ${e}, sliceDim: ${r}, and batchDim: ${o}.`;if(n.rank1?t.shape[r-1]:1,i=n.length;let a=1;for(let h=o;hc.scatterND(r,o,n),a={indices:r,updates:o},s={shape:n};return g.runKernelFunc(i,a,null,Lp,s)}const fm=m({scatterND_:Vv});function gm(e,t,n,r){if(e.dtype!=="int32")throw new Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was ${e.dtype}.`);if(e.rank>2)throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${e.shape}.`);const o=e.rank>0?e.shape[0]:1,i=e.rank>1?e.shape[1]:1;if(n.length!==i)throw new Error(`outputShape has incorrect number of elements:, ${n.length}, should be: ${i}.`);const a=t.size;if(!(t.rank===0||t.rank===1&&a===o))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${o}]`);if(t.dtype!==r.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}function Kv(e,t,n,r=0){const o=u(e,"sparseIndices","sparseToDense","int32"),i=u(t,"sparseValues","sparseToDense"),a=u(r,"defaultValue","sparseToDense",i.dtype);gm(o,i,n,a);const s={sparseIndices:o,sparseValues:i,defaultValue:a},c={outputShape:n};return g.runKernelFunc(p=>p.sparseToDense(o,i,n,a),s,null,Sp,c)}const bm=m({sparseToDense_:Kv});function Jv(e,t){const n=u(t,"indices","gatherND","int32"),r=u(e,"x","gatherND"),o=a=>a.gatherND(r,n),i={params:r,indices:n};return g.runKernelFunc(o,i,null,Zc)}const wm=m({gatherND_:Jv});function xm(e,t){if(t==null)return e.shape.slice();if(Te(e.shape,t))return t;if(e.shape.length===t.length){const n=[];for(let r=0;r`x has to be a floating point tensor since it's going to be scaled, but got a ${o.dtype} tensor instead.`),f(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),t===0)return e instanceof ee?o.clone():o;const i=xm(o,n),a=1-t,s=F(Pn(R(Ns(i,0,1,"float32",r),a)),a);return v(o,s)}const ym=m({dropout_:Xv});function $a(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function qr(e,t,n){const r=1-e%2,o=new Float32Array(e);for(let i=0;i1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${r.rank}`),f(r.rank-1===o.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${r.rank} and targets rank ${o.rank}`),P(r.shape.slice(0,r.shape.length-1),o.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");const i=r.shape[r.shape.length-1];f(n>0&&n<=i,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${i}), but got ${n}`);const a=await r.data(),s=await o.data(),[c,p]=[a.length/i,i],l=Er("bool",c);for(let h=0;hL.value-w.value),l[h]=0;for(let w=0;w`Error in conv2dDerFilter: input must be rank 4, but got shape ${s.shape}.`),f(c.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${c.shape}.`),f(n.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`);const p=i==="NHWC"?s.shape[3]:s.shape[1],l=i==="NHWC"?c.shape[3]:c.shape[1];f(p===n[2],()=>`Error in conv2dDerFilter: depth of input ${p}) must match input depth in filter (${n[2]}.`),f(l===n[3],()=>`Error in conv2dDerFilter: depth of dy (${l}) must match output depth for filter (${n[3]}).`),a!=null&&f(X(o),()=>`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`);const h=x=>{const w=1,L=yn(i),S=je(s.shape,n,r,w,o,a,!1,L);return x.conv2dDerFilter(s,c,S)},d={x:s,dy:c},b={strides:r,pad:o,dataFormat:i,dimRoundingMode:a};return g.runKernelFunc(h,d,null,Uc,b)}const Hr=m({conv2DBackpropFilter_:Qv});function tr(e,t,n){if(n==null||n==="linear")return e;if(n==="relu")return v(e,Dt(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function nr(e,t){let n=t;const r=ae(e.shape,t.shape);return r.length>0&&(n=U(n,r)),y(n,e.shape)}function rr(e,t,n){if(t==="linear")return e;if(t==="relu")return ie(e);if(t==="elu")return bs(e);if(t==="relu6")return Rs(e);if(t==="prelu")return Ts(e,n);throw new Error(`Unknown fused activation ${t}.`)}const or=(e,t)=>{const n=e>0;return!n||t==="linear"};function eS({x:e,filter:t,strides:n,pad:r,dataFormat:o="NHWC",dilations:i=[1,1],dimRoundingMode:a,bias:s,activation:c="linear",preluActivationWeights:p}){if(c=c||"linear",or(g.state.gradientDepth,c)===!1){let E=xe(e,t,n,r,o,i,a);return s!=null&&(E=R(E,s)),rr(E,c,p)}const l=u(e,"x","conv2d"),h=u(t,"filter","conv2d");let d=l,b=!1;l.rank===3&&(b=!0,d=y(l,[1,l.shape[0],l.shape[1],l.shape[2]])),f(d.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${d.rank}.`),f(h.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${h.rank}.`),a!=null&&f(X(r),()=>`Error in fused conv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${r}.`),f(d.shape[3]===h.shape[2],()=>`Error in conv2d: depth of input (${d.shape[3]}) must match input depth for filter ${h.shape[2]}.`),f(le(n,i),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'`),f(o==="NHWC",()=>`Error in conv2d: got dataFormat of ${o} but only NHWC is currently supported.`);const x=je(d.shape,h.shape,n,i,r,a);let w;s!=null&&(w=u(s,"bias","fused conv2d"),[w]=V(w,l),q(x.outShape,w.shape));let L;p!=null&&(L=u(p,"prelu weights","fused conv2d"));const S=(E,M)=>{const[D,$,B,j]=M,te=tr(E,B,c);f(ct(i),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${i}'`);const re=$r($.shape,te,D,n,r),he=Hr($,te,D.shape,n,r),ye=[re,he];if(j!=null){const Me=nr(j,te);ye.push(Me)}return ye},I=E=>{const M=E.fusedConv2d({input:d,filter:h,convInfo:x,bias:w,activation:c,preluActivationWeights:L});return M},N={x:d,filter:h,bias:w,preluActivationWeights:L},A={strides:n,pad:r,dataFormat:o,dilations:i,dimRoundingMode:a,activation:c};if(s==null){const E=Ke((M,D,$)=>{let B=g.runKernelFunc(I,N,null,Ia,A);return $([D,M,B]),b&&(B=y(B,[B.shape[1],B.shape[2],B.shape[3]])),{value:B,gradFunc:S}});return E(d,h)}else{const E=Ke((M,D,$,B)=>{let j=g.runKernelFunc(I,N,null,Ia,A);return B([D,M,j,$]),b&&(j=y(j,[j.shape[1],j.shape[2],j.shape[3]])),{value:j,gradFunc:S}});return E(d,h,w)}}const tS=m({fusedConv2d_:eS});function nS(e,t,n,r){let o=e;e.rank===3&&(o=y(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let i=t;i.rank===3&&(i=y(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const a=c=>c.depthwiseConv2DDerFilter(o,i,r),s={x:o,dy:i};return g.runKernelFunc(a,s,null,Gc)}const ja=m({depthwiseConv2dNativeBackpropFilter_:nS});function rS(e,t,n,r){let o=t,i=!1;t.rank===3&&(i=!0,o=y(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const a=p=>p.depthwiseConv2DDerInput(o,n,r),s={dy:o},c=g.runKernelFunc(a,s,null,Pc);return i?y(c,[c.shape[1],c.shape[2],c.shape[3]]):c}const Ga=m({depthwiseConv2dNativeBackpropInput_:rS});function oS({x:e,filter:t,strides:n,pad:r,dataFormat:o="NHWC",dilations:i=[1,1],dimRoundingMode:a,bias:s,activation:c="linear",preluActivationWeights:p}){if(or(g.state.gradientDepth,c)===!1){let E=en(e,t,n,r,o,i,a);return s!=null&&(E=R(E,s)),rr(E,c,p)}const l=u(e,"x","depthwiseConv2d"),h=u(t,"filter","depthwiseConv2d");let d=l,b=!1;l.rank===3&&(b=!0,d=y(l,[1,l.shape[0],l.shape[1],l.shape[2]])),f(d.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${d.rank}.`),f(h.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${h.rank}.`),f(d.shape[3]===h.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${d.shape[3]}) must match the inChannels dimension in filter ${h.shape[2]}.`),i==null&&(i=[1,1]),f(le(n,i),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'`),a!=null&&f(X(r),()=>`Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode ${a} but got pad ${r}.`);const x=je(d.shape,h.shape,n,i,r,a,!0);let w;s!=null&&(w=u(s,"bias","fused conv2d"),[w]=V(w,l),q(x.outShape,w.shape));let L;p!=null&&(L=u(p,"prelu weights","fused depthwiseConv2d"));const S=(E,M)=>{f(ct(i),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${i}'`);const[D,$,B,j]=M,te=tr(E,B,c),re=Ga($.shape,te,D,x),he=ja($,te,D.shape,x);if(j!=null){const ye=nr(w,te);return[re,he,ye]}return[re,he]},I=E=>{const M=E.fusedDepthwiseConv2D({input:d,filter:h,convInfo:x,bias:w,activation:c,preluActivationWeights:L});return M},N={x:d,filter:h,bias:w,preluActivationWeights:L},A={strides:n,pad:r,dataFormat:o,dilations:i,dimRoundingMode:a,activation:c};if(s==null){const E=Ke((M,D,$)=>{let B=g.runKernelFunc(I,N,null,Ta,A);return $([D,M,B]),b&&(B=y(B,[B.shape[1],B.shape[2],B.shape[3]])),{value:B,gradFunc:S}});return E(d,h)}else{const E=Ke((M,D,$,B)=>{let j=g.runKernelFunc(I,N,null,Ta,A);return B([D,M,j,$]),b&&(j=y(j,[j.shape[1],j.shape[2],j.shape[3]])),{value:j,gradFunc:S}});return E(d,h,w)}}const iS=m({fusedDepthwiseConv2d_:oS});function sS({a:e,b:t,transposeA:n=!1,transposeB:r=!1,bias:o,activation:i="linear",preluActivationWeights:a}){if(or(g.state.gradientDepth,i)===!1){let j=Y(e,t,n,r);return o!=null&&(j=R(j,o)),rr(j,i,a)}let s=u(e,"a","fused matMul"),c=u(t,"b","fused matMul");[s,c]=V(s,c);const p=n?s.shape[s.rank-2]:s.shape[s.rank-1],l=r?c.shape[c.rank-1]:c.shape[c.rank-2],h=n?s.shape[s.rank-1]:s.shape[s.rank-2],d=r?c.shape[c.rank-2]:c.shape[c.rank-1],b=s.shape.slice(0,-2),x=c.shape.slice(0,-2),w=Q(b),L=Q(x);f(s.rank>=2&&c.rank>=2&&s.rank===c.rank,()=>`Error in fused matMul: inputs must have the same rank of at least 2, got ranks ${s.rank} and ${c.rank}.`),f(Te(b,x),()=>`Error in fused matMul: outer dimensions (${b}) and (${x}) of Tensors with shapes ${s.shape} and ${c.shape} must match.`),f(p===l,()=>`Error in fused matMul: inner shapes (${p}) and (${l}) of Tensors with shapes ${s.shape} and ${c.shape} and transposeA=${n} and transposeB=${r} must match.`);const S=s.shape.slice(0,-2).concat([h,d]),I=n?y(s,[w,p,h]):y(s,[w,h,p]),N=r?y(c,[L,d,l]):y(c,[L,l,d]);let A;o!=null&&(A=u(o,"bias","fused matMul"),[A]=V(A,s),q(S,A.shape));let E;a!=null&&(E=u(a,"prelu weights","fused matMul"));const M=(j,te)=>{const[re,he,ye,Me]=te,Tt=tr(y(j,ye.shape),ye,i);let ln,wr;if(!n&&!r?(ln=Y(Tt,he,!1,!0),wr=Y(re,Tt,!0,!1)):!n&&r?(ln=Y(Tt,he,!1,!1),wr=Y(Tt,re,!0,!1)):n&&!r?(ln=Y(he,Tt,!1,!0),wr=Y(re,Tt,!1,!1)):(ln=Y(he,Tt,!0,!0),wr=Y(Tt,re,!0,!0)),o!=null){const Yb=nr(Me,Tt);return[ln,wr,Yb]}else return[ln,wr]},D=j=>{const te=j.fusedBatchMatMul({a:I,b:N,transposeA:n,transposeB:r,bias:A,activation:i,preluActivationWeights:E});return te},$={a:I,b:N,bias:A,preluActivationWeights:E},B={transposeA:n,transposeB:r,activation:i};if(o==null){const j=Ke((te,re,he)=>{const ye=g.runKernelFunc(D,$,null,Sa,B);return he([te,re,ye]),{value:y(ye,S),gradFunc:M}});return j(I,N)}else{const j=Ke((te,re,he,ye)=>{const Me=g.runKernelFunc(D,$,null,Sa,B);return ye([te,re,Me,he]),{value:y(Me,S),gradFunc:M}});return j(I,N,A)}}const aS=m({fusedMatMul_:sS});const Mh={};Re(Mh,{conv2d:()=>tS,depthwiseConv2d:()=>iS,matMul:()=>aS});function cS(e){return qr(e,.54,.46)}const vm=m({hammingWindow_:cS});function pS(e){return qr(e,.5,.5)}const Pa=m({hannWindow_:pS});function lS(e,t,n,r=!1,o=0){let i=0;const a=[];for(;i+t<=e.size;)a.push(G(e,i,t)),i+=n;if(r)for(;i`Error in cropAndResize: image must be rank 4,but got rank ${a.rank}.`),f(s.rank===2&&s.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${p},4] but had shape ${s.shape}.`),f(c.rank===1&&c.shape[0]===p,()=>`Error in cropAndResize: boxInd must be have size [${p}] but had shape ${s.shape}.`),f(r.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${r.length}.`),f(r[0]>=1&&r[1]>=1,()=>`cropSize must be atleast [1,1], but was ${r}`),f(o==="bilinear"||o==="nearest",()=>`method must be bilinear or nearest, but was ${o}`);const l=x=>x.cropAndResize(a,s,c,r,o,i),h={image:a,boxes:s,boxInd:c},d={method:o,extrapolationValue:i,cropSize:r},b=g.runKernelFunc(l,h,null,$c,d);return b}const Im=m({cropAndResize_:uS});function dS(e){const t=u(e,"image","flipLeftRight","float32");f(t.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);const n={image:t},r=g.runKernel(Xc,n,{});return r}const Tm=m({flipLeftRight_:dS});function mS(e,t,n=0,r=.5){const o=u(e,"image","rotateWithOffset","float32");f(o.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${o.rank}.`);const i={image:o},a={radians:t,fillValue:n,center:r},s=g.runKernel(Ap,i,a);return s}const Am=m({rotateWithOffset_:mS});function St(e,t,n,r,o,i){r==null&&(r=.5),o==null&&(o=Number.NEGATIVE_INFINITY),i==null&&(i=0);const a=e.shape[0];return n=Math.min(n,a),f(0<=r&&r<=1,()=>`iouThreshold must be in [0, 1], but was '${r}'`),f(e.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`),f(e.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`),f(t.rank===1,()=>"scores must be a 1D tensor"),f(t.shape[0]===a,()=>`scores has incompatible shape with boxes. Expected ${a}, but was ${t.shape[0]}`),f(0<=i&&i<=1,()=>`softNmsSigma must be in [0, 1], but was '${i}'`),{maxOutputSize:n,iouThreshold:r,scoreThreshold:o,softNmsSigma:i}}function fS(e,t,n,r=.5,o=Number.NEGATIVE_INFINITY){const i=u(e,"boxes","nonMaxSuppression"),a=u(t,"scores","nonMaxSuppression"),s=St(i,a,n,r,o);n=s.maxOutputSize,r=s.iouThreshold,o=s.scoreThreshold;const c={maxOutputSize:n,iouThreshold:r,scoreThreshold:o};return g.runKernelFunc(p=>p.nonMaxSuppression(i,a,n,r,o),{boxes:i,scores:a},null,dp,c)}const Nm=m({nonMaxSuppression_:fS});function Rm(e,t,n){const r=gS(e,t,n),o=r<0?-(r+1):r;e.splice(o,0,t)}function gS(e,t,n){return wS(e,t,n||bS)}function bS(e,t){return e>t?1:e>>1);const s=n(t,e[i]);s>0?r=i+1:(o=i,a=!s)}return a?r:-r-1}function Ha(e,t,n,r,o){return Uh(e,t,n,r,o,0).selectedIndices}function za(e,t,n,r,o,i){return Uh(e,t,n,r,o,0,!1,i,!0)}function Ya(e,t,n,r,o,i){return Uh(e,t,n,r,o,i,!0)}function Uh(e,t,n,r,o,i,a=!1,s=!1,c=!1){const p=[];for(let L=0;Lo&&p.push({score:t[L],boxIndex:L,suppressBeginIndex:0});p.sort(_m);const l=i>0?-.5/i:0,h=[],d=[];for(;h.length0;){const L=p.pop(),{score:S,boxIndex:I,suppressBeginIndex:N}=L;if(S=N;--E){const M=xS(e,I,h[E]);if(M>=r){A=!0;break}if(L.score=L.score*yS(r,l,M),L.score<=o)break}L.suppressBeginIndex=h.length,A||(L.score===S?(h.push(I),d.push(L.score)):L.score>o&&Rm(p,L,_m))}const b=h.length,x=n-b;s&&x>0&&(h.push(...new Array(x).fill(0)),d.push(...new Array(x).fill(0)));const w={selectedIndices:ce(h,"int32")};return a&&(w.selectedScores=ce(d,"float32")),c&&(w.validOutputs=_(b,"int32")),w}function xS(e,t,n){const r=e.subarray(t*4,t*4+4),o=e.subarray(n*4,n*4+4),i=Math.min(r[0],r[2]),a=Math.min(r[1],r[3]),s=Math.max(r[0],r[2]),c=Math.max(r[1],r[3]),p=Math.min(o[0],o[2]),l=Math.min(o[1],o[3]),h=Math.max(o[0],o[2]),d=Math.max(o[1],o[3]),b=(s-i)*(c-a),x=(h-p)*(d-l);if(b<=0||x<=0)return 0;const w=Math.max(i,p),L=Math.max(a,l),S=Math.min(s,h),I=Math.min(c,d),N=Math.max(S-w,0)*Math.max(I-L,0);return N/(b+x-N)}function yS(e,t,n){const r=Math.exp(t*n*n);return n<=e?r:0}function _m(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function LS(e,t,n,r=.5,o=Number.NEGATIVE_INFINITY){const i=u(e,"boxes","nonMaxSuppressionAsync"),a=u(t,"scores","nonMaxSuppressionAsync"),s=St(i,a,n,r,o);n=s.maxOutputSize,r=s.iouThreshold,o=s.scoreThreshold;const c=await Promise.all([i.data(),a.data()]),p=c[0],l=c[1],h=Ha(p,l,n,r,o);return i!==e&&i.dispose(),a!==t&&a.dispose(),h}const Cm=LS;function vS(e,t,n,r=.5,o=Number.NEGATIVE_INFINITY,i=0){const a=u(e,"boxes","nonMaxSuppression"),s=u(t,"scores","nonMaxSuppression"),c=St(a,s,n,r,o,i);n=c.maxOutputSize,r=c.iouThreshold,o=c.scoreThreshold,i=c.softNmsSigma;const p={boxes:a,scores:s},l={maxOutputSize:n,iouThreshold:r,scoreThreshold:o,softNmsSigma:i},h=g.runKernel(fp,p,l);return{selectedIndices:h[0],selectedScores:h[1]}}const Em=m({nonMaxSuppressionWithScore_:vS});async function SS(e,t,n,r=.5,o=Number.NEGATIVE_INFINITY,i=0){const a=u(e,"boxes","nonMaxSuppressionAsync"),s=u(t,"scores","nonMaxSuppressionAsync"),c=St(a,s,n,r,o,i);n=c.maxOutputSize,r=c.iouThreshold,o=c.scoreThreshold,i=c.softNmsSigma;const p=await Promise.all([a.data(),s.data()]),l=p[0],h=p[1],d=Ya(l,h,n,r,o,i);return a!==e&&a.dispose(),s!==t&&s.dispose(),d}const Om=SS;function IS(e,t,n,r=.5,o=Number.NEGATIVE_INFINITY,i=!1){const a=u(e,"boxes","nonMaxSuppression"),s=u(t,"scores","nonMaxSuppression"),c=St(a,s,n,r,o,null),p=c.maxOutputSize,l=c.iouThreshold,h=c.scoreThreshold,d={boxes:a,scores:s},b={maxOutputSize:p,iouThreshold:l,scoreThreshold:h,padToMaxOutputSize:i},x=g.runKernel(mp,d,b);return{selectedIndices:x[0],validOutputs:x[1]}}const km=m({nonMaxSuppressionPadded_:IS});async function TS(e,t,n,r=.5,o=Number.NEGATIVE_INFINITY,i=!1){const a=u(e,"boxes","nonMaxSuppressionAsync"),s=u(t,"scores","nonMaxSuppressionAsync"),c=St(a,s,n,r,o,null),p=c.maxOutputSize,l=c.iouThreshold,h=c.scoreThreshold,[d,b]=await Promise.all([a.data(),s.data()]),x=za(d,b,p,l,h,i);return a!==e&&a.dispose(),s!==t&&s.dispose(),x}const Dm=TS;function AS(e,t,n=!1){const r=u(e,"images","resizeBilinear");f(r.rank===3||r.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${r.rank}.`),f(t.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`);let o=r,i=!1;r.rank===3&&(i=!0,o=y(r,[1,r.shape[0],r.shape[1],r.shape[2]]));const[a,s]=t,c=(d,b)=>(b([o]),d.resizeBilinear(o,a,s,n)),p={images:o},l={alignCorners:n,size:t},h=g.runKernelFunc(c,p,null,Ri,l);return i?y(h,[h.shape[1],h.shape[2],h.shape[3]]):h}const Fm=m({resizeBilinear_:AS});function NS(e,t,n=!1){const r=u(e,"images","resizeNearestNeighbor");f(r.rank===3||r.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${r.rank}.`),f(t.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),f(r.dtype==="float32"||r.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype");let o=r,i=!1;r.rank===3&&(i=!0,o=y(r,[1,r.shape[0],r.shape[1],r.shape[2]]));const[a,s]=t,c={images:o},p={alignCorners:n,size:t},l=(d,b)=>(b([o]),d.resizeNearestNeighbor(o,a,s,n)),h=g.runKernelFunc(l,c,null,Ni,p);return i?y(h,[h.shape[1],h.shape[2],h.shape[3]]):h}const Mm=m({resizeNearestNeighbor_:NS});function RS(e,t,n){f(t%1===0,()=>`bandPart(): numLower must be an integer, got ${t}.`),f(n%1===0,()=>`bandPart(): numUpper must be an integer, got ${n}.`);const r=u(e,"a","bandPart");f(r.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${r.rank}.`);const o=r.shape,[i,a]=r.shape.slice(-2);if(!(t<=i))throw new Error(`bandPart(): numLower (${t}) must not be greater than the number of rows (${i}).`);if(!(n<=a))throw new Error(`bandPart(): numUpper (${n}) must not be greater than the number of columns (${a}).`);t<0&&(t=i),n<0&&(n=a);const s=y(Gr(0,i,1,"int32"),[-1,1]),c=Gr(0,a,1,"int32"),p=O(s,c),l=Lt(ut(p,_(+t,"int32")),ht(p,_(-n,"int32"))),h=Ce([i,a],r.dtype);return y(ke(Ie(y(r,[-1,i,a])).map(d=>Oe(l,d,h))),o)}const Um=m({bandPart_:RS});function _S(e){let t;if(Array.isArray(e)){t=!1,f(e!=null&&e.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");const o=e[0].shape[0];for(let i=1;i`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[i].shape[0]} vs. ${o})`)}else t=!0,e=Yt(e,e.shape[0],0).map(o=>Qn(o,[0]));f(e.length<=e[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`);const n=[],r=e;for(let o=0;o{let i=r[o];if(o>0)for(let a=0;a=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`),e.rank===2)return Bm(e,t);{const n=e.shape.slice(0,e.shape.length-2).reduce((c,p)=>c*p),r=Ie(y(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),o=[],i=[];r.forEach(c=>{const[p,l]=Bm(c,t);o.push(p),i.push(l)});const a=y(ke(o,0),e.shape),s=y(ke(i,0),e.shape);return[a,s]}}function Bm(e,t=!1){return g.tidy(()=>{f(e.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`);const n=e.shape[0],r=e.shape[1];let o=ws(n),i=Et(e);const a=mt([[1]],[1,1]);let s=Et(a);const c=n>=r?r:n;for(let p=0;p{const b=G(i,[p,p],[n-p,1]),x=Pr(b),w=G(i,[p,p],[1,1]),L=Oe(tt(w,0),mt([[-1]]),mt([[1]])),S=O(w,v(L,x)),I=F(b,S);I.shape[0]===1?s=Et(a):s=Z([a,G(I,[1,0],[I.shape[0]-1,I.shape[1]])],0);const N=ne(F(Y(L,S),x)),A=G(i,[p,0],[n-p,r]),E=v(N,s),M=K(s);if(p===0)i=O(A,Y(E,Y(M,A)));else{const B=O(A,Y(E,Y(M,A)));i=Z([G(i,[0,0],[p,r]),B],0)}const D=K(E),$=G(o,[0,p],[n,o.shape[1]-p]);if(p===0)o=O($,Y(Y($,s),D));else{const B=O($,Y(Y($,s),D));o=Z([G(o,[0,0],[n,p]),B],1)}return[s,i,o]}),ve([l,h,d])}return!t&&n>r&&(o=G(o,[0,0],[n,r]),i=G(i,[0,0],[r,r])),[o,i]})}const $m=m({qr_:CS});var be;(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"})(be||(be={}));function ES(e,t,n=be.SUM_BY_NONZERO_WEIGHTS){const r=u(e,"losses","computeWeightedLoss");let o=null;t!=null&&(o=u(t,"weights","computeWeightedLoss"));const i=o==null?r:v(r,o);if(n===be.NONE)return i;if(n===be.SUM)return U(i);if(n===be.MEAN){if(o==null)return Sn(i);{const a=r.size/o.size,s=F(U(i),U(o));return a>1?F(s,_(a)):s}}if(n===be.SUM_BY_NONZERO_WEIGHTS){if(o==null)return F(U(i),_(r.size));{const a=v(o,vt(r.shape)),s=C(U(Vn(a,_(0))),"float32");return F(U(i),s)}}throw Error(`Unknown reduction: ${n}`)}const $e=m({computeWeightedLoss_:ES});function OS(e,t,n,r=be.SUM_BY_NONZERO_WEIGHTS){const o=u(e,"labels","absoluteDifference"),i=u(t,"predictions","absoluteDifference");let a=null;n!=null&&(a=u(n,"weights","absoluteDifference")),P(o.shape,i.shape,"Error in absoluteDifference: ");const s=Ee(O(o,i));return $e(s,a,r)}const jm=m({absoluteDifference_:OS});function kS(e,t,n,r,o=be.SUM_BY_NONZERO_WEIGHTS){const i=u(e,"labels","cosineDistance"),a=u(t,"predictions","cosineDistance");let s=null;r!=null&&(s=u(r,"weights","cosineDistance")),P(i.shape,a.shape,"Error in cosineDistance: ");const c=_(1),p=O(c,U(v(i,a),n,!0));return $e(p,s,o)}const Gm=m({cosineDistance_:kS});function DS(e,t,n,r=be.SUM_BY_NONZERO_WEIGHTS){let o=u(e,"labels","hingeLoss");const i=u(t,"predictions","hingeLoss");let a=null;n!=null&&(a=u(n,"weights","hingeLoss")),P(o.shape,i.shape,"Error in hingeLoss: ");const s=_(1);o=O(v(_(2),o),s);const c=ie(O(s,v(o,i)));return $e(c,a,r)}const Pm=m({hingeLoss_:DS});function FS(e,t,n,r=1,o=be.SUM_BY_NONZERO_WEIGHTS){const i=u(e,"labels","huberLoss"),a=u(t,"predictions","huberLoss");let s=null;n!=null&&(s=u(n,"weights","huberLoss")),P(i.shape,a.shape,"Error in huberLoss: ");const c=_(r),p=Ee(O(a,i)),l=Yn(p,c),h=O(p,l),d=R(v(_(.5),H(l)),v(c,h));return $e(d,s,o)}const qm=m({huberLoss_:FS});function MS(e,t,n,r=1e-7,o=be.SUM_BY_NONZERO_WEIGHTS){const i=u(e,"labels","logLoss"),a=u(t,"predictions","logLoss");let s=null;n!=null&&(s=u(n,"weights","logLoss")),P(i.shape,a.shape,"Error in logLoss: ");const c=_(1),p=_(r),l=ne(v(i,yt(R(a,p)))),h=v(O(c,i),yt(R(O(c,a),p))),d=O(l,h);return $e(d,s,o)}const Hm=m({logLoss_:MS});function US(e,t,n,r=be.SUM_BY_NONZERO_WEIGHTS){const o=u(e,"labels","meanSquaredError"),i=u(t,"predictions","meanSquaredError");let a=null;n!=null&&(a=u(n,"weights","meanSquaredError")),P(o.shape,i.shape,"Error in meanSquaredError: ");const s=Zn(o,i);return $e(s,a,r)}const zm=m({meanSquaredError_:US});function WS(e,t){const n=u(e,"labels","sigmoidCrossEntropyWithLogits"),r=u(t,"logits","sigmoidCrossEntropyWithLogits");P(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");const o=ie(r),i=v(r,n),a=ys(Se(ne(Ee(r))));return R(O(o,i),a)}function BS(e,t,n,r=0,o=be.SUM_BY_NONZERO_WEIGHTS){let i=u(e,"multiClassLabels","sigmoidCrossEntropy");const a=u(t,"logits","sigmoidCrossEntropy");let s=null;if(n!=null&&(s=u(n,"weights","sigmoidCrossEntropy")),P(i.shape,a.shape,"Error in sigmoidCrossEntropy: "),r>0){const p=_(r),l=_(1),h=_(.5);i=R(v(i,O(l,p)),v(h,p))}const c=WS(i,a);return $e(c,s,o)}const Ym=m({sigmoidCrossEntropy_:BS});function $S(e,t,n=-1){if(n===-1&&(n=t.rank-1),n!==t.rank-1)throw Error(`Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank ${t.rank} and dim was ${n}`);const r=Ke((o,i,a)=>{const s=!0,c=vs(i,[n],s),p=O(C(i,"float32"),c);a([o,p]);const l=ne(v(p,o)),h=U(l,[n]),d=(b,x)=>{const[w,L]=x,S=we(b.shape,[n]);return[v(y(b,S),O(C(w,"float32"),Se(L))),v(y(b,S),O(Se(L),C(w,"float32")))]};return{value:h,gradFunc:d}});return r(e,t)}function jS(e,t,n,r=0,o=be.SUM_BY_NONZERO_WEIGHTS){let i=u(e,"onehotLabels","softmaxCrossEntropy");const a=u(t,"logits","softmaxCrossEntropy");let s=null;if(n!=null&&(s=u(n,"weights","softmaxCrossEntropy")),P(i.shape,a.shape,"Error in softmaxCrossEntropy: "),r>0){const p=_(r),l=_(1),h=_(i.shape[1]);i=R(v(i,O(l,p)),F(p,h))}const c=$S(i,a);return $e(c,s,o)}const Vm=m({softmaxCrossEntropy_:jS});const Wh={};Re(Wh,{abs:()=>Ee,acos:()=>Hp,acosh:()=>zp,add:()=>R,addN:()=>Yp,addStrict:()=>nm,all:()=>Jp,any:()=>Xp,argMax:()=>Zp,argMin:()=>Qp,asin:()=>el,asinh:()=>tl,atan:()=>nl,atan2:()=>rl,atanh:()=>ol,avgPool:()=>pt,avgPool3d:()=>cl,basicLSTMCell:()=>xl,batchNorm:()=>Ct,batchNorm2d:()=>yl,batchNorm3d:()=>Ll,batchNorm4d:()=>vl,batchToSpaceND:()=>Bn,booleanMaskAsync:()=>Kd,broadcastTo:()=>Br,buffer:()=>Be,cast:()=>C,ceil:()=>Sl,clipByValue:()=>$n,clone:()=>Et,complex:()=>Ye,concat:()=>Z,concat1d:()=>Il,concat2d:()=>Tl,concat3d:()=>Al,concat4d:()=>Nl,conv1d:()=>Rl,conv2d:()=>xe,conv2dTranspose:()=>_l,conv3d:()=>Cl,conv3dTranspose:()=>El,cos:()=>jn,cosh:()=>ms,cosineWindow:()=>qr,cumsum:()=>fs,depthToSpace:()=>Ol,depthwiseConv2d:()=>en,diag:()=>kl,dilation2d:()=>Dl,div:()=>F,divNoNan:()=>Fl,divStrict:()=>rm,dot:()=>Ml,dropout:()=>ym,elu:()=>bs,enclosingPowerOfTwo:()=>$a,equal:()=>tn,equalStrict:()=>Jd,erf:()=>Ul,exp:()=>Se,expandDims:()=>et,expm1:()=>Wl,eye:()=>ws,fft:()=>Gn,fill:()=>Ge,floor:()=>Pn,floorDiv:()=>gs,fused:()=>Mh,gather:()=>qn,gatherND:()=>wm,greater:()=>tt,greaterEqual:()=>ht,greaterEqualStrict:()=>Xd,greaterStrict:()=>Zd,ifft:()=>vn,imag:()=>nn,image:()=>Va,inTopKAsync:()=>Lm,irfft:()=>xs,isFinite:()=>$l,isInf:()=>jl,isNaN:()=>Gl,leakyRelu:()=>Pl,less:()=>Hn,lessEqual:()=>ut,lessEqualStrict:()=>Qd,lessStrict:()=>em,linalg:()=>Xm,linspace:()=>ql,localResponseNormalization:()=>Hl,log:()=>yt,log1p:()=>ys,logSigmoid:()=>Yl,logSoftmax:()=>Vl,logSumExp:()=>vs,logicalAnd:()=>Lt,logicalNot:()=>zn,logicalOr:()=>Ss,logicalXor:()=>Kl,losses:()=>Zm,matMul:()=>Y,max:()=>dt,maxPool:()=>Ae,maxPool3d:()=>Jl,maxPoolWithArgmax:()=>Xl,maximum:()=>kt,maximumStrict:()=>om,mean:()=>Sn,min:()=>In,minimum:()=>Yn,minimumStrict:()=>im,mod:()=>Is,modStrict:()=>sm,moments:()=>Zl,movingAverage:()=>um,mul:()=>v,mulStrict:()=>am,multiRNNCell:()=>Ql,multinomial:()=>eh,neg:()=>ne,norm:()=>Pr,notEqual:()=>Vn,notEqualStrict:()=>tm,oneHot:()=>jr,ones:()=>vt,onesLike:()=>Ma,op:()=>m,outerProduct:()=>th,pad:()=>Pe,pad1d:()=>nh,pad2d:()=>rh,pad3d:()=>oh,pad4d:()=>ih,pool:()=>sh,pow:()=>Je,powStrict:()=>cm,prelu:()=>Ts,print:()=>ah,prod:()=>ch,rand:()=>ph,randomGamma:()=>dh,randomNormal:()=>mh,randomUniform:()=>Ns,range:()=>Gr,real:()=>zt,reciprocal:()=>fh,relu:()=>ie,relu6:()=>Rs,reshape:()=>y,reverse:()=>Ve,reverse1d:()=>gh,reverse2d:()=>bh,reverse3d:()=>wh,reverse4d:()=>xh,rfft:()=>Jn,round:()=>Lh,rsqrt:()=>_s,scalar:()=>_,scatterND:()=>fm,selu:()=>vh,separableConv2d:()=>Xn,setdiff1dAsync:()=>Sh,sigmoid:()=>lt,sign:()=>Ih,signal:()=>Jm,sin:()=>Cs,sinh:()=>Es,slice:()=>G,slice1d:()=>Th,slice2d:()=>Ah,slice3d:()=>Os,slice4d:()=>Nh,softmax:()=>rn,softplus:()=>Ls,spaceToBatchND:()=>Kn,sparseToDense:()=>bm,spectral:()=>Km,split:()=>Yt,sqrt:()=>me,square:()=>H,squaredDifference:()=>Zn,squaredDifferenceStrict:()=>pm,squeeze:()=>Qn,stack:()=>ke,step:()=>Dt,stridedSlice:()=>Rh,sub:()=>O,subStrict:()=>lm,sum:()=>U,tan:()=>_h,tanh:()=>Wr,tensor:()=>ze,tensor1d:()=>ce,tensor2d:()=>mt,tensor3d:()=>er,tensor4d:()=>ft,tensor5d:()=>Ch,tensor6d:()=>Eh,tile:()=>Ot,topk:()=>Oh,transpose:()=>K,truncatedNormal:()=>kh,unsortedSegmentSum:()=>ks,unstack:()=>Ie,variable:()=>Dh,where:()=>Oe,whereAsync:()=>Ds,zeros:()=>Ce,zerosLike:()=>W});const Km={fft:Gn,ifft:vn,rfft:Jn,irfft:xs},Jm={hammingWindow:vm,hannWindow:Pa,frame:qa,stft:Sm},Va={flipLeftRight:Tm,resizeNearestNeighbor:Mm,resizeBilinear:Fm,rotateWithOffset:Am,cropAndResize:Im,nonMaxSuppression:Nm,nonMaxSuppressionAsync:Cm,nonMaxSuppressionWithScore:Em,nonMaxSuppressionWithScoreAsync:Om,nonMaxSuppressionPadded:km,nonMaxSuppressionPaddedAsync:Dm},Xm={bandPart:Um,gramSchmidt:Wm,qr:$m},Zm={absoluteDifference:jm,computeWeightedLoss:$e,cosineDistance:Gm,hingeLoss:Pm,huberLoss:qm,logLoss:Hm,meanSquaredError:zm,sigmoidCrossEntropy:Ym,softmaxCrossEntropy:Vm};Ed(Wh);const Fs={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};const Ka=4;async function PS(e,t){const n=[],r=[],o=Array.isArray(e)?e.map(a=>a.name):Object.keys(e);for(let a=0;a{const d=await c.bytes(),b=d.reduce((L,S)=>L+S.length,0)+Ka*d.length,x=new Uint8Array(b);let w=0;for(let L=0;L{if(t+=i.byteLength,n.push(i.byteLength===i.buffer.byteLength?i:new i.constructor(i)),!(i instanceof Float32Array||i instanceof Int32Array||i instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${i.constructor.name}`)});const r=new Uint8Array(t);let o=0;return n.forEach(i=>{r.set(new Uint8Array(i.buffer),o),o+=i.byteLength}),r.buffer}const HS=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function Qm(e){return HS?Buffer.byteLength(e):new Blob([e]).size}function Ms(e){if(e.length===1)return e[0];let t=0;e.forEach(o=>{t+=o.byteLength});const n=new Uint8Array(t);let r=0;return e.forEach(o=>{n.set(new Uint8Array(o),r),r+=o.byteLength}),n.buffer}function $h(e){const t="/";for(e=e.trim();e.endsWith(t);)e=e.slice(0,e.length-1);const n=e.split(t);return n[n.length-1]}function Us(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:Qm(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:Qm(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:e.weightData.byteLength}}function zS(){const e=n=>{let r=n<<13,o=0;for(;(r&8388608)===0;)o-=8388608,r<<=1;return r&=~8388608,o+=947912704,r|o},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 YS(){const e=new Uint32Array(64);e[0]=0,e[31]=1199570944,e[32]=2147483648,e[63]=3347054592;for(let t=1;t<31;t++)e[t]=t<<23;for(let t=33;t<63;t++)e[t]=2147483648+(t-32<<23);return e}function VS(){const e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function qS(){const e=zS(),t=YS(),n=VS();return r=>{const o=new ArrayBuffer(4*r.length),i=new Uint32Array(o);for(let a=0;a>10]+(s&1023)]+t[s>>10];i[a]=c}return new Float32Array(o)}}class Ne{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return Ne.instance==null&&(Ne.instance=new Ne()),Ne.instance}static registerSaveRouter(e){Ne.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Ne.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Ne.getHandlers(e,"save")}static getLoadHandlers(e,t){return Ne.getHandlers(e,"load",t)}static getHandlers(e,t,n){const r=[],o=t==="load"?Ne.getInstance().loadRouters:Ne.getInstance().saveRouters;return o.forEach(i=>{const a=i(e,n);a!==null&&r.push(a)}),r}}const KS=e=>Ne.registerSaveRouter(e),JS=e=>Ne.registerLoadRouter(e),XS=e=>Ne.getSaveHandlers(e),ZS=(e,t)=>Ne.getLoadHandlers(e,t);const zr="://";class Ft{constructor(){this.managers={}}static getInstance(){return Ft.instance==null&&(Ft.instance=new Ft()),Ft.instance}static registerManager(e,t){f(e!=null,()=>"scheme must not be undefined or null."),e.endsWith(zr)&&(e=e.slice(0,e.indexOf(zr))),f(e.length>0,()=>"scheme must not be an empty string.");const n=Ft.getInstance();f(n.managers[e]==null,()=>`A model store manager is already registered for scheme '${e}'.`),n.managers[e]=t}static getManager(e){const t=this.getInstance().managers[e];if(t==null)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(this.getInstance().managers)}}function Ja(e){if(e.indexOf(zr)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Ft.getSchemes().join(",")}`);return{scheme:e.split(zr)[0],path:e.split(zr)[1]}}async function ef(e,t,n=!1){f(e!==t,()=>`Old path and new path are the same: '${e}'`);const r=Ne.getLoadHandlers(e);f(r.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),f(r.length<2,()=>`Copying failed because more than one (${r.length}) load handlers for source URL ${e}.`);const o=r[0],i=Ne.getSaveHandlers(t);f(i.length>0,()=>`Copying failed because no save handler is found for destination URL ${t}.`),f(i.length<2,()=>`Copying failed because more than one (${r.length}) save handlers for destination URL ${t}.`);const a=i[0],s=Ja(e).scheme,c=Ja(e).path,p=s===Ja(e).scheme,l=await o.load();n&&p&&await Ft.getManager(s).removeModel(c);const h=await a.save(l);return n&&!p&&await Ft.getManager(s).removeModel(c),h.modelArtifactsInfo}async function tf(){const e=Ft.getSchemes(),t={};for(const n of e){const r=await Ft.getManager(n).listModels();for(const o in r){const i=n+zr+o;t[i]=r[o]}}return t}async function nf(e){const t=Ja(e),n=Ft.getManager(t.scheme);return n.removeModel(t.path)}async function rf(e,t){const n=!1;return ef(e,t,n)}async function of(e,t){const n=!0;return ef(e,t,n)}const QS="model",eI=".json",tI=".weights.bin";function sf(e){return new Promise(t=>setTimeout(t)).then(e)}class Yr{constructor(e){if(!pe().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(Yr.URL_SCHEME)&&(e=e.slice(Yr.URL_SCHEME.length)),(e==null||e.length===0)&&(e=QS),this.modelTopologyFileName=e+eI,this.weightDataFileName=e+tI}async save(e){if(typeof document=="undefined")throw new Error("Browser downloads are not supported in this environment since `document` is not present");const t=window.URL.createObjectURL(new Blob([e.weightData],{type:"application/octet-stream"}));if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");{const n=[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}],r={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:n},o=window.URL.createObjectURL(new Blob([JSON.stringify(r)],{type:"application/json"})),i=this.jsonAnchor==null?document.createElement("a"):this.jsonAnchor;if(i.download=this.modelTopologyFileName,i.href=o,await sf(()=>i.dispatchEvent(new MouseEvent("click"))),e.weightData!=null){const a=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor;a.download=this.weightDataFileName,a.href=t,await sf(()=>a.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:Us(e)}}}}Yr.URL_SCHEME="downloads://";class nI{constructor(e){if(e==null||e.length<1)throw new Error(`When calling browserFiles, at least 1 file is required, but received ${e}`);this.files=e}async load(){const e=this.files[0],t=this.files.slice(1);return new Promise((n,r)=>{const o=new FileReader();o.onload=i=>{const a=JSON.parse(i.target.result),s=a.modelTopology;if(s==null){r(new Error(`modelTopology field is missing from file ${e.name}`));return}t.length===0&&n({modelTopology:s});const c=a.weightsManifest;if(c==null){r(new Error(`weightManifest field is missing from file ${e.name}`));return}let p;try{p=this.checkManifestAndWeightFiles(c,t)}catch(b){r(b);return}const l=[],h=[],d=[];c.forEach(b=>{b.paths.forEach(x=>{h.push(x),d.push(null)}),l.push(...b.weights)}),c.forEach(b=>{b.paths.forEach(x=>{const w=new FileReader();w.onload=L=>{const S=L.target.result,I=h.indexOf(x);d[I]=S,d.indexOf(null)===-1&&n({modelTopology:s,weightSpecs:l,weightData:Ms(d),format:a.format,generatedBy:a.generatedBy,convertedBy:a.convertedBy,userDefinedMetadata:a.userDefinedMetadata})},w.onerror=L=>r(`Failed to weights data from file of path '${x}'.`),w.readAsArrayBuffer(p[x])})})},o.onerror=i=>r(`Failed to read model topology and weights manifest JSON from file '${e.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),o.readAsText(e)})}checkManifestAndWeightFiles(e,t){const n=[],r=t.map(i=>$h(i.name)),o={};for(const i of e)i.paths.forEach(a=>{const s=$h(a);if(n.indexOf(s)!==-1)throw new Error(`Duplicate file basename found in weights manifest: '${s}'`);if(n.push(s),r.indexOf(s)===-1)throw new Error(`Weight file with basename '${s}' is not provided.`);o[a]=t[r.indexOf(s)]});if(n.length!==t.length)throw new Error(`Mismatch in the number of files in weights manifest (${n.length}) and the number of weight files provided (${t.length}).`);return o}}const oI=e=>pe().getBool("IS_BROWSER")&&(!Array.isArray(e)&&e.startsWith(Yr.URL_SCHEME))?rI(e.slice(Yr.URL_SCHEME.length)):null;Ne.registerSaveRouter(oI);function rI(e="model"){return new Yr(e)}function iI(e){return new nI(e)}function jh(e,t,n,r){a(e),n=n==null?0:n,r=r==null?1:r,s(n,r);let o=0;const i=c=>(c.then(p=>{const l=n+ ++o/e.length*(r-n);return t(l),p}),c);function a(c){f(c!=null&&Array.isArray(c)&&c.length>0,()=>"promises must be a none empty array")}function s(c,p){f(c>=0&&c<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${c}`),f(p>=0&&p<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${p}`),f(p>=c,()=>`startFraction must be no more than endFraction, but got startFraction ${c} and endFraction ${p}`)}return Promise.all(e.map(i))}async function Gh(e,t){t==null&&(t={});const n=t.fetchFunc==null?pe().platform.fetch:t.fetchFunc,r=e.map(h=>n(h,t.requestInit,{isBinary:!0})),o=0,i=.5,a=t.onProgress==null?await Promise.all(r):await jh(r,t.onProgress,o,i),s=a.map(h=>h.arrayBuffer()),c=.5,p=1,l=t.onProgress==null?await Promise.all(s):await jh(s,t.onProgress,c,p);return l}async function sI(e,t="",n,r){const o=a=>Gh(a,{requestInit:r}),i=af(o);return i(e,t,n)}function af(e){return async(t,n="",r)=>{const o=t.map(()=>!1),i={},a=r!=null?r.map(()=>!1):[],s=[];if(t.forEach((b,x)=>{let w=0;b.weights.forEach(L=>{const S="quantization"in L?L.quantization.dtype:L.dtype,I=Fs[S]*Q(L.shape),N=()=>{o[x]=!0,i[x]==null&&(i[x]=[]),i[x].push({manifestEntry:L,groupOffset:w,sizeBytes:I})};r!=null?r.forEach((A,E)=>{A===L.name&&(N(),a[E]=!0)}):N(),s.push(L.name),w+=I})}),!a.every(b=>b)){const b=r.filter((x,w)=>!a[w]);throw new Error(`Could not find weights in manifest with names: ${b.join(", ")}.
Manifest JSON has weights with names: ${s.join(", ")}.`)}const c=o.reduce((b,x,w)=>(x&&b.push(w),b),[]),p=[];c.forEach(b=>{t[b].paths.forEach(x=>{const w=n+(n.endsWith("/")?"":"/")+x;p.push(w)})});const l=await e(p),h={};let d=0;return c.forEach(b=>{const x=t[b].paths.length;let w=0;for(let A=0;A{const E=L.slice(A.groupOffset,A.groupOffset+A.sizeBytes),M=Bh(E,[A.manifestEntry]);for(const D in M)h[D]=M[D]}),d+=x}),h}}const aI="application/octet-stream",cI="application/json";class Ph{constructor(e,t){if(this.DEFAULT_METHOD="POST",t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,t.fetchFunc!=null?(f(typeof t.fetchFunc=="function",()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"),this.fetch=t.fetchFunc):this.fetch=pe().platform.fetch,f(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&f(e.length===2,()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`),this.path=e,t.requestInit!=null&&t.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");const t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData();const n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],r={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,userDefinedMetadata:e.userDefinedMetadata,weightsManifest:n};t.body.append("model.json",new Blob([JSON.stringify(r)],{type:cI}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:aI}),"model.weights.bin");const o=await this.fetch(this.path,t);if(o.ok)return{modelArtifactsInfo:Us(e),responses:[o]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${o.status}.`)}async load(){const e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new Error(`Request to ${this.path} failed with status code ${e.status}. Please verify this URL points to the model JSON of the model to load.`);let t;try{t=await e.json()}catch(l){let h=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?h+=" 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.":h+=" Please make sure the server is serving valid JSON for this request.",new Error(h)}const n=t.modelTopology,r=t.weightsManifest,o=t.generatedBy,i=t.convertedBy,a=t.format,s=t.userDefinedMetadata;if(n==null&&r==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);let c,p;if(r!=null){const l=await this.loadWeights(r);[c,p]=l}return{modelTopology:n,weightSpecs:c,weightData:p,userDefinedMetadata:s,generatedBy:o,convertedBy:i,format:a}}async loadWeights(e){const t=Array.isArray(this.path)?this.path[1]:this.path,[n,r]=pI(t),o=this.weightPathPrefix||n,i=[];for(const c of e)i.push(...c.weights);const a=[];e.forEach(c=>{c.paths.forEach(p=>{a.push(o+p+r)})});const s=await Gh(a,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[i,Ms(s)]}}Ph.URL_SCHEME_REGEX=/^https?:\/\//;function pI(e){const t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),r=e.substring(0,t),o=n>t?e.substring(n):"";return[r+"/",o]}function qh(e){return e.match(Ph.URL_SCHEME_REGEX)!=null}const cf=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let n=!0;if(Array.isArray(e)?n=e.every(r=>qh(r)):n=qh(e),n)return Hh(e,t)}return null};Ne.registerSaveRouter(cf);Ne.registerLoadRouter(cf);function Hh(e,t){return new Ph(e,t)}function lI(e,t){return Hh(e,t)}class zh{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}}class hI{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}}function uI(e,t,n,r){if(arguments.length===1){const o=e.modelTopology!=null||e.weightSpecs!=null;return o?new zh(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 zh({modelTopology:e}))}else return console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new zh({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:r})}function dI(e){return new hI(e)}const Vr={};Re(Vr,{browserFiles:()=>iI,browserHTTPRequest:()=>lI,concatenateArrayBuffers:()=>Ms,copyModel:()=>rf,decodeWeights:()=>Bh,encodeWeights:()=>PS,fromMemory:()=>uI,getLoadHandlers:()=>ZS,getModelArtifactsInfoForJSON:()=>Us,getSaveHandlers:()=>XS,http:()=>Hh,isHTTPScheme:()=>qh,listModels:()=>tf,loadWeights:()=>sI,moveModel:()=>of,registerLoadRouter:()=>JS,registerSaveRouter:()=>KS,removeModel:()=>nf,weightsLoaderFactory:()=>af,withSaveHandler:()=>dI});function mI(e,t,n){const r=u(e,"labels","confusionMatrix"),o=u(t,"predictions","confusionMatrix");f(n==null||n>0&&Number.isInteger(n),()=>`If provided, numClasses must be a positive integer, but got ${n}`),f(r.rank===1,()=>`Expected the rank of labels to be 1, but got ${r.rank}`),f(o.rank===1,()=>`Expected the rank of predictions to be 1, but got ${o.rank}`),f(r.shape[0]===o.shape[0],()=>`Mismatch in the number of examples: ${r.shape[0]} vs. ${o.shape[0]}. Labels and predictions should have the same number of elements.`),f(n>0&&Number.isInteger(n),()=>`numClasses is required to be a positive integer, but got ${n}`);const i=jr(C(r,"int32"),n),a=jr(C(o,"int32"),n),s=K(i);return C(Y(s,a),"int32")}const fI=m({confusionMatrix_:mI});const pf={};Re(pf,{confusionMatrix:()=>fI});const Kr={};Re(Kr,{fromPixels:()=>wI,toPixels:()=>bI});let Jr;function gI(e,t=3){if(t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(e==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let n=!1,r=!1,o=!1,i=!1,a=!1;if(e.data instanceof Uint8Array)n=!0;else if(typeof ImageData!="undefined"&&e instanceof ImageData)r=!0;else if(typeof HTMLVideoElement!="undefined"&&e instanceof HTMLVideoElement)o=!0;else if(typeof HTMLImageElement!="undefined"&&e instanceof HTMLImageElement)i=!0;else if(e.getContext!=null)a=!0;else throw new Error(`pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was ${e.constructor.name}`);if(o){const b=2;if(o&&e.readyState element.")}const s=rs(va,g.backendName);if(s!=null){const b={pixels:e},x={numChannels:t};return g.runKernel(va,b,x)}const[c,p]=o?[e.videoWidth,e.videoHeight]:[e.width,e.height];let l;a?l=e.getContext("2d").getImageData(0,0,c,p).data:r||n?l=e.data:(i||o)&&(Jr==null&&(Jr=document.createElement("canvas").getContext("2d")),Jr.canvas.width=c,Jr.canvas.height=p,Jr.drawImage(e,0,0,c,p),l=Jr.getImageData(0,0,c,p).data);let h;if(t===4)h=new Int32Array(l);else{const b=c*p;h=new Int32Array(b*t);for(let x=0;x4||i===2)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${i}`);const a=await n.data(),s=In(n),c=dt(n),p=await Promise.all([s.data(),c.data()]),l=p[0],h=p[1],d=l[0],b=h[0];if(s.dispose(),c.dispose(),n.dtype==="float32"){if(d<0||b>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but got range [${d} - ${b}].`)}else if(n.dtype==="int32"){if(d<0||b>255)throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but got range [${d} - ${b}].`)}else throw new Error(`Unsupported type for toPixels: ${n.dtype}. Please use float32 or int32 tensors.`);const x=n.dtype==="float32"?255:1,w=new Uint8ClampedArray(o*r*4);for(let L=0;Lhf});function hf(e,t){if(e.rank<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${e.rank}.`);if(t.rank<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${t.rank}.`);if(t.dtype!=="int32")throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${t.dtype}.`);if(t.shape[t.rank-1]>e.rank)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[t.rank-1]} vs. ${e.rank}`);if(e.size===0)throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);const n=t.shape,r=n[n.length-1];let o=1;for(let p=0;pp/s),1].slice(0,r);return[a,o,s,c]}const uf={};Re(uf,{Serializable:()=>Yh,SerializationMap:()=>ir,registerClass:()=>nt});class Yh{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}}class ir{constructor(){this.classNameMap={}}static getMap(){return ir.instance==null&&(ir.instance=new ir()),ir.instance}static register(e){ir.getMap().classNameMap[e.className]=[e,e.fromConfig]}}function nt(e){f(e.className!=null,()=>"Class being registered does not have the static className property defined."),f(typeof e.className=="string",()=>"className is required to be a string, but got type "+typeof e.className),f(e.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),ir.register(e)}const xI="2.3.0";class ot extends Yh{minimize(e,t=!1,n){const{value:r,grads:o}=this.computeGradients(e,n);if(n!=null){const i=n.map(a=>({name:a.name,tensor:o[a.name]}));this.applyGradients(i)}else this.applyGradients(o);return ve(o),t?r:(r.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return zl(e,t)}dispose(){this.iterations_!=null&&ve(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:_(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(ot,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});class sr extends ot{constructor(e,t,n=null){super();this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],n==null&&(this.epsilon=g.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);t.forEach((n,r)=>{const o=g.registeredVariables[n],i=!1;this.accumulatedGrads[r]==null&&(this.accumulatedGrads[r]={originalName:`${n}/accum_grad`,variable:k(()=>W(o).variable(i))}),this.accumulatedUpdates[r]==null&&(this.accumulatedUpdates[r]={originalName:`${n}/accum_var`,variable:k(()=>W(o).variable(i))});const a=Array.isArray(e)?e[r].tensor:e[n];if(a==null)return;const s=this.accumulatedGrads[r].variable,c=this.accumulatedUpdates[r].variable;k(()=>{const p=R(v(s,this.rho),v(H(a),1-this.rho)),l=v(F(me(R(c,this.epsilon)),me(R(s,this.epsilon))),a),h=R(v(c,this.rho),v(H(l),1-this.rho));s.assign(p),c.assign(h);const d=R(v(l,-this.learningRate),o);o.assign(d)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(ve(this.accumulatedGrads.map(e=>e.variable)),ve(this.accumulatedUpdates.map(e=>e.variable)))}async getWeights(){const e=[...this.accumulatedGrads,...this.accumulatedUpdates];return[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e);const t=e.length/2,n=!1;this.accumulatedGrads=e.slice(0,t).map(r=>({originalName:r.name,variable:r.tensor.variable(n)})),this.accumulatedUpdates=e.slice(t,t*2).map(r=>({originalName:r.name,variable:r.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}}sr.className="Adadelta";nt(sr);class ar extends ot{constructor(e,t=.1){super();this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);t.forEach((n,r)=>{const o=g.registeredVariables[n];if(this.accumulatedGrads[r]==null){const s=!1;this.accumulatedGrads[r]={originalName:`${n}/accumulator`,variable:k(()=>Ge(o.shape,this.initialAccumulatorValue).variable(s))}}const i=Array.isArray(e)?e[r].tensor:e[n];if(i==null)return;const a=this.accumulatedGrads[r].variable;k(()=>{const s=R(a,H(i));a.assign(s);const c=R(v(F(i,me(R(s,g.backend.epsilon()))),-this.learningRate),o);o.assign(c)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&ve(this.accumulatedGrads.map(e=>e.variable))}async getWeights(){return[await this.saveIterations()].concat(this.accumulatedGrads.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);const t=!1;this.accumulatedGrads=e.map(n=>({originalName:n.name,variable:n.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}}ar.className="Adagrad";nt(ar);class cr extends ot{constructor(e,t,n,r=null){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=r,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],k(()=>{this.accBeta1=_(t).variable(),this.accBeta2=_(n).variable()}),r==null&&(this.epsilon=g.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);k(()=>{const n=O(1,this.accBeta1),r=O(1,this.accBeta2);t.forEach((o,i)=>{const a=g.registeredVariables[o],s=!1;this.accumulatedFirstMoment[i]==null&&(this.accumulatedFirstMoment[i]={originalName:`${o}/m`,variable:k(()=>W(a).variable(s))}),this.accumulatedSecondMoment[i]==null&&(this.accumulatedSecondMoment[i]={originalName:`${o}/v`,variable:k(()=>W(a).variable(s))});const c=Array.isArray(e)?e[i].tensor:e[o];if(c==null)return;const p=this.accumulatedFirstMoment[i].variable,l=this.accumulatedSecondMoment[i].variable,h=R(v(p,this.beta1),v(c,1-this.beta1)),d=R(v(l,this.beta2),v(H(c),1-this.beta2)),b=F(h,n),x=F(d,r);p.assign(h),l.assign(d);const w=R(v(F(b,R(me(x),this.epsilon)),-this.learningRate),a);a.assign(w)}),this.accBeta1.assign(v(this.accBeta1,this.beta1)),this.accBeta2.assign(v(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&ve(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&ve(this.accumulatedSecondMoment.map(e=>e.variable))}async getWeights(){const e=[...this.accumulatedFirstMoment,...this.accumulatedSecondMoment];return[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e),k(()=>{this.accBeta1.assign(Je(this.beta1,this.iterations_+1)),this.accBeta2.assign(Je(this.beta2,this.iterations_+1))});const t=e.length/2,n=!1;this.accumulatedFirstMoment=e.slice(0,t).map(r=>({originalName:r.name,variable:r.tensor.variable(n)})),this.accumulatedSecondMoment=e.slice(t,t*2).map(r=>({originalName:r.name,variable:r.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)}}cr.className="Adam";nt(cr);class pr extends ot{constructor(e,t,n,r=null,o=0){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=r,this.decay=o,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],k(()=>{this.iteration=_(0).variable(),this.accBeta1=_(t).variable()}),r==null&&(this.epsilon=g.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);k(()=>{const n=O(1,this.accBeta1),r=F(-this.learningRate,R(v(this.iteration,this.decay),1));t.forEach((o,i)=>{const a=g.registeredVariables[o],s=!1;this.accumulatedFirstMoment[i]==null&&(this.accumulatedFirstMoment[i]={originalName:`${o}/m`,variable:W(a).variable(s)}),this.accumulatedWeightedInfNorm[i]==null&&(this.accumulatedWeightedInfNorm[i]={originalName:`${o}/v`,variable:W(a).variable(s)});const c=Array.isArray(e)?e[i].tensor:e[o];if(c==null)return;const p=this.accumulatedFirstMoment[i].variable,l=this.accumulatedWeightedInfNorm[i].variable,h=R(v(p,this.beta1),v(c,1-this.beta1)),d=v(l,this.beta2),b=Ee(c),x=kt(d,b);p.assign(h),l.assign(x);const w=R(v(F(r,n),F(h,R(x,this.epsilon))),a);a.assign(w)}),this.iteration.assign(R(this.iteration,1)),this.accBeta1.assign(v(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&ve(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&ve(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)}}pr.className="Adamax";nt(pr);class on extends ot{constructor(e){super();this.learningRate=e,this.setLearningRate(e)}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);t.forEach((n,r)=>{const o=Array.isArray(e)?e[r].tensor:e[n];if(o==null)return;const i=g.registeredVariables[n];k(()=>{const a=R(v(this.c,o),i);i.assign(a)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=al(_(-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)}}on.className="SGD";nt(on);class lr extends on{constructor(e,t,n=!1){super(e);this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=_(this.momentum)}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);t.forEach((n,r)=>{const o=g.registeredVariables[n];if(this.accumulations[r]==null){const s=!1;this.accumulations[r]={originalName:`${n}/momentum`,variable:k(()=>W(o).variable(s))}}const i=this.accumulations[r].variable,a=Array.isArray(e)?e[r].tensor:e[n];if(a==null)return;k(()=>{let s;const c=R(v(this.m,i),a);this.useNesterov?s=R(v(this.c,R(a,v(c,this.m))),o):s=R(v(this.c,c),o),i.assign(c),o.assign(s)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&ve(this.accumulations.map(e=>e.variable))}setMomentum(e){this.momentum=e}async getWeights(){return[await this.saveIterations()].concat(this.accumulations.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);const t=!1;this.accumulations=e.map(n=>({originalName:n.name,variable:n.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)}}lr.className="Momentum";nt(lr);class hr extends ot{constructor(e,t=.9,n=0,r=null,o=!1){super();if(this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=r,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=o,r==null&&(this.epsilon=g.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);t.forEach((n,r)=>{const o=g.registeredVariables[n],i=!1;this.accumulatedMeanSquares[r]==null&&(this.accumulatedMeanSquares[r]={originalName:`${n}/rms`,variable:k(()=>W(o).variable(i))}),this.accumulatedMoments[r]==null&&(this.accumulatedMoments[r]={originalName:`${n}/momentum`,variable:k(()=>W(o).variable(i))}),this.accumulatedMeanGrads[r]==null&&this.centered&&(this.accumulatedMeanGrads[r]={originalName:`${n}/mg`,variable:k(()=>W(o).variable(i))});const a=Array.isArray(e)?e[r].tensor:e[n];if(a==null)return;const s=this.accumulatedMeanSquares[r].variable,c=this.accumulatedMoments[r].variable;k(()=>{const p=R(v(s,this.decay),v(H(a),1-this.decay));if(this.centered){const l=this.accumulatedMeanGrads[r].variable,h=R(v(l,this.decay),v(a,1-this.decay)),d=F(v(a,this.learningRate),me(O(p,R(H(h),this.epsilon)))),b=R(v(c,this.momentum),d);s.assign(p),l.assign(h),c.assign(b);const x=O(o,b);o.assign(x)}else{const l=R(v(s,this.decay),v(H(a),1-this.decay)),h=R(v(c,this.momentum),F(v(a,this.learningRate),me(R(l,this.epsilon))));s.assign(l),c.assign(h);const d=O(o,h);o.assign(d)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&ve(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&ve(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&ve(this.accumulatedMoments.map(e=>e.variable))}async getWeights(){const e=[...this.accumulatedMeanSquares,...this.accumulatedMoments];return this.centered&&e.push(...this.accumulatedMeanGrads),[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e);const t=this.centered?e.length/3:e.length/2,n=!1;this.accumulatedMeanSquares=e.slice(0,t).map(r=>({originalName:r.name,variable:r.tensor.variable(n)})),this.accumulatedMoments=e.slice(t,t*2).map(r=>({originalName:r.name,variable:r.tensor.variable(n)})),this.centered&&(this.accumulatedMeanGrads=e.slice(t*2,t*3).map(r=>({originalName:r.name,variable:r.tensor.variable(n)})))}getConfig(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}}static fromConfig(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)}}hr.className="RMSProp";nt(hr);class Tn{static sgd(e){return new on(e)}static momentum(e,t,n=!1){return new lr(e,t,n)}static rmsprop(e,t=.9,n=0,r=null,o=!1){return new hr(e,t,n,r,o)}static adam(e=.001,t=.9,n=.999,r=null){return new cr(e,t,n,r)}static adadelta(e=.001,t=.95,n=null){return new sr(e,t,n)}static adamax(e=.002,t=.9,n=.999,r=null,o=0){return new pr(e,t,n,r,o)}static adagrad(e,t=.1){return new ar(e,t)}}lr,on,sr,ar,hr,pr,cr;const yI={sgd:Tn.sgd,momentum:Tn.momentum,adadelta:Tn.adadelta,adagrad:Tn.adagrad,rmsprop:Tn.rmsprop,adamax:Tn.adamax,adam:Tn.adam};const LI=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:e=>e())();function vI(){return new Promise(e=>LI(()=>e()))}function SI(e,t,n){const r=n*(typeof e=="number"?e:e[0]),o=t*(typeof e=="number"?e:e[1]);return[r,o]}function II(e,t,n,r=!0){let o=[];if(r)o=o.concat(t.slice(0)),o.push(e[0]/n),o=o.concat(e.slice(1));else{o=o.concat(e[0]);const i=t.length;for(let a=0;a=t*2+1||a%2===1?i.push(a):o.push(a);r.push(...o),r.push(0),r.push(...i)}return r}function AI(e,t,n,r=!0){const o=[];r?o.push(e[0]/n):o.push(e[0]*n);for(let i=1;iCI,ERF_A2:()=>EI,ERF_A3:()=>OI,ERF_A4:()=>kI,ERF_A5:()=>DI,ERF_P:()=>_I,PARALLELIZE_THRESHOLD:()=>Da,SELU_SCALE:()=>Kh,SELU_SCALEALPHA:()=>Vh,applyActivation:()=>rr,assertAndGetBroadcastShape:()=>q,assertAxesAreInnerMostDims:()=>zw,assertParamsConsistent:()=>pl,assignToTypedArray:()=>GI,axesAreInnerMostDims:()=>Vp,calculateShapes:()=>mm,castTensor:()=>HI,combineLocations:()=>Bd,complexWithEvenIndex:()=>BI,complexWithOddIndex:()=>$I,computeConv2DInfo:()=>je,computeConv3DInfo:()=>Ln,computeDefaultPad:()=>sl,computeDilation2DInfo:()=>ix,computeOptimalWindowSize:()=>_y,computeOutAndReduceShapes:()=>Kp,computeOutShape:()=>ll,computePool2DInfo:()=>_t,computePool3DInfo:()=>Qt,convertConv2DDataFormat:()=>yn,eitherStridesOrDilationsAreOne:()=>le,expandShapeToKeepDim:()=>we,exponent:()=>qI,exponents:()=>PI,getAxesPermutation:()=>ge,getBroadcastDims:()=>my,getComplexWithIndex:()=>jI,getFusedBiasGradient:()=>nr,getFusedDyActivation:()=>tr,getImageCenter:()=>SI,getInnerMostAxes:()=>De,getPermuted:()=>TI,getReductionAxes:()=>ae,getReshaped:()=>II,getReshapedPermuted:()=>AI,getSliceBeginCoords:()=>NI,getSliceSize:()=>RI,getUndoAxesPermutation:()=>Un,linspaceImpl:()=>YI,log:()=>MI,mergeRealAndImagArrays:()=>UI,prepareAndValidate:()=>hf,prepareSplitSize:()=>yh,reshapeTensor:()=>zI,segment_util:()=>qd,shouldFuse:()=>or,splitRealAndImagArrays:()=>WI,tupleValuesAreOne:()=>ct,upcastType:()=>Mr,validateInput:()=>Ba,validateUpdateShape:()=>Fh,warn:()=>FI});function HI(e,t,n){if(t==="complex64"){if(e.dtype==="complex64")return e.clone();const r=Ce(e.shape),o=C(e,"float32"),i=n.complex(o,r);return r.dispose(),o.dispose(),i}if(!kp(e.dtype,t))return g.makeTensorFromDataId(e.dataId,e.shape,t);if(e.dtype==="complex64"){const r=n.real(e),o=C(r,t);return r.dispose(),o}if(t==="int32")return n.int(e);if(t==="bool"){const r=_(0,e.dtype),o=n.notEqual(e,r);return r.dispose(),o}else throw new Error(`Error in Cast: failed to cast ${e.dtype} to ${t}`)}function zI(e,t){return g.makeTensorFromDataId(e.dataId,t,e.dtype)}function YI(e,t,n){const r=(t-e)/(n-1),o=Pt(n,"float32");o[0]=e;for(let i=1;i{const a=[...o];a[n]=i;const s=G(e,r,a);return r[n]+=i,s})}function ff(e,t){const n=new Array(e.rank);for(let o=0;oN.value-I.value);const w=h*r,L=c.subarray(w,w+r),S=p.subarray(w,w+r);for(let I=0;IHa,nonMaxSuppressionV4Impl:()=>za,nonMaxSuppressionV5Impl:()=>Ya,split:()=>mf,tile:()=>ff,topkImpl:()=>gf,whereImpl:()=>Wa});const VI=1e-7,KI=1e-4;class JI{constructor(e,t){this.backend=e,this.dataMover=t,this.data=new WeakMap(),this.dataIdsCount=0}get(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)}set(e,t){this.dataIdsCount++,this.data.set(e,t)}has(e){return this.data.has(e)}delete(e){return this.dataIdsCount--,this.data.delete(e)}numDataIds(){return this.dataIdsCount}}class XI{time(e){return T("time")}read(e){return T("read")}readSync(e){return T("readSync")}numDataIds(){return T("numDataIds")}disposeData(e){return T("disposeData")}write(e,t,n){return T("write")}move(e,t,n,r){return T("move")}memory(){return T("memory")}floatPrecision(){return T("floatPrecision")}epsilon(){return this.floatPrecision()===32?VI:KI}batchMatMul(e,t,n,r){return T("batchMatMul")}fusedBatchMatMul({a:e,b:t,transposeA:n,transposeB:r,bias:o,activation:i,preluActivationWeights:a}){return T("fusedBatchMatMul")}slice(e,t,n){return T("slice")}stridedSlice(e,t,n,r){return T("stridedSlice")}unstack(e,t){return T("unstack")}reverse(e,t){return T("reverse")}concat(e,t){return T("concat")}neg(e){return T("neg")}add(e,t){return T("add")}addN(e){return T("addN")}subtract(e,t){return T("subtract")}multiply(e,t){return T("multiply")}realDivide(e,t){return T("realDivide")}floorDiv(e,t){return T("floorDiv")}sum(e,t){return T("sum")}prod(e,t){return T("prod")}unsortedSegmentSum(e,t,n){return T("unsortedSegmentSum")}argMin(e,t){return T("argMin")}argMax(e,t){return T("argMax")}equal(e,t){return T("equal")}notEqual(e,t){return T("notEqual")}less(e,t){return T("less")}lessEqual(e,t){return T("lessEqual")}greater(e,t){return T("greater")}greaterEqual(e,t){return T("greaterEqual")}logicalNot(e){return T("logicalNot")}logicalAnd(e,t){return T("logicalAnd")}logicalOr(e,t){return T("logicalOr")}where(e){return T("where")}select(e,t,n){return T("select")}topk(e,t,n){return T("topk")}min(e,t){return T("min")}minimum(e,t){return T("minimum")}mod(e,t){return T("mod")}max(e,t){return T("max")}maximum(e,t){return T("maximum")}all(e,t){return T("all")}any(e,t){return T("any")}squaredDifference(e,t){return T("squaredDifference")}ceil(e){return T("ceil")}floor(e){return T("floor")}round(e){return T("round")}sign(e){return T("sign")}isNaN(e){return T("isNaN")}isInf(e){return T("isInf")}isFinite(e){return T("isFinite")}pow(e,t){return T("pow")}exp(e){return T("exp")}expm1(e){return T("expm1")}softmax(e,t){return T("softmax")}log(e){return T("log")}log1p(e){return T("log1p")}sqrt(e){return T("sqrt")}rsqrt(e){return T("rsqrt")}square(e){return T("square")}reciprocal(e){return T("reciprocal")}relu(e){return T("relu")}relu6(e){return T("relu6")}prelu(e,t){return T("prelu")}elu(e){return T("elu")}eluDer(e,t){return T("eluDer")}selu(e){return T("selu")}int(e){return T("int")}clip(e,t,n){return T("clip")}abs(e){return T("abs")}complexAbs(e){return T("complexAbs")}sigmoid(e){return T("sigmoid")}softplus(e){return T("softplus")}sin(e){return T("sin")}cos(e){return T("cos")}tan(e){return T("tan")}asin(e){return T("asin")}acos(e){return T("acos")}atan(e){return T("atan")}atan2(e,t){return T("atan2")}sinh(e){return T("sinh")}cosh(e){return T("cosh")}tanh(e){return T("tanh")}asinh(e){return T("asinh")}acosh(e){return T("acosh")}atanh(e){return T("atanh")}erf(e){return T("erf")}step(e,t){return T("step")}fusedConv2d({input:e,filter:t,convInfo:n,bias:r,activation:o,preluActivationWeights:i}){return T("fusedConv2d")}conv2d(e,t,n){return T("conv2d")}conv2dDerInput(e,t,n){return T("conv2dDerInput")}conv2dDerFilter(e,t,n){return T("conv2dDerFilter")}fusedDepthwiseConv2D({input:e,filter:t,convInfo:n,bias:r,activation:o,preluActivationWeights:i}){return T("fusedDepthwiseConv2D")}depthwiseConv2D(e,t,n){return T("depthwiseConv2D")}depthwiseConv2DDerInput(e,t,n){return T("depthwiseConv2DDerInput")}depthwiseConv2DDerFilter(e,t,n){return T("depthwiseConv2DDerFilter")}conv3d(e,t,n){return T("conv3d")}conv3dDerInput(e,t,n){return T("conv3dDerInput")}conv3dDerFilter(e,t,n){return T("conv3dDerFilter")}maxPool(e,t){return T("maxPool")}maxPoolBackprop(e,t,n,r){return T("maxPoolBackprop")}avgPool(e,t){return T("avgPool")}avgPoolBackprop(e,t,n){return T("avgPoolBackprop")}avgPool3d(e,t){return T("avgPool3d")}avgPool3dBackprop(e,t,n){return T("avgPool3dBackprop")}maxPool3d(e,t){return T("maxPool3d")}maxPool3dBackprop(e,t,n,r){return T("maxPool3dBackprop")}reshape(e,t){return T("reshape")}cast(e,t){return T("cast")}tile(e,t){return T("tile")}pad(e,t,n){return T("pad")}transpose(e,t){return T("transpose")}gather(e,t,n){return T("gather")}gatherND(e,t){return T("gatherND")}scatterND(e,t,n){return T("scatterND")}batchToSpaceND(e,t,n){return T("batchToSpaceND")}spaceToBatchND(e,t,n){return T("spaceToBatchND")}resizeBilinear(e,t,n,r){return T("resizeBilinear")}resizeBilinearBackprop(e,t,n){return T("resizeBilinearBackprop")}resizeNearestNeighbor(e,t,n,r){return T("resizeNearestNeighbor")}resizeNearestNeighborBackprop(e,t,n){return T("resizeNearestNeighborBackprop")}batchNorm(e,t,n,r,o,i){return T("batchNorm")}localResponseNormalization4D(e,t,n,r,o){return T("localResponseNormalization4D")}LRNGrad(e,t,n,r,o,i,a){return T("LRNGrad")}multinomial(e,t,n,r){return T("multinomial")}oneHot(e,t,n,r){return T("oneHot")}cumsum(e,t,n,r){return T("cumsum")}nonMaxSuppression(e,t,n,r,o){return T("nonMaxSuppression")}fft(e){return T("fft")}ifft(e){return T("ifft")}complex(e,t){return T("complex")}real(e){return T("real")}imag(e){return T("imag")}cropAndResize(e,t,n,r,o,i){return T("cropAndResize")}depthToSpace(e,t,n){return T("depthToSpace")}split(e,t,n){return T("split")}sparseToDense(e,t,n,r){return T("sparseToDense")}diag(e){return T("diag")}fill(e,t,n){return T("fill")}onesLike(e){return T("onesLike")}zerosLike(e){return T("zerosLike")}linspace(e,t,n){return T("linspace")}dispose(){return T("dispose")}}function T(e){throw new Error(`'${e}' not yet implemented or not found in the registry. Did you forget to import the kernel?`)}const wf={kernelName:xo,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(e,Dt(C(n,"float32"),-1))}}};const xf={kernelName:yo,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const r=H(C(n,"float32")),o=me(O(_(1),r));return ne(F(e,o))}}}};const yf={kernelName:Lo,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const r=me(O(H(C(n,"float32")),1));return F(e,r)}}}};const Lf={kernelName:kn,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,o=q(n.shape,r.shape),i=()=>{let s=e;const c=ae(n.shape,o);return c.length>0&&(s=U(s,c)),y(s,n.shape)},a=()=>{let s=e;const c=ae(r.shape,o);return c.length>0&&(s=U(s,c)),y(s,r.shape)};return{a:i,b:a}}};const vf={kernelName:vo,saveAllInputs:!0,gradFunc:(e,t)=>{const n={};return t.forEach((r,o)=>{n[o]=()=>e.clone()}),n}};const Sf={kernelName:So,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>W(n)}}};const If={kernelName:Io,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>W(n)}}};const Tf={kernelName:To,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>F(e,me(O(_(1),H(C(n,"float32")))))}}};const Af={kernelName:Ao,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const r=me(R(_(1),H(C(n,"float32"))));return F(e,r)}}}};const Nf={kernelName:_o,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,o=q(n.shape,r.shape),i=()=>{const s=R(H(n),H(r));let c=v(e,F(r,s));const p=ae(n.shape,o);return p.length>0&&(c=U(c,p)),y(c,n.shape)},a=()=>{const s=R(H(n),H(r));let c=ne(v(e,F(n,s)));const p=ae(r.shape,o);return p.length>0&&(c=U(c,p)),y(c,r.shape)};return{a:i,b:a}}};const Rf={kernelName:No,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>F(e,R(H(C(n,"float32")),1))}}};const _f={kernelName:Ro,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>F(e,O(_(1),H(C(n,"float32"))))}}};function ZI(e,t,n,r,o=[1,1,1],i,a){const s=u(e,"dy","avgPool3dBackprop"),c=u(t,"input","avgPool3dBackprop");let p=s,l=c,h=!1;c.rank===4&&(h=!0,p=y(s,[1,s.shape[0],s.shape[1],s.shape[2],s.shape[3]]),l=y(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]])),f(p.rank===5,()=>`Error in avgPool3dBackprop: dy must be rank 5 but got rank ${p.rank}.`),f(l.rank===5,()=>`Error in avgPool3dBackprop: input must be rank 5 but got rank ${l.rank}.`),f(le(r,o),()=>`Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides ${r} and dilations '${o}'`),a!=null&&f(X(i),()=>`Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode ${a} but got pad ${i}.`);const d=L=>{const S=Qt(l.shape,n,r,o,i,a);return L.avgPool3dBackprop(p,l,S)},b={dy:p,input:l},x={filterSize:n,strides:r,dilations:o,pad:i,dimRoundingMode:a},w=g.runKernelFunc(d,b,null,Fc,x);return h?y(w,[w.shape[1],w.shape[2],w.shape[3],w.shape[4]]):w}const Cf=m({avgPool3dBackprop_:ZI});const Ef={kernelName:Eo,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{filterSize:o,strides:i,dilations:a,pad:s,dimRoundingMode:c}=n,p=a==null?[1,1,1]:a;return{x:()=>Cf(e,r,o,i,p,s,c)}}};function QI(e,t,n,r,o){const i=u(e,"dy","avgPoolBackprop"),a=u(t,"input","avgPoolBackprop");f(a.rank===i.rank,()=>`Rank of input (${a.rank}) does not match rank of dy (${i.rank})`);let s=a,c=i,p=!1;a.rank===3&&(p=!0,s=y(a,[1,a.shape[0],a.shape[1],a.shape[2]]),c=y(i,[1,i.shape[0],i.shape[1],i.shape[2]])),f(c.rank===4,()=>`Error in avgPoolBackprop: dy must be rank 4 but got rank ${c.rank}.`),f(s.rank===4,()=>`Error in avgPoolBackprop: input must be rank 4 but got rank ${s.rank}.`);const l=x=>{const w=_t(s.shape,n,r,1,o);return x.avgPoolBackprop(c,s,w)},h={dy:c,input:s},d={filterSize:n,strides:r,pad:o},b=g.runKernelFunc(l,h,null,Dc,d);return p?y(b,[b.shape[1],b.shape[2],b.shape[3]]):b}const Of=m({avgPoolBackprop_:QI});const kf={kernelName:Co,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{filterSize:o,strides:i,pad:a}=n;return{x:()=>Of(e,r,o,i,a)}}};const Df={kernelName:Oo,inputsToSave:["a","b"],gradFunc:(e,t,n)=>{const[r,o]=t,{transposeA:i,transposeB:a}=n;return!i&&!a?{a:()=>Y(e,o,!1,!0),b:()=>Y(r,e,!0,!1)}:!i&&a?{a:()=>Y(e,o,!1,!1),b:()=>Y(e,r,!0,!1)}:i&&!a?{a:()=>Y(o,e,!1,!0),b:()=>Y(r,e,!1,!1)}:{a:()=>Y(o,e,!0,!0),b:()=>Y(e,r,!0,!0)}}};const Ff={kernelName:ko,gradFunc:(e,t,n)=>{const{blockShape:r,crops:o}=n;return{x:()=>Kn(e,r,o)}}};const Mf={kernelName:Do,gradFunc:(e,t,n)=>{const r=n,o=r.inputShape,i=r.shape,a=Array.from(i);for(let c=o.length-1;c>=0;c--)if(o[c]===i[c])a[c]=1;else if(o[c]!==1)throw new Error(`broadcastTo(): [${o}] cannot be broadcast to [${i}].`);const s=[];for(let c=0;c1&&s.push(c);return{x:()=>U(e,s,!0)}}};const Uf={kernelName:Dn,gradFunc:e=>({x:()=>e.clone()})};const Wf={kernelName:Fo,gradFunc:e=>({x:()=>W(e)})};const Bf={kernelName:Mo,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{clipValueMin:o,clipValueMax:i}=n;return{x:()=>Oe(Lt(ht(r,o),ut(r,i)),e,W(e))}}};const $f={kernelName:Uo,saveAllInputs:!0,gradFunc:(e,t,n)=>{const r=t.map(c=>c.shape),{axis:o}=n,i=z(o,t[0].shape)[0],a=r.map(c=>c[i]),s=Yt(e,a,i);return s.map(c=>()=>c)}};const jf={kernelName:Wo,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[r,o]=t,{dilations:i,strides:a,pad:s,dataFormat:c}=n;return f(ct(i),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${i}'`),{x:()=>$r(r.shape,e,o,a,s,c),filter:()=>Hr(r,e,o.shape,a,s,c)}}};const Gf={kernelName:Bo,inputsToSave:["dy","filter"],gradFunc:(e,t,n)=>{const[r,o]=t,{strides:i,pad:a,dataFormat:s,dimRoundingMode:c}=n;return{dy:()=>xe(e,o,i,a,s,1,c),filter:()=>Hr(e,r,o.shape,i,a,s,c)}}};function eT(e,t,n,r,o){let i=e;e.rank===4&&(i=y(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let a=t;a.rank===4&&(a=y(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),f(i.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${i.shape}.`),f(a.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${a.shape}.`),f(n.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${n}.`),f(i.shape[4]===n[3],()=>`Error in conv3dDerFilter: depth of input ${i.shape[4]}) must match input depth in filter (${n[3]}.`),f(a.shape[4]===n[4],()=>`Error in conv3dDerFilter: depth of dy (${a.shape[4]}) must match output depth for filter (${n[4]}).`);const s=l=>{const h=1,d=Ln(i.shape,n,r,h,o);return l.conv3dDerFilter(i,a,d)},c={x:i,y:a},p={strides:r,pad:o};return g.runKernelFunc(s,c,null,Wc,p)}const Pf=m({conv3DBackpropFilter_:eT});const qf={kernelName:$o,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:r,strides:o,pad:i}=n;f(ct(r),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${r}'`);const[a,s]=t;return{x:()=>ka(a.shape,e,s,o,i),filter:()=>Pf(a,e,s.shape,o,i)}}};const Hf={kernelName:jo,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(ne(Cs(C(n,"float32"))),e)}}};const zf={kernelName:Go,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(Es(C(n,"float32")),e)}}};const Yf={kernelName:Po,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{axis:o,exclusive:i,reverse:a}=n;return{x:()=>{const s=ge([o],r.rank);let c=fs(e,o,i,!a);return s!=null&&(c=K(c,s)),c}}}};const Vf={kernelName:qo,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:r,strides:o,pad:i,dimRoundingMode:a}=n,s=r==null?[1,1]:r;f(ct(s),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${s}'`);const[c,p]=t;f(c.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${c.rank}.`),f(p.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${p.rank}.`),f(c.shape[3]===p.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${c.shape[3]}) must match the inChannels dimension in filter ${p.shape[2]}.`),f(le(o,s),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${s}'.`),a!=null&&f(X(i),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${i}.`);const l=je(c.shape,p.shape,o,s,i,a,!0);return{x:()=>Ga(c.shape,e,p,l),filter:()=>ja(c,e,p.shape,l)}}};const Kf={kernelName:Ho,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[r,o]=t,i={x:r,filter:o,dy:e},a={x:r,filter:o,dy:e};return{x:()=>g.runKernel(Hc,i,n),filter:()=>g.runKernel(zc,a,n)}}};const Jf={kernelName:zo,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,o=q(n.shape,r.shape),i=()=>{const s=F(e,C(r,"float32")),c=ae(n.shape,o);return c.length>0?y(U(s,c),n.shape):s},a=()=>{let s=v(e,C(n,"float32"));const c=ae(r.shape,o);c.length>0&&(s=y(U(s,c),r.shape));const p=H(r);return ne(F(s,C(p,"float32")))};return{a:i,b:a}}};const Xf={kernelName:Yo,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t,r=i=>i.eluDer(e,n),o={dy:e,y:n};return{x:()=>g.runKernelFunc(r,o,null,Yc)}}};const Zf={kernelName:Vo,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,r=v(Se(ne(H(n))),2/Math.sqrt(Math.PI));return{x:()=>v(e,r)}}};const Qf={kernelName:Ko,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(e,n)}}};const eg={kernelName:Jo,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(e,Se(n))}}};const tg={kernelName:Xo,gradFunc:e=>({x:()=>W(e)})};const ng={kernelName:Zo,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,o=q(n.shape,r.shape),i=()=>{const s=F(e,C(r,"float32")),c=ae(n.shape,o);return c.length>0?y(U(s,c),n.shape):s},a=()=>{let s=v(e,C(n,"float32"));const c=ae(r.shape,o);c.length>0&&(s=y(U(s,c),r.shape));const p=H(r);return ne(F(s,C(p,"float32")))};return{a:i,b:a}}};const rg={kernelName:Qo,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{const{varianceEpsilon:r}=n,[o,i,a,s]=t,c=s==null?_(1):s,p=ae(i.shape,o.shape),l=[];if(i.rank===1){for(let A=0;Ai.rank===1?y(v(v(e,Ot(y(b,[1,1,1,i.shape[0]]),l)),c),o.shape):y(v(v(e,b),c),o.shape),L=()=>{let A=v(v(b,_(-1)),d);return i.rank===1&&(A=U(A,p)),y(A,i.shape)},S=()=>{let A=v(v(x,h),d);return i.rank===1&&(A=U(A,p)),y(A,i.shape)},I=()=>{const A=v(h,b);let E=v(e,A);return i.rank===1&&(E=U(E,p)),y(E,i.shape)},N=()=>{let A=e;return i.rank===1&&(A=U(A,p)),y(A,i.shape)};return{x:w,mean:L,variance:S,scale:I,offset:N}}};const sg={kernelName:ei,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{const[r,o]=t,{axis:i}=n,a=z(i,r.shape)[0],s=()=>{const c=r.shape,p=o.size,l=c.slice(0,a),h=l.length,d=c.slice(i,c.length).slice(1),b=d.length,x=og(0,h),w=og(h+1,h+1+b),L=ig([l,[p],d]),S=y(e,L),I=y(o,[p]),N=ig([[h],x,w]),A=K(S,N);let E=ks(A,I,r.shape[a]);const M=Un(N);return E=K(E,M),E};return{x:s,indices:()=>o}}};function og(e,t){const n=[];for(let r=e;r{const[n,r]=t;return{a:()=>W(n),b:()=>W(r)}}};const cg={kernelName:ni,gradFunc:e=>({x:()=>C(e,"float32")})};const pg={kernelName:ri,gradFunc:e=>({x:()=>W(e)})};const lg={kernelName:oi,gradFunc:e=>({x:()=>W(e)})};const hg={kernelName:ii,gradFunc:e=>({x:()=>W(e)})};const ug={kernelName:ai,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>F(e,R(n,1))}}};const dg={kernelName:si,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>F(e,C(n,"float32"))}}};const mg={kernelName:ci,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r]=t,{axis:o}=n;return{logits:()=>{const i=!0,a=Se(r);return O(e,v(U(e,o,i),a))}}}};function tT(e,t,n,r=5,o=1,i=1,a=.5){const s=l=>l.LRNGrad(n,e,t,r,o,i,a),c={x:e,y:t,dy:n},p={depthRadius:r,bias:o,alpha:i,beta:a};return g.runKernelFunc(s,c,null,cp,p)}const fg=m({localResponseNormalizationBackprop_:tT});const gg={kernelName:pi,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r,o]=t,{depthRadius:i,bias:a,alpha:s,beta:c}=n;return{x:()=>fg(r,o,e,i,a,s,c)}}};function Xa(e,t,n,r,o){return t.rank{const i=v(e,C(tn(n,t),e.dtype));return o==null?i:K(i,o)}}}const Jh={kernelName:li,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const r=n,{reductionIndices:o}=r,[i,a]=t,s=z(o,i.shape),c=ge(s,i.rank),p=Xa(e,a,i,s,c);return{x:()=>{let l=p.x();return c!=null&&(l=K(l)),l}}}};const bg={kernelName:hi,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,o=()=>v(e,C(ht(n,r),"float32")),i=()=>v(e,C(Hn(n,r),"float32"));return{a:o,b:i}}};function nT(e,t,n,r,o,i=[1,1,1],a,s){const c=u(e,"dy","maxPool3dBackprop"),p=u(t,"input","maxPool3dBackprop"),l=u(n,"output","maxPool3dBackprop");let h=c,d=p,b=l,x=!1;p.rank===4&&(x=!0,h=y(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]]),d=y(p,[1,p.shape[0],p.shape[1],p.shape[2],p.shape[3]]),b=y(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]])),f(h.rank===5,()=>`Error in maxPool3dBackprop: dy must be rank 5 but got rank ${h.rank}.`),f(d.rank===5,()=>`Error in maxPool3dBackprop: input must be rank 5 but got rank ${d.rank}.`),f(b.rank===5,()=>`Error in maxPool3dBackprop: output must be rank 5 but got rank ${b.rank}.`),f(le(o,i),()=>`Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides ${o} and dilations '${i}'`),s!=null&&f(X(a),()=>`Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode ${s} but got pad ${a}.`);const w=N=>{const A=Qt(d.shape,r,o,i,a,s);return N.maxPool3dBackprop(h,d,b,A)},L={dy:h,input:d,output:b},S={filterSize:r,strides:o,dilations:i,pad:a,dimRoundingMode:s},I=g.runKernelFunc(w,L,null,lp,S);return x?y(I,[I.shape[1],I.shape[2],I.shape[3],I.shape[4]]):I}const wg=m({maxPool3dBackprop_:nT});const xg={kernelName:di,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r,o]=t,{filterSize:i,strides:a,dilations:s,pad:c,dimRoundingMode:p}=n,l=s==null?[1,1,1]:s;return{x:()=>wg(e,r,o,i,a,l,c,p)}}};function rT(e,t,n,r,o,i,a){const s=u(e,"dy","maxPoolBackprop"),c=u(t,"input","maxPoolBackprop"),p=u(n,"output","maxPoolBackprop");f(c.rank===s.rank,()=>`Rank of input (${c.rank}) does not match rank of dy (${s.rank})`),f(s.rank===4,()=>`Error in maxPoolBackprop: dy must be rank 4 but got rank ${s.rank}.`),f(c.rank===4,()=>`Error in maxPoolBackprop: input must be rank 4 but got rank ${c.rank}.`),a!=null&&f(X(i),()=>`Error in maxPoolBackprop: pad must be an integer when using, dimRoundingMode ${a} but got pad ${i}.`);const l=b=>{const x=_t(c.shape,r,o,1,i,a);return b.maxPoolBackprop(s,c,p,x)},h={dy:s,input:c,output:p},d={filterSize:r,strides:o,pad:i,dimRoundingMode:a};return g.runKernelFunc(l,h,null,pp,d)}const yg=m({maxPoolBackprop_:rT});const Lg={kernelName:ui,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r,o]=t,{filterSize:i,strides:a,pad:s}=n;return{x:()=>yg(e,r,o,i,a,s)}}};const vg={kernelName:mi,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const r=n,{axis:o}=r,[i,a]=t,s=z(o,i.shape),c=ge(s,i.rank),p=Xa(e,a,i,s,c);return{x:()=>{let l=p.x();return c!=null&&(l=K(l)),l}}}};const Sg={kernelName:fi,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,o=()=>v(e,C(ut(n,r),"float32")),i=()=>v(e,C(tt(n,r),"float32"));return{a:o,b:i}}};const Ig={kernelName:gi,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,o=q(n.shape,r.shape),i=()=>{const s=ae(n.shape,o);return s.length>0?y(U(e,s),n.shape):e},a=()=>{const s=v(e,ne(Pn(F(n,r)))),c=ae(r.shape,o);return c.length>0?y(U(s,c),r.shape):s};return{a:i,b:a}}};const Tg={kernelName:bi,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,o=q(n.shape,r.shape),i=()=>{const s=v(e,C(r,"float32")),c=ae(n.shape,o);return c.length>0?y(U(s,c),n.shape):s},a=()=>{const s=v(e,C(n,"float32")),c=ae(r.shape,o);return c.length>0?y(U(s,c),r.shape):s};return{a:i,b:a}}};const Ag={kernelName:wi,gradFunc:e=>({x:()=>ne(e)})};const Ng={kernelName:yi,inputsToSave:["indices"],gradFunc:(e,t)=>{const n=t[0];return{indices:()=>Ce(n.shape,"float32")}}};const Rg={kernelName:xi,gradFunc:e=>({x:()=>W(e)})};const Xh={kernelName:Li,inputsToSave:["x"],gradFunc:(e,t,n)=>{const r=t[0],{paddings:o}=n,i=o.map(a=>a[0]);return{x:()=>G(e,i,r.shape)}}};const _g={kernelName:vi,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{const[n,r,o]=t,i=n,a=r,s=q(i.shape,a.shape),c=()=>{const l=C(a,"float32");let h=v(e,v(l,Je(i,O(l,_(1)))));const d=ae(i.shape,s);return d.length>0&&(h=U(h,d)),y(h,i.shape)},p=()=>{const l=tt(i,0),h=Oe(l,yt(i),W(i));let d=v(e,v(o,h));const b=ae(a.shape,s);return b.length>0&&(d=U(d,b)),y(d,a.shape)};return{a:c,b:p}}};const Cg={kernelName:Si,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{const[n,r]=t,o=tt(n,0);return{x:()=>Oe(o,e,v(e,r)),alpha:()=>{let i=Oe(o,W(e),v(e,n));const a=ae(r.shape,e.shape);return a.length>0&&(i=U(i,a)),y(i,r.shape)}}}};const Eg={kernelName:Ii,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>F(e,ne(H(n)))}}};const Og={kernelName:_i,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,r=v(ut(n,6),Dt(n));return{x:()=>v(e,C(r,"float32"))}}};const kg={kernelName:Ti,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(e,C(Dt(n),"float32"))}}};const Dg={kernelName:Ai,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>y(e,n.shape)}}};const Fg={kernelName:Ri,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[r]=t,o=s=>{const{alignCorners:c}=n;return s.resizeBilinearBackprop(e,r,c)},i={images:r},a=()=>g.runKernelFunc(o,i,null,yp,n);return{images:a}}};const Mg={kernelName:Ni,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[r]=t,o=s=>{const{alignCorners:c}=n;return s.resizeNearestNeighborBackprop(e,r,c)},i={images:r},a=()=>g.runKernelFunc(o,i,null,xp,n);return{images:a}}};const Ug={kernelName:Ci,gradFunc:(e,t,n)=>{const{dims:r}=n,o=z(r,e.shape);return{x:()=>Ve(e,o)}}};const Wg={kernelName:Ei,gradFunc:e=>({x:()=>W(e)})};const Bg={kernelName:Oi,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>ne(F(e,v(Je(n,1.5),2)))}}};const $g={kernelName:ki,inputsToSave:["condition"],gradFunc:(e,t)=>{const[n]=t;return{condition:()=>C(W(n),"float32"),t:()=>v(e,C(n,e.dtype)),e:()=>v(e,C(zn(n),e.dtype))}}};const jg={kernelName:Di,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const r=tt(n,_(0)),o=_(Vh),i=_(Kh),a=v(e,i),s=v(v(e,o),Se(C(n,"float32")));return Oe(r,a,s)}}}};const Gg={kernelName:Bi,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(e,v(n,O(_(1),n)))}}};const Pg={kernelName:Wi,gradFunc:e=>({x:()=>W(e)})};const qg={kernelName:Mi,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(jn(C(n,"float32")),e)}}};const Hg={kernelName:Ui,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(ms(C(n,"float32")),e)}}};const zg={kernelName:Fi,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{begin:o,size:i}=n,a=r.shape,[s,c]=ds(r,o,i),p=[];for(let l=0;lPe(e,p)}}};const Yg={kernelName:Hi,outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r]=t,{dim:o}=n,i=!0,a=v(e,r);return{logits:()=>O(a,v(U(a,[o],i),r))}}};const Vg={kernelName:$i,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(e,lt(n))}}};const Zh={kernelName:Pi,gradFunc:(e,t,n)=>{const{blockShape:r,paddings:o}=n;return{x:()=>Bn(e,r,o)}}};const Qh={kernelName:qi,gradFunc:(e,t,n)=>{const{axis:r}=n;return{x:()=>Z(e,r)}}};const Kg={kernelName:ji,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>F(e,v(me(C(n,"float32")),2))}}};const Jg={kernelName:vp,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(e,v(C(n,"float32"),2))}}};const Xg={kernelName:zi,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,o=_(2),i=()=>v(e,v(o,O(n,r))),a=()=>v(e,v(o,O(r,n)));return{a:i,b:a}}};const Zg={kernelName:ts,gradFunc:e=>({x:()=>W(e)})};const Qg={kernelName:Yi,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,o=q(n.shape,r.shape),i=()=>{let s=e;const c=ae(n.shape,o);return c.length>0&&(s=U(s,c)),y(s,n.shape)},a=()=>{let s=e;const c=ae(r.shape,o);return c.length>0&&(s=U(s,c)),y(ne(s),r.shape)};return{a:i,b:a}}};const eb={kernelName:Gi,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,o=r.shape.slice(),{axis:i}=n,a=z(i,r.shape);a.forEach(p=>{o[p]=1});const s=y(e,o),c=v(s,vt(r.shape,"float32"));return{x:()=>c}}};const tb={kernelName:Vi,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>F(e,H(jn(n)))}}};const nb={kernelName:Ki,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(O(_(1),H(n)),e)}}};const rb={kernelName:Ji,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{reps:o}=n,i=()=>{let a=W(r);if(r.rank===1)for(let s=0;s{const r=n,{perm:o}=r,i=Un(o);return{x:()=>K(e,i)}}};const ib={kernelName:Zi,gradFunc:(e,t,n)=>{const r=n,{axis:o}=r;return{value:()=>ke(e,o)}}};const sb={kernelName:Qi,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{const[n]=t,r=()=>oT(e,n);return{x:r}}};function oT(e,t){const n=kt(t,W(t)),r=qn(e,n);let o=ht(t,_(0,"int32"));const i=r.rank-o.rank;for(let s=0;s({x:()=>W(e)})};const iT=[wf,xf,yf,Lf,vf,Sf,If,Tf,Af,Nf,Rf,_f,Ef,kf,Df,Ff,Mf,Uf,Wf,Bf,$f,Gf,jf,qf,Hf,zf,Yf,Vf,Kf,Jf,Xf,Zf,Qf,eg,ng,tg,rg,sg,ag,cg,pg,lg,hg,ug,dg,mg,gg,Jh,Jh,bg,xg,Lg,vg,Sg,Ig,Tg,Ag,Ng,Rg,Xh,Xh,_g,Cg,Eg,Og,kg,Dg,Fg,Mg,Ug,Wg,Bg,$g,jg,Gg,Pg,qg,Hg,zg,Yg,Vg,Zh,Zh,Qh,Qh,Kg,Xg,Jg,Zg,Qg,eb,tb,nb,rb,ob,ib,sb,ab];for(const e of iT)Rp(e);const Vs={};Re(Vs,{Abs:()=>xo,Acos:()=>yo,Acosh:()=>Lo,AdadeltaOptimizer:()=>sr,AdagradOptimizer:()=>ar,AdamOptimizer:()=>cr,AdamaxOptimizer:()=>pr,Add:()=>kn,AddN:()=>vo,All:()=>Oc,Any:()=>kc,ArgMax:()=>So,ArgMin:()=>Io,Asin:()=>To,Asinh:()=>Ao,Atan:()=>No,Atan2:()=>_o,Atanh:()=>Ro,AvgPool:()=>Co,AvgPool3D:()=>Eo,AvgPool3DBackprop:()=>Fc,AvgPoolBackprop:()=>Dc,BatchMatMul:()=>Oo,BatchToSpaceND:()=>ko,BroadcastTo:()=>Do,Cast:()=>Dn,Ceil:()=>Fo,ClipByValue:()=>Mo,Complex:()=>Mc,Concat:()=>Uo,Conv2D:()=>Wo,Conv2DBackpropFilter:()=>Uc,Conv2DBackpropInput:()=>Bo,Conv3D:()=>$o,Conv3DBackpropFilterV2:()=>Wc,Conv3DBackpropInputV2:()=>Bc,Cos:()=>jo,Cosh:()=>Go,CropAndResize:()=>$c,Cumsum:()=>Po,DataStorage:()=>JI,DepthToSpace:()=>jc,DepthwiseConv2dNative:()=>qo,DepthwiseConv2dNativeBackpropFilter:()=>Gc,DepthwiseConv2dNativeBackpropInput:()=>Pc,Diag:()=>qc,Dilation2D:()=>Ho,Dilation2DBackpropFilter:()=>zc,Dilation2DBackpropInput:()=>Hc,Div:()=>zo,ENV:()=>Rc,Elu:()=>Yo,EluGrad:()=>Yc,Environment:()=>Nc,Equal:()=>Vc,Erf:()=>Vo,Exp:()=>Ko,Expm1:()=>Jo,FFT:()=>Kc,Fill:()=>Jc,FlipLeftRight:()=>Xc,Floor:()=>Xo,FloorDiv:()=>Zo,FromPixels:()=>va,FusedBatchNorm:()=>Qo,FusedConv2D:()=>Ia,FusedDepthwiseConv2D:()=>Ta,GatherNd:()=>Zc,GatherV2:()=>ei,Greater:()=>Qc,GreaterEqual:()=>ti,IFFT:()=>ep,Identity:()=>ni,Imag:()=>tp,IsFinite:()=>ri,IsInf:()=>oi,IsNan:()=>ii,KernelBackend:()=>XI,LRN:()=>pi,LRNBackprop:()=>cp,Less:()=>np,LessEqual:()=>rp,LinSpace:()=>op,Log:()=>si,Log1p:()=>ai,LogSoftmax:()=>ci,LogicalAnd:()=>ip,LogicalNot:()=>sp,LogicalOr:()=>ap,Max:()=>li,MaxPool:()=>ui,MaxPool3D:()=>di,MaxPool3DBackprop:()=>lp,MaxPoolBackprop:()=>pp,MaxPoolWithArgmax:()=>hp,Maximum:()=>hi,Mean:()=>pw,Min:()=>mi,Minimum:()=>fi,Mod:()=>gi,MomentumOptimizer:()=>lr,Multiply:()=>bi,Negate:()=>wi,NonMaxSuppressionV3:()=>dp,NonMaxSuppressionV4:()=>mp,NonMaxSuppressionV5:()=>fp,NotEqual:()=>up,OneHot:()=>yi,OnesLike:()=>xi,Optimizer:()=>ot,PadV2:()=>Li,Pool:()=>lw,Pow:()=>vi,Prelu:()=>Si,Prod:()=>gp,RMSPropOptimizer:()=>hr,Range:()=>bp,Rank:()=>Wp,Real:()=>wp,Reciprocal:()=>Ii,Reduction:()=>be,Relu:()=>Ti,Relu6:()=>_i,Reshape:()=>Ai,ResizeBilinear:()=>Ri,ResizeBilinearGrad:()=>yp,ResizeNearestNeighbor:()=>Ni,ResizeNearestNeighborGrad:()=>xp,Reverse:()=>Ci,RotateWithOffset:()=>Ap,Round:()=>Ei,Rsqrt:()=>Oi,SGDOptimizer:()=>on,ScatterNd:()=>Lp,SelectV2:()=>ki,Selu:()=>Di,Sigmoid:()=>Bi,Sign:()=>Wi,Sin:()=>Mi,Sinh:()=>Ui,Slice:()=>Fi,Softmax:()=>Hi,Softplus:()=>$i,SpaceToBatchND:()=>Pi,SparseToDense:()=>Sp,SplitV:()=>qi,Sqrt:()=>ji,Square:()=>vp,SquaredDifference:()=>zi,Step:()=>ts,StridedSlice:()=>Ip,Sub:()=>Yi,Sum:()=>Gi,Tan:()=>Vi,Tanh:()=>Ki,Tensor:()=>ee,TensorBuffer:()=>Dr,Tile:()=>Ji,TopK:()=>Tp,Transpose:()=>Xi,Unpack:()=>Zi,UnsortedSegmentSum:()=>Qi,Variable:()=>Ht,ZerosLike:()=>es,_FusedMatMul:()=>Sa,abs:()=>Ee,acos:()=>Hp,acosh:()=>zp,add:()=>R,addN:()=>Yp,addStrict:()=>nm,all:()=>Jp,any:()=>Xp,argMax:()=>Zp,argMin:()=>Qp,asin:()=>el,asinh:()=>tl,atan:()=>nl,atan2:()=>rl,atanh:()=>ol,avgPool:()=>pt,avgPool3d:()=>cl,backend:()=>Ax,backend_util:()=>df,basicLSTMCell:()=>xl,batchNorm:()=>Ct,batchNorm2d:()=>yl,batchNorm3d:()=>Ll,batchNorm4d:()=>vl,batchToSpaceND:()=>Bn,booleanMaskAsync:()=>Kd,broadcastTo:()=>Br,browser:()=>Kr,buffer:()=>Be,cast:()=>C,ceil:()=>Sl,clipByValue:()=>$n,clone:()=>Et,complex:()=>Ye,concat:()=>Z,concat1d:()=>Il,concat2d:()=>Tl,concat3d:()=>Al,concat4d:()=>Nl,conv1d:()=>Rl,conv2d:()=>xe,conv2dTranspose:()=>_l,conv3d:()=>Cl,conv3dTranspose:()=>El,cos:()=>jn,cosh:()=>ms,cosineWindow:()=>qr,cumsum:()=>fs,customGrad:()=>Ke,deprecationWarn:()=>Le,depthToSpace:()=>Ol,depthwiseConv2d:()=>en,device_util:()=>Md,diag:()=>kl,dilation2d:()=>Dl,disableDeprecationWarnings:()=>dx,dispose:()=>ve,disposeVariables:()=>mx,div:()=>F,divNoNan:()=>Fl,divStrict:()=>rm,dot:()=>Ml,dropout:()=>ym,elu:()=>bs,enableDebugMode:()=>ux,enableProdMode:()=>hx,enclosingPowerOfTwo:()=>$a,engine:()=>fx,env:()=>pe,equal:()=>tn,equalStrict:()=>Jd,erf:()=>Ul,exp:()=>Se,expandDims:()=>et,expm1:()=>Wl,eye:()=>ws,fft:()=>Gn,fill:()=>Ge,findBackend:()=>Sx,findBackendFactory:()=>Ix,floor:()=>Pn,floorDiv:()=>gs,fused:()=>Mh,gather:()=>qn,gatherND:()=>wm,gather_util:()=>lf,getBackend:()=>Lx,getGradient:()=>Aa,getKernel:()=>rs,getKernelsForBackend:()=>Na,grad:()=>Jy,grads:()=>Xy,greater:()=>tt,greaterEqual:()=>ht,greaterEqualStrict:()=>Xd,greaterStrict:()=>Zd,ifft:()=>vn,imag:()=>nn,image:()=>Va,inTopKAsync:()=>Lm,io:()=>Vr,irfft:()=>xs,isFinite:()=>$l,isInf:()=>jl,isNaN:()=>Gl,keep:()=>al,kernel_impls:()=>bf,leakyRelu:()=>Pl,less:()=>Hn,lessEqual:()=>ut,lessEqualStrict:()=>Qd,lessStrict:()=>em,linalg:()=>Xm,linspace:()=>ql,localResponseNormalization:()=>Hl,log:()=>yt,log1p:()=>ys,logSigmoid:()=>Yl,logSoftmax:()=>Vl,logSumExp:()=>vs,logicalAnd:()=>Lt,logicalNot:()=>zn,logicalOr:()=>Ss,logicalXor:()=>Kl,losses:()=>Zm,matMul:()=>Y,math:()=>pf,max:()=>dt,maxPool:()=>Ae,maxPool3d:()=>Jl,maxPoolWithArgmax:()=>Xl,maximum:()=>kt,maximumStrict:()=>om,mean:()=>Sn,memory:()=>gx,min:()=>In,minimum:()=>Yn,minimumStrict:()=>im,mod:()=>Is,modStrict:()=>sm,moments:()=>Zl,movingAverage:()=>um,mul:()=>v,mulStrict:()=>am,multiRNNCell:()=>Ql,multinomial:()=>eh,neg:()=>ne,nextFrame:()=>vI,norm:()=>Pr,notEqual:()=>Vn,notEqualStrict:()=>tm,oneHot:()=>jr,ones:()=>vt,onesLike:()=>Ma,op:()=>m,outerProduct:()=>th,pad:()=>Pe,pad1d:()=>nh,pad2d:()=>rh,pad3d:()=>oh,pad4d:()=>ih,pool:()=>sh,pow:()=>Je,powStrict:()=>cm,prelu:()=>Ts,print:()=>ah,prod:()=>ch,profile:()=>bx,rand:()=>ph,randomGamma:()=>dh,randomNormal:()=>mh,randomUniform:()=>Ns,range:()=>Gr,ready:()=>yx,real:()=>zt,reciprocal:()=>fh,registerBackend:()=>Tx,registerGradient:()=>Rp,registerKernel:()=>hw,relu:()=>ie,relu6:()=>Rs,removeBackend:()=>vx,reshape:()=>y,reverse:()=>Ve,reverse1d:()=>gh,reverse2d:()=>bh,reverse3d:()=>wh,reverse4d:()=>xh,rfft:()=>Jn,round:()=>Lh,rsqrt:()=>_s,scalar:()=>_,scatterND:()=>fm,scatter_util:()=>dm,selu:()=>vh,separableConv2d:()=>Xn,serialization:()=>uf,setBackend:()=>xx,setPlatform:()=>Nx,setdiff1dAsync:()=>Sh,sigmoid:()=>lt,sign:()=>Ih,signal:()=>Jm,sin:()=>Cs,sinh:()=>Es,slice:()=>G,slice1d:()=>Th,slice2d:()=>Ah,slice3d:()=>Os,slice4d:()=>Nh,slice_util:()=>$d,softmax:()=>rn,softplus:()=>Ls,spaceToBatchND:()=>Kn,sparseToDense:()=>bm,spectral:()=>Km,split:()=>Yt,sqrt:()=>me,square:()=>H,squaredDifference:()=>Zn,squaredDifferenceStrict:()=>pm,squeeze:()=>Qn,stack:()=>ke,step:()=>Dt,stridedSlice:()=>Rh,sub:()=>O,subStrict:()=>lm,sum:()=>U,sumOutType:()=>kw,tan:()=>_h,tanh:()=>Wr,tensor:()=>ze,tensor1d:()=>ce,tensor2d:()=>mt,tensor3d:()=>er,tensor4d:()=>ft,tensor5d:()=>Ch,tensor6d:()=>Eh,tensor_util:()=>kd,test_util:()=>Hd,tidy:()=>k,tile:()=>Ot,time:()=>wx,topk:()=>Oh,train:()=>yI,transpose:()=>K,truncatedNormal:()=>kh,unregisterGradient:()=>dw,unregisterKernel:()=>uw,unsortedSegmentSum:()=>ks,unstack:()=>Ie,upcastType:()=>Mr,util:()=>wd,valueAndGrad:()=>Zy,valueAndGrads:()=>Qy,variable:()=>Dh,variableGrads:()=>zl,version_core:()=>xI,where:()=>Oe,whereAsync:()=>Ds,zeros:()=>Ce,zerosLike:()=>W});function sn(e,t,n=!1){if(e.beginPath(),t.slice(1).forEach(({x:r,y:o},i)=>{const a=t[i];e.moveTo(a.x,a.y),e.lineTo(r,o)}),n){const r=t[t.length-1],o=t[0];if(!r||!o)return;e.moveTo(r.x,r.y),e.lineTo(o.x,o.y)}e.stroke()}class Qe{constructor(e,t){if(!Mt(e)||!Mt(t))throw new Error(`Dimensions.constructor - expected width and height to be valid numbers, instead have ${JSON.stringify({width:e,height:t})}`);this._width=e,this._height=t}get width(){return this._width}get height(){return this._height}reverse(){return new Qe(1/this.width,1/this.height)}}const Js={};Re(Js,{computeReshapedDimensions:()=>nu,getCenterPoint:()=>mr,isDimensions:()=>Qa,isEven:()=>Za,isFloat:()=>tu,isTensor:()=>ur,isTensor1D:()=>sT,isTensor2D:()=>eu,isTensor3D:()=>an,isTensor4D:()=>gt,isValidNumber:()=>Mt,isValidProbablitiy:()=>Xr,range:()=>Vt,round:()=>dr});function ur(e,t){return e instanceof ee&&e.shape.length===t}function sT(e){return ur(e,1)}function eu(e){return ur(e,2)}function an(e){return ur(e,3)}function gt(e){return ur(e,4)}function tu(e){return e%1!==0}function Za(e){return e%2===0}function dr(e,t=2){const n=Math.pow(10,t);return Math.floor(e*n)/n}function Qa(e){return e&&e.width&&e.height}function nu({width:e,height:t},n){const r=n/Math.max(t,e);return new Qe(Math.round(e*r),Math.round(t*r))}function mr(e){return e.reduce((t,n)=>t.add(n),new J(0,0)).div(new J(e.length,e.length))}function Vt(e,t,n){return Array(e).fill(0).map((r,o)=>t+o*n)}function Mt(e){return!!e&&e!==Infinity&&e!==-Infinity&&!isNaN(e)||e===0}function Xr(e){return Mt(e)&&0<=e&&e<=1}class J{constructor(e,t){this._x=e,this._y=t}get x(){return this._x}get y(){return this._y}add(e){return new J(this.x+e.x,this.y+e.y)}sub(e){return new J(this.x-e.x,this.y-e.y)}mul(e){return new J(this.x*e.x,this.y*e.y)}div(e){return new J(this.x/e.x,this.y/e.y)}abs(){return new J(Math.abs(this.x),Math.abs(this.y))}magnitude(){return Math.sqrt(Math.pow(this.x,2)+Math.pow(this.y,2))}floor(){return new J(Math.floor(this.x),Math.floor(this.y))}}class de{constructor(e,t=!0){const n=e||{},r=[n.left,n.top,n.right,n.bottom].every(Mt),o=[n.x,n.y,n.width,n.height].every(Mt);if(!o&&!r)throw new Error(`Box.constructor - expected box to be IBoundingBox | IRect, instead have ${JSON.stringify(n)}`);const[i,a,s,c]=o?[n.x,n.y,n.width,n.height]:[n.left,n.top,n.right-n.left,n.bottom-n.top];de.assertIsValidBox({x:i,y:a,width:s,height:c},"Box.constructor",t),this._x=i,this._y=a,this._width=s,this._height=c}static isRect(e){return!!e&&[e.x,e.y,e.width,e.height].every(Mt)}static assertIsValidBox(e,t,n=!1){if(!de.isRect(e))throw new Error(`${t} - invalid box: ${JSON.stringify(e)}, expected object with properties x, y, width, height`);if(!n&&(e.width<0||e.height<0))throw new Error(`${t} - width (${e.width}) and height (${e.height}) must be positive numbers`)}get x(){return this._x}get y(){return this._y}get width(){return this._width}get height(){return this._height}get left(){return this.x}get top(){return this.y}get right(){return this.x+this.width}get bottom(){return this.y+this.height}get area(){return this.width*this.height}get topLeft(){return new J(this.left,this.top)}get topRight(){return new J(this.right,this.top)}get bottomLeft(){return new J(this.left,this.bottom)}get bottomRight(){return new J(this.right,this.bottom)}round(){const[e,t,n,r]=[this.x,this.y,this.width,this.height].map(o=>Math.round(o));return new de({x:e,y:t,width:n,height:r})}floor(){const[e,t,n,r]=[this.x,this.y,this.width,this.height].map(o=>Math.floor(o));return new de({x:e,y:t,width:n,height:r})}toSquare(){let{x:e,y:t,width:n,height:r}=this;const o=Math.abs(n-r);return nt&&(a=-l+t+n,l=t),h>e&&(s=-h+e+r,h=e),c<1&&(s=2-c,c=1),p<1&&(s=2-p,p=1),{dy:i,edy:s,dx:o,edx:a,y:p,ey:h,x:c,ex:l,w:n,h:r}}calibrate(e){return new de({left:this.left+e.left*this.width,top:this.top+e.top*this.height,right:this.right+e.right*this.width,bottom:this.bottom+e.bottom*this.height}).toSquare().round()}}class Rr extends de{constructor(e,t,n,r,o=!1){super({left:e,top:t,right:n,bottom:r},o)}}class On{constructor(e,t,n,r,o){this._imageDims=new Qe(o.width,o.height),this._score=e,this._classScore=t,this._className=n,this._box=new de(r).rescale(this._imageDims)}get score(){return this._score}get classScore(){return this._classScore}get className(){return this._className}get box(){return this._box}get imageDims(){return this._imageDims}get imageWidth(){return this.imageDims.width}get imageHeight(){return this.imageDims.height}get relativeBox(){return new de(this._box).rescale(this.imageDims.reverse())}forSize(e,t){return new On(this.score,this.classScore,this.className,this.relativeBox,{width:e,height:t})}}class fe extends On{constructor(e,t,n){super(e,e,"",t,n)}forSize(e,t){const{score:n,relativeBox:r,imageDims:o}=super.forSize(e,t);return new fe(n,r,o)}}function ra(e,t,n=!0){const r=Math.max(0,Math.min(e.right,t.right)-Math.max(e.left,t.left)),o=Math.max(0,Math.min(e.bottom,t.bottom)-Math.max(e.top,t.top)),i=r*o;return n?i/(e.area+t.area-i):i/Math.min(e.area,t.area)}function na(e){const t=e.map(s=>s.x),n=e.map(s=>s.y),r=t.reduce((s,c)=>ccss({score:a,boxIndex:s})).sort((a,s)=>a.score-s.score).map(a=>a.boxIndex);const i=[];for(;o.length>0;){const a=o.pop();i.push(a);const s=o,c=[];for(let p=0;pc[l]<=n)}return i}function wt(e,t){return k(()=>{const[n,r,o]=t,i=Ge([...e.shape.slice(0,3),1],n),a=Ge([...e.shape.slice(0,3),1],r),s=Ge([...e.shape.slice(0,3),1],o),c=Z([i,a,s],3);return O(e,c)})}function ea(e,t=!1){return k(()=>{const[n,r]=e.shape.slice(1);if(n===r)return e;const o=Math.abs(n-r),i=Math.round(o*(t?.5:1)),a=n>r?2:1,s=d=>{const b=e.shape.slice();return b[a]=d,Ge(b,0)},c=s(i),p=o-c.shape[a],l=t&&p?s(p):null,h=[l,e,c].filter(d=>!!d).map(d=>d.toFloat());return Z(h,a)})}function Bu(e){const t=e.slice();for(let n=t.length-1;n>0;n--){const r=Math.floor(Math.random()*(n+1)),o=t[n];t[n]=t[r],t[r]=o}return t}function Lr(e){return 1/(1+Math.exp(-e))}function $u(e){return Math.log(e/(1-e))}class Ar extends de{constructor(e,t,n,r,o=!1){super({x:e,y:t,width:n,height:r},o)}}const aT=.5,cT=.43,pT=.45;class st{constructor(e,t,n=new J(0,0)){const{width:r,height:o}=t;this._imgDims=new Qe(r,o),this._shift=n,this._positions=e.map(i=>i.mul(new J(r,o)).add(n))}get shift(){return new J(this._shift.x,this._shift.y)}get imageWidth(){return this._imgDims.width}get imageHeight(){return this._imgDims.height}get positions(){return this._positions}get relativePositions(){return this._positions.map(e=>e.sub(this._shift).div(new J(this.imageWidth,this.imageHeight)))}forSize(e,t){return new this.constructor(this.relativePositions,{width:e,height:t})}shiftBy(e,t){return new this.constructor(this.relativePositions,this._imgDims,new J(e,t))}shiftByPoint(e){return this.shiftBy(e.x,e.y)}align(e,t={}){if(e){const o=e instanceof fe?e.box.floor():new de(e);return this.shiftBy(o.x,o.y).align(null,t)}const{useDlibAlignment:n,minBoxPadding:r}=Object.assign({},{useDlibAlignment:!1,minBoxPadding:.2},t);return n?this.alignDlib():this.alignMinBbox(r)}alignDlib(){const e=this.getRefPointsForAlignment(),[t,n,r]=e,o=l=>r.sub(l).magnitude(),i=(o(t)+o(n))/2,a=Math.floor(i/pT),s=mr(e),c=Math.floor(Math.max(0,s.x-aT*a)),p=Math.floor(Math.max(0,s.y-cT*a));return new Ar(c,p,Math.min(a,this.imageWidth+c),Math.min(a,this.imageHeight+p))}alignMinBbox(e){const t=na(this.positions);return t.pad(t.width*e,t.height*e)}getRefPointsForAlignment(){throw new Error("getRefPointsForAlignment not implemented by base class")}}class md extends st{getRefPointsForAlignment(){const e=this.positions;return[e[0],e[1],mr([e[3],e[4]])]}}class Nr extends st{getJawOutline(){return this.positions.slice(0,17)}getLeftEyeBrow(){return this.positions.slice(17,22)}getRightEyeBrow(){return this.positions.slice(22,27)}getNose(){return this.positions.slice(27,36)}getLeftEye(){return this.positions.slice(36,42)}getRightEye(){return this.positions.slice(42,48)}getMouth(){return this.positions.slice(48,68)}getRefPointsForAlignment(){return[this.getLeftEye(),this.getRightEye(),this.getMouth()].map(mr)}}class wo{constructor(e,t){this._label=e,this._distance=t}get label(){return this._label}get distance(){return this._distance}toString(e=!0){return`${this.label}${e?` (${dr(this.distance)})`:""}`}}class bo extends de{constructor(e,t){super(e);this._label=t}static assertIsValidLabeledBox(e,t){if(de.assertIsValidBox(e,t),!Mt(e.label))throw new Error(`${t} - expected property label (${e.label}) to be a number`)}get label(){return this._label}}class xn{constructor(e,t){if(!(typeof e=="string"))throw new Error("LabeledFaceDescriptors - constructor expected label to be a string");if(!Array.isArray(t)||t.some(n=>!(n instanceof Float32Array)))throw new Error("LabeledFaceDescriptors - constructor expected descriptors to be an array of Float32Array");this._label=e,this._descriptors=t}get label(){return this._label}get descriptors(){return this._descriptors}toJSON(){return{label:this.label,descriptors:this.descriptors.map(e=>Array.from(e))}}static fromJSON(e){const t=e.descriptors.map(n=>new Float32Array(n));return new xn(e.label,t)}}class dd extends bo{constructor(e,t,n,r){super(e,t);this._score=n,this._classScore=r}static assertIsValidPredictedBox(e,t){if(bo.assertIsValidLabeledBox(e,t),!Xr(e.score)||!Xr(e.classScore))throw new Error(`${t} - expected properties score (${e.score}) and (${e.classScore}) to be a number between [0, 1]`)}get score(){return this._score}get classScore(){return this._classScore}}function Nt(e){return e.detection instanceof fe}function mn(e,t){const n={detection:t};return Object.assign({},e,n)}function ru(){const e=window.fetch||function(){throw new Error("fetch - missing fetch implementation for browser environment")},t=function(){throw new Error("readFile - filesystem not available for browser environment")};return{Canvas:HTMLCanvasElement,CanvasRenderingContext2D,Image:HTMLImageElement,ImageData,Video:HTMLVideoElement,createCanvasElement:()=>document.createElement("canvas"),createImageElement:()=>document.createElement("img"),fetch:e,readFile:t}}function ec(e){let t="";if(!e)try{e=require("fs")}catch(r){t=r.toString()}const n=e?function(r){return new Promise((o,i)=>{e.readFile(r,function(a,s){return a?i(a):o(s)})})}:function(){throw new Error(`readFile - failed to require fs in nodejs environment with error: ${t}`)};return{readFile:n}}function ou(){const e=global.Canvas||global.HTMLCanvasElement,t=global.Image||global.HTMLImageElement,n=function(){if(e)return new e();throw new Error("createCanvasElement - missing Canvas implementation for nodejs environment")},r=function(){if(t)return new t();throw new Error("createImageElement - missing Image implementation for nodejs environment")},o=global.fetch||function(){throw new Error("fetch - missing fetch implementation for nodejs environment")},i=ec();return zs({Canvas:e||class{},CanvasRenderingContext2D:global.CanvasRenderingContext2D||class{},Image:t||class{},ImageData:global.ImageData||class{},Video:global.HTMLVideoElement||class{},createCanvasElement:n,createImageElement:r,fetch:o},i)}function iu(){return typeof window=="object"&&typeof document!="undefined"&&typeof HTMLImageElement!="undefined"&&typeof HTMLCanvasElement!="undefined"&&typeof HTMLVideoElement!="undefined"&&typeof ImageData!="undefined"&&typeof CanvasRenderingContext2D!="undefined"}const su=fu(ku());let Fe;function lT(){if(!Fe)throw new Error("getEnv - environment is not defined, check isNodejs() and isBrowser()");return Fe}function au(e){Fe=e}function cu(){if(iu())return au(ru());if(su.isNodejs())return au(ou())}function hT(e){if(Fe||cu(),!Fe)throw new Error("monkeyPatch - environment is not defined, check isNodejs() and isBrowser()");const{Canvas:t=Fe.Canvas,Image:n=Fe.Image}=e;Fe.Canvas=t,Fe.Image=n,Fe.createCanvasElement=e.createCanvasElement||(()=>new t()),Fe.createImageElement=e.createImageElement||(()=>new n()),Fe.ImageData=e.ImageData||Fe.ImageData,Fe.Video=e.Video||Fe.Video,Fe.fetch=e.fetch||Fe.fetch,Fe.readFile=e.readFile||Fe.readFile}const se={getEnv:lT,setEnv:au,initialize:cu,createBrowserEnv:ru,createFileSystem:ec,createNodejsEnv:ou,monkeyPatch:hT,isBrowser:iu,isNodejs:su.isNodejs};cu();function gn(e){return!se.isNodejs()&&typeof e=="string"?document.getElementById(e):e}function qe(e){const{Canvas:t,CanvasRenderingContext2D:n}=se.getEnv();if(e instanceof n)return e;const r=gn(e);if(!(r instanceof t))throw new Error("resolveContext2d - expected canvas to be of instance of Canvas");const o=r.getContext("2d");if(!o)throw new Error("resolveContext2d - canvas 2d context is null");return o}var Kt;(function(e){e.TOP_LEFT="TOP_LEFT",e.TOP_RIGHT="TOP_RIGHT",e.BOTTOM_LEFT="BOTTOM_LEFT",e.BOTTOM_RIGHT="BOTTOM_RIGHT"})(Kt||(Kt={}));class tc{constructor(e={}){const{anchorPosition:t,backgroundColor:n,fontColor:r,fontSize:o,fontStyle:i,padding:a}=e;this.anchorPosition=t||Kt.TOP_LEFT,this.backgroundColor=n||"rgba(0, 0, 0, 0.5)",this.fontColor=r||"rgba(255, 255, 255, 1)",this.fontSize=o||14,this.fontStyle=i||"Georgia",this.padding=a||4}}class Zr{constructor(e,t,n={}){this.text=typeof e=="string"?[e]:e instanceof Zr?e.text:e,this.anchor=t,this.options=new tc(n)}measureWidth(e){const{padding:t}=this.options;return this.text.map(n=>e.measureText(n).width).reduce((n,r)=>n{const b=s+l.x,x=s+l.y+(d+1)*i;n.fillText(h,b,x)})}}class cb{constructor(e={}){const{boxColor:t,lineWidth:n,label:r,drawLabelOptions:o}=e;this.boxColor=t||"rgba(0, 0, 255, 1)",this.lineWidth=n||2,this.label=r;const i={anchorPosition:Kt.BOTTOM_LEFT,backgroundColor:this.boxColor};this.drawLabelOptions=new tc(Object.assign({},i,o))}}class pu{constructor(e,t={}){this.box=new de(e),this.options=new cb(t)}draw(e){const t=qe(e),{boxColor:n,lineWidth:r}=this.options,{x:o,y:i,width:a,height:s}=this.box;t.strokeStyle=n,t.lineWidth=r,t.strokeRect(o,i,a,s);const{label:c}=this.options;c&&new Zr([c],{x:o-r/2,y:i},this.options.drawLabelOptions).draw(e)}}function uT(e,t){const n=Array.isArray(t)?t:[t];n.forEach(r=>{const o=r instanceof fe?r.score:Nt(r)?r.detection.score:void 0,i=r instanceof fe?r.box:Nt(r)?r.detection.box:new de(r),a=o?`${dr(o)}`:void 0;new pu(i,{label:a}).draw(e)})}function Ir(e){const{Image:t,Video:n}=se.getEnv();return e instanceof t&&e.complete||e instanceof n&&e.readyState>=3}function ya(e){return new Promise((t,n)=>{if(e instanceof se.getEnv().Canvas||Ir(e))return t();function r(i){if(!i.currentTarget)return;i.currentTarget.removeEventListener("load",r),i.currentTarget.removeEventListener("error",o),t(i)}function o(i){if(!i.currentTarget)return;i.currentTarget.removeEventListener("load",r),i.currentTarget.removeEventListener("error",o),n(i)}e.addEventListener("load",r),e.addEventListener("error",o)})}function xa(e){return new Promise((t,n)=>{if(!(e instanceof Blob))return n("bufferToImage - expected buf to be of type: Blob");const r=new FileReader();r.onload=()=>{if(typeof r.result!="string")return n("bufferToImage - expected reader.result to be a string, in onload");const o=se.getEnv().createImageElement();o.onload=()=>t(o),o.onerror=n,o.src=r.result},r.onerror=n,r.readAsDataURL(e)})}function bn(e){const{Image:t,Video:n}=se.getEnv();return e instanceof t?new Qe(e.naturalWidth,e.naturalHeight):e instanceof n?new Qe(e.videoWidth,e.videoHeight):new Qe(e.width,e.height)}function En({width:e,height:t}){const{createCanvasElement:n}=se.getEnv(),r=n();return r.width=e,r.height=t,r}function Tr(e,t){const{ImageData:n}=se.getEnv();if(!(e instanceof n)&&!Ir(e))throw new Error("createCanvasFromMedia - media has not finished loading yet");const{width:r,height:o}=t||bn(e),i=En({width:r,height:o});return e instanceof n?qe(i).putImageData(e,0,0):qe(i).drawImage(e,0,0,r,o),i}async function ba(e,t){const n=t||se.getEnv().createCanvasElement(),[r,o,i]=e.shape.slice(gt(e)?1:0),a=k(()=>e.as3D(r,o,i).toInt());return await Kr.toPixels(a,n),a.dispose(),n}function go(e){const{Image:t,Canvas:n,Video:r}=se.getEnv();return e instanceof t||e instanceof n||e instanceof r}function ga(e,t,n=!1){const{Image:r,Canvas:o}=se.getEnv();if(!(e instanceof r||e instanceof o))throw new Error("imageToSquare - expected arg0 to be HTMLImageElement | HTMLCanvasElement");const i=bn(e),a=t/Math.max(i.height,i.width),s=a*i.width,c=a*i.height,p=En({width:t,height:t}),l=e instanceof o?e:Tr(e),h=Math.abs(s-c)/2,d=n&&s{if(an(n)){this._imageTensors[r]=n,this._inputDimensions[r]=n.shape;return}if(gt(n)){const i=n.shape[0];if(i!==1)throw new Error(`NetInput - tf.Tensor4D with batchSize ${i} passed, but not supported in input array`);this._imageTensors[r]=n,this._inputDimensions[r]=n.shape.slice(1);return}const o=n instanceof se.getEnv().Canvas?n:Tr(n);this._canvases[r]=o,this._inputDimensions[r]=[o.height,o.width,3]})}get imageTensors(){return this._imageTensors}get canvases(){return this._canvases}get isBatchInput(){return this.batchSize>1||this._treatAsBatchInput}get batchSize(){return this._batchSize}get inputDimensions(){return this._inputDimensions}get inputSize(){return this._inputSize}get reshapedInputDimensions(){return Vt(this.batchSize,0,1).map((e,t)=>this.getReshapedInputDimensions(t))}getInput(e){return this.canvases[e]||this.imageTensors[e]}getInputDimensions(e){return this._inputDimensions[e]}getInputHeight(e){return this._inputDimensions[e][0]}getInputWidth(e){return this._inputDimensions[e][1]}getReshapedInputDimensions(e){if(typeof this.inputSize!="number")throw new Error("getReshapedInputDimensions - inputSize not set, toBatchTensor has not been called yet");const t=this.getInputWidth(e),n=this.getInputHeight(e);return nu({width:t,height:n},this.inputSize)}toBatchTensor(e,t=!0){return this._inputSize=e,k(()=>{const n=Vt(this.batchSize,0,1).map(o=>{const i=this.getInput(o);if(i instanceof ee){let a=gt(i)?i:i.expandDims();return a=ea(a,t),(a.shape[1]!==e||a.shape[2]!==e)&&(a=Va.resizeBilinear(a,[e,e])),a.as3D(e,e,3)}if(i instanceof se.getEnv().Canvas)return Kr.fromPixels(ga(i,e,t));throw new Error(`toBatchTensor - at batchIdx ${o}, expected input to be instanceof tf.Tensor or instanceof HTMLCanvasElement, instead have ${i}`)}),r=ke(n.map(o=>o.toFloat())).as4D(this.batchSize,e,e,3);return r})}}async function ue(e){if(e instanceof Jt)return e;let t=Array.isArray(e)?e:[e];if(!t.length)throw new Error("toNetInput - empty array passed as input");const n=o=>Array.isArray(e)?` at input index ${o}:`:"",r=t.map(gn);return r.forEach((o,i)=>{if(!go(o)&&!an(o)&&!gt(o))throw typeof t[i]=="string"?new Error(`toNetInput -${n(i)} string passed, but could not resolve HTMLElement for element id ${t[i]}`):new Error(`toNetInput -${n(i)} expected media to be of type HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | tf.Tensor3D, or to be an element id`);if(gt(o)){const a=o.shape[0];if(a!==1)throw new Error(`toNetInput -${n(i)} tf.Tensor4D with batchSize ${a} passed, but not supported in input array`)}}),await Promise.all(r.map(o=>go(o)&&ya(o))),new Jt(r,Array.isArray(e))}async function _n(e,t){const{Canvas:n}=se.getEnv();let r=e;if(!(e instanceof n)){const a=await ue(e);if(a.batchSize>1)throw new Error("extractFaces - batchSize > 1 not supported");const s=a.getInput(0);r=s instanceof n?s:await ba(s)}const o=qe(r),i=t.map(a=>a instanceof fe?a.forSize(r.width,r.height).box.floor():a).map(a=>a.clipAtImageBorders(r.width,r.height));return i.map(({x:a,y:s,width:c,height:p})=>{const l=En({width:c,height:p});return qe(l).putImageData(o.getImageData(a,s,c,p),0,0),l})}async function Cn(e,t){if(!an(e)&&!gt(e))throw new Error("extractFaceTensors - expected image tensor to be 3D or 4D");if(gt(e)&&e.shape[0]>1)throw new Error("extractFaceTensors - batchSize > 1 not supported");return k(()=>{const[n,r,o]=e.shape.slice(gt(e)?1:0),i=t.map(s=>s instanceof fe?s.forSize(r,n).box:s).map(s=>s.clipAtImageBorders(r,n)),a=i.map(({x:s,y:c,width:p,height:l})=>Os(e.as3D(n,r,o),[c,s,0],[l,p,o]));return a})}async function wn(e,t){const n=se.getEnv().fetch,r=await n(e,t);if(!(r.status<400))throw new Error(`failed to fetch: (${r.status}) ${r.statusText}, from url: ${r.url}`);return r}async function ud(e){const t=await wn(e),n=await t.blob();if(!n.type.startsWith("image/"))throw new Error(`fetchImage - expected blob type to be of type image/*, instead have: ${n.type}, for url: ${t.url}`);return xa(n)}async function wa(e){return(await wn(e)).json()}async function hd(e){return new Float32Array(await(await wn(e)).arrayBuffer())}function nc(e,t){const n=`${t}-weights_manifest.json`;if(!e)return{modelBaseUri:"",manifestUri:n};if(e==="/")return{modelBaseUri:"/",manifestUri:`/${n}`};const r=e.startsWith("http://")?"http://":e.startsWith("https://")?"https://":"";e=e.replace(r,"");const o=e.split("/").filter(s=>s),i=e.endsWith(".json")?o[o.length-1]:n;let a=r+(e.endsWith(".json")?o.slice(0,o.length-1):o).join("/");return a=e.startsWith("/")?`/${a}`:a,{modelBaseUri:a,manifestUri:a==="/"?`/${i}`:`${a}/${i}`}}async function fa(e,t){const{manifestUri:n,modelBaseUri:r}=nc(e,t);let o=await wa(n);return Vr.loadWeights(o,r)}function ld(e,t,n=!1){const{width:r,height:o}=n?bn(t):t;return e.width=r,e.height=o,{width:r,height:o}}class Ue{constructor(e){this._name=e,this._params=void 0,this._paramMappings=[]}get params(){return this._params}get paramMappings(){return this._paramMappings}get isLoaded(){return!!this.params}getParamFromPath(e){const{obj:t,objProp:n}=this.traversePropertyPath(e);return t[n]}reassignParamFromPath(e,t){const{obj:n,objProp:r}=this.traversePropertyPath(e);n[r].dispose(),n[r]=t}getParamList(){return this._paramMappings.map(({paramPath:e})=>({path:e,tensor:this.getParamFromPath(e)}))}getTrainableParams(){return this.getParamList().filter(e=>e.tensor instanceof Ht)}getFrozenParams(){return this.getParamList().filter(e=>!(e.tensor instanceof Ht))}variable(){this.getFrozenParams().forEach(({path:e,tensor:t})=>{this.reassignParamFromPath(e,t.variable())})}freeze(){this.getTrainableParams().forEach(({path:e,tensor:t})=>{const n=ze(t.dataSync());t.dispose(),this.reassignParamFromPath(e,n)})}dispose(e=!0){this.getParamList().forEach(t=>{if(e&&t.tensor.isDisposed)throw new Error(`param tensor has already been disposed for path ${t.path}`);t.tensor.dispose()}),this._params=void 0}serializeParams(){return new Float32Array(this.getParamList().map(({tensor:e})=>Array.from(e.dataSync())).reduce((e,t)=>e.concat(t)))}async load(e){if(e instanceof Float32Array){this.extractWeights(e);return}await this.loadFromUri(e)}async loadFromUri(e){if(e&&typeof e!="string")throw new Error(`${this._name}.loadFromUri - expected model uri`);const t=await fa(e,this.getDefaultModelName());this.loadFromWeightMap(t)}async loadFromDisk(e){if(e&&typeof e!="string")throw new Error(`${this._name}.loadFromDisk - expected model file path`);const{readFile:t}=se.getEnv(),{manifestUri:n,modelBaseUri:r}=nc(e,this.getDefaultModelName()),o=c=>Promise.all(c.map(p=>t(p).then(l=>l.buffer))),i=Vr.weightsLoaderFactory(o),a=JSON.parse((await t(n)).toString()),s=await i(a,r);this.loadFromWeightMap(s)}loadFromWeightMap(e){const{paramMappings:t,params:n}=this.extractParamsFromWeigthMap(e);this._paramMappings=t,this._params=n}extractWeights(e){const{paramMappings:t,params:n}=this.extractParams(e);this._paramMappings=t,this._params=n}traversePropertyPath(e){if(!this.params)throw new Error("traversePropertyPath - model has no loaded params");const t=e.split("/").reduce((o,i)=>{if(!o.nextObj.hasOwnProperty(i))throw new Error(`traversePropertyPath - object does not have property ${i}, for path ${e}`);return{obj:o.nextObj,objProp:i,nextObj:o.nextObj[i]}},{nextObj:this.params}),{obj:n,objProp:r}=t;if(!n||!r||!(n[r]instanceof ee))throw new Error(`traversePropertyPath - parameter is not a tensor, for path ${e}`);return{obj:n,objProp:r}}}function rt(e,t,n){return k(()=>{let r=Xn(e,t.depthwise_filter,t.pointwise_filter,n,"same");return r=R(r,t.bias),r})}function rc(e,t,n=!1){return k(()=>{const r=ie(n?R(xe(e,t.conv0.filters,[2,2],"same"),t.conv0.bias):rt(e,t.conv0,[2,2])),o=rt(r,t.conv1,[1,1]),i=ie(R(r,o)),a=rt(i,t.conv2,[1,1]);return ie(R(r,R(o,a)))})}function Ws(e,t,n=!1,r=!0){return k(()=>{const o=ie(n?R(xe(e,t.conv0.filters,r?[2,2]:[1,1],"same"),t.conv0.bias):rt(e,t.conv0,r?[2,2]:[1,1])),i=rt(o,t.conv1,[1,1]),a=ie(R(o,i)),s=rt(a,t.conv2,[1,1]),c=ie(R(o,R(i,s))),p=rt(c,t.conv3,[1,1]);return ie(R(o,R(i,R(s,p))))})}function fr(e,t,n="same",r=!1){return k(()=>{const o=R(xe(e,t.filters,[1,1],n),t.bias);return r?ie(o):o})}function Xe(e,t){Object.keys(e).forEach(n=>{t.some(r=>r.originalPath===n)||e[n].dispose()})}function Qr(e,t){return function(n,r,o,i){const a=ft(e(n*r*o*o),[o,o,n,r]),s=ce(e(r));return t.push({paramPath:`${i}/filters`},{paramPath:`${i}/bias`}),{filters:a,bias:s}}}function oc(e,t){return function(n,r,o){const i=mt(e(n*r),[n,r]),a=ce(e(r));return t.push({paramPath:`${o}/weights`},{paramPath:`${o}/bias`}),{weights:i,bias:a}}}class lu{constructor(e,t,n){this.depthwise_filter=e,this.pointwise_filter=t,this.bias=n}}function eo(e,t){return function(n,r,o){const i=ft(e(3*3*n),[3,3,n,1]),a=ft(e(n*r),[1,1,n,r]),s=ce(e(r));return t.push({paramPath:`${o}/depthwise_filter`},{paramPath:`${o}/pointwise_filter`},{paramPath:`${o}/bias`}),new lu(i,a,s)}}function to(e){return function(t){const n=e(`${t}/depthwise_filter`,4),r=e(`${t}/pointwise_filter`,4),o=e(`${t}/bias`,1);return new lu(n,r,o)}}function it(e,t){return function(n,r,o){const i=e[n];if(!ur(i,r))throw new Error(`expected weightMap[${n}] to be a Tensor${r}D, instead have ${i}`);return t.push({originalPath:n,paramPath:o||n}),i}}function Ze(e){let t=e;function n(o){const i=t.slice(0,o);return t=t.slice(o),i}function r(){return t}return{extractWeights:n,getRemainingWeights:r}}function ic(e,t){const n=Qr(e,t),r=eo(e,t);function o(a,s,c,p=!1){const l=p?n(a,s,3,`${c}/conv0`):r(a,s,`${c}/conv0`),h=r(s,s,`${c}/conv1`),d=r(s,s,`${c}/conv2`);return{conv0:l,conv1:h,conv2:d}}function i(a,s,c,p=!1){const{conv0:l,conv1:h,conv2:d}=o(a,s,c,p),b=r(s,s,`${c}/conv3`);return{conv0:l,conv1:h,conv2:d,conv3:b}}return{extractDenseBlock3Params:o,extractDenseBlock4Params:i}}function pb(e){const t=[],{extractWeights:n,getRemainingWeights:r}=Ze(e),{extractDenseBlock4Params:o}=ic(n,t),i=o(3,32,"dense0",!0),a=o(32,64,"dense1"),s=o(64,128,"dense2"),c=o(128,256,"dense3");if(r().length!==0)throw new Error(`weights remaing after extract: ${r().length}`);return{paramMappings:t,params:{dense0:i,dense1:a,dense2:s,dense3:c}}}function sc(e){return function(t){const n=e(`${t}/filters`,4),r=e(`${t}/bias`,1);return{filters:n,bias:r}}}function ac(e,t){const n=it(e,t),r=sc(n),o=to(n);function i(s,c=!1){const p=c?r(`${s}/conv0`):o(`${s}/conv0`),l=o(`${s}/conv1`),h=o(`${s}/conv2`);return{conv0:p,conv1:l,conv2:h}}function a(s,c=!1){const p=c?r(`${s}/conv0`):o(`${s}/conv0`),l=o(`${s}/conv1`),h=o(`${s}/conv2`),d=o(`${s}/conv3`);return{conv0:p,conv1:l,conv2:h,conv3:d}}return{extractDenseBlock3Params:i,extractDenseBlock4Params:a}}function lb(e){const t=[],{extractDenseBlock4Params:n}=ac(e,t),r={dense0:n("dense0",!0),dense1:n("dense1"),dense2:n("dense2"),dense3:n("dense3")};return Xe(e,t),{params:r,paramMappings:t}}class cc extends Ue{constructor(){super("FaceFeatureExtractor")}forwardInput(e){const{params:t}=this;if(!t)throw new Error("FaceFeatureExtractor - load model before inference");return k(()=>{const n=e.toBatchTensor(112,!0),r=[122.782,117.001,104.298],o=wt(n,r).div(_(255));let i=Ws(o,t.dense0,!0);return i=Ws(i,t.dense1),i=Ws(i,t.dense2),i=Ws(i,t.dense3),i=pt(i,[7,7],[2,2],"valid"),i})}async forward(e){return this.forwardInput(await ue(e))}getDefaultModelName(){return"face_feature_extractor_model"}extractParamsFromWeigthMap(e){return lb(e)}extractParams(e){return pb(e)}}function Bs(e,t){return k(()=>R(Y(e,t.weights),t.bias))}function hb(e,t,n){const r=[],{extractWeights:o,getRemainingWeights:i}=Ze(e),a=oc(o,r),s=a(t,n,"fc");if(i().length!==0)throw new Error(`weights remaing after extract: ${i().length}`);return{paramMappings:r,params:{fc:s}}}function ub(e){const t=[],n=it(e,t);function r(i){const a=n(`${i}/weights`,2),s=n(`${i}/bias`,1);return{weights:a,bias:s}}const o={fc:r("fc")};return Xe(e,t),{params:o,paramMappings:t}}function pc(e){const t={},n={};return Object.keys(e).forEach(r=>{const o=r.startsWith("fc")?n:t;o[r]=e[r]}),{featureExtractorMap:t,classifierMap:n}}class lc extends Ue{constructor(e,t){super(e);this._faceFeatureExtractor=t}get faceFeatureExtractor(){return this._faceFeatureExtractor}runNet(e){const{params:t}=this;if(!t)throw new Error(`${this._name} - load model before inference`);return k(()=>{const n=e instanceof Jt?this.faceFeatureExtractor.forwardInput(e):e;return Bs(n.as2D(n.shape[0],-1),t.fc)})}dispose(e=!0){this.faceFeatureExtractor.dispose(e),super.dispose(e)}loadClassifierParams(e){const{params:t,paramMappings:n}=this.extractClassifierParams(e);this._params=t,this._paramMappings=n}extractClassifierParams(e){return hb(e,this.getClassifierChannelsIn(),this.getClassifierChannelsOut())}extractParamsFromWeigthMap(e){const{featureExtractorMap:t,classifierMap:n}=pc(e);return this.faceFeatureExtractor.loadFromWeightMap(t),ub(n)}extractParams(e){const t=this.getClassifierChannelsIn(),n=this.getClassifierChannelsOut(),r=n*t+n,o=e.slice(0,e.length-r),i=e.slice(e.length-r);return this.faceFeatureExtractor.extractWeights(o),this.extractClassifierParams(i)}}const ua=["neutral","happy","sad","angry","fearful","disgusted","surprised"];class fn{constructor(e){if(e.length!==7)throw new Error(`FaceExpressions.constructor - expected probabilities.length to be 7, have: ${e.length}`);ua.forEach((t,n)=>{this[t]=e[n]})}asSortedArray(){return ua.map(e=>({expression:e,probability:this[e]})).sort((e,t)=>t.probability-e.probability)}}class da extends lc{constructor(e=new cc()){super("FaceExpressionNet",e)}forwardInput(e){return k(()=>rn(this.runNet(e)))}async forward(e){return this.forwardInput(await ue(e))}async predictExpressions(e){const t=await ue(e),n=await this.forwardInput(t),r=await Promise.all(Ie(n).map(async i=>{const a=await i.data();return i.dispose(),a}));n.dispose();const o=r.map(i=>new fn(i));return t.isBatchInput?o:o[0]}getDefaultModelName(){return"face_expression_model"}getClassifierChannelsIn(){return 256}getClassifierChannelsOut(){return 7}}function la(e){return e.expressions instanceof fn}function uo(e,t){const n={expressions:t};return Object.assign({},e,n)}function dT(e,t,n=.1,r){const o=Array.isArray(t)?t:[t];o.forEach(i=>{const a=i instanceof fn?i:la(i)?i.expressions:void 0;if(!a)throw new Error("drawFaceExpressions - expected faceExpressions to be FaceExpressions | WithFaceExpressions<{}> or array thereof");const s=a.asSortedArray(),c=s.filter(h=>h.probability>n),p=Nt(i)?i.detection.box.bottomLeft:r||new J(0,0),l=new Zr(c.map(h=>`${h.expression} (${dr(h.probability)})`),p);l.draw(e)})}function dn(e){return Nt(e)&&e.landmarks instanceof st&&e.unshiftedLandmarks instanceof st&&e.alignedRect instanceof fe}function Rn(e,t){const{box:n}=e.detection,r=t.shiftBy(n.x,n.y),o=r.align(),{imageDims:i}=e.detection,a=new fe(e.detection.score,o.rescale(i.reverse()),i),s={landmarks:r,unshiftedLandmarks:t,alignedRect:a};return Object.assign({},e,s)}class db{constructor(e={}){const{drawLines:t=!0,drawPoints:n=!0,lineWidth:r,lineColor:o,pointSize:i,pointColor:a}=e;this.drawLines=t,this.drawPoints=n,this.lineWidth=r||1,this.pointSize=i||2,this.lineColor=o||"rgba(0, 255, 255, 1)",this.pointColor=a||"rgba(255, 0, 255, 1)"}}class mb{constructor(e,t={}){this.faceLandmarks=e,this.options=new db(t)}draw(e){const t=qe(e),{drawLines:n,drawPoints:r,lineWidth:o,lineColor:i,pointSize:a,pointColor:s}=this.options;if(n&&this.faceLandmarks instanceof Nr&&(t.strokeStyle=i,t.lineWidth=o,sn(t,this.faceLandmarks.getJawOutline()),sn(t,this.faceLandmarks.getLeftEyeBrow()),sn(t,this.faceLandmarks.getRightEyeBrow()),sn(t,this.faceLandmarks.getNose()),sn(t,this.faceLandmarks.getLeftEye(),!0),sn(t,this.faceLandmarks.getRightEye(),!0),sn(t,this.faceLandmarks.getMouth(),!0)),r){t.strokeStyle=s,t.fillStyle=s;const c=p=>{t.beginPath(),t.arc(p.x,p.y,a,0,2*Math.PI),t.fill()};this.faceLandmarks.positions.forEach(c)}}}function mT(e,t){const n=Array.isArray(t)?t:[t];n.forEach(r=>{const o=r instanceof st?r:dn(r)?r.landmarks:void 0;if(!o)throw new Error("drawFaceLandmarks - expected faceExpressions to be FaceLandmarks | WithFaceLandmarks> or array thereof");new mb(o).draw(e)})}const Ks={};Re(Ks,{AnchorPosition:()=>Kt,DrawBox:()=>pu,DrawBoxOptions:()=>cb,DrawFaceLandmarks:()=>mb,DrawFaceLandmarksOptions:()=>db,DrawTextField:()=>Zr,DrawTextFieldOptions:()=>tc,drawContour:()=>sn,drawDetections:()=>uT,drawFaceExpressions:()=>dT,drawFaceLandmarks:()=>mT});function fT(e,t){const n=Qr(e,t),r=eo(e,t);function o(a,s,c){const p=r(a,s,`${c}/separable_conv0`),l=r(s,s,`${c}/separable_conv1`),h=n(a,s,1,`${c}/expansion_conv`);return{separable_conv0:p,separable_conv1:l,expansion_conv:h}}function i(a,s){const c=r(a,a,`${s}/separable_conv0`),p=r(a,a,`${s}/separable_conv1`),l=r(a,a,`${s}/separable_conv2`);return{separable_conv0:c,separable_conv1:p,separable_conv2:l}}return{extractConvParams:n,extractSeparableConvParams:r,extractReductionBlockParams:o,extractMainBlockParams:i}}function fb(e,t){const n=[],{extractWeights:r,getRemainingWeights:o}=Ze(e),{extractConvParams:i,extractSeparableConvParams:a,extractReductionBlockParams:s,extractMainBlockParams:c}=fT(r,n),p=i(3,32,3,"entry_flow/conv_in"),l=s(32,64,"entry_flow/reduction_block_0"),h=s(64,128,"entry_flow/reduction_block_1"),d={conv_in:p,reduction_block_0:l,reduction_block_1:h},b={};Vt(t,0,1).forEach(S=>{b[`main_block_${S}`]=c(128,`middle_flow/main_block_${S}`)});const x=s(128,256,"exit_flow/reduction_block"),w=a(256,512,"exit_flow/separable_conv"),L={reduction_block:x,separable_conv:w};if(o().length!==0)throw new Error(`weights remaing after extract: ${o().length}`);return{paramMappings:n,params:{entry_flow:d,middle_flow:b,exit_flow:L}}}function gT(e,t){const n=it(e,t),r=sc(n),o=to(n);function i(s){const c=o(`${s}/separable_conv0`),p=o(`${s}/separable_conv1`),l=r(`${s}/expansion_conv`);return{separable_conv0:c,separable_conv1:p,expansion_conv:l}}function a(s){const c=o(`${s}/separable_conv0`),p=o(`${s}/separable_conv1`),l=o(`${s}/separable_conv2`);return{separable_conv0:c,separable_conv1:p,separable_conv2:l}}return{extractConvParams:r,extractSeparableConvParams:o,extractReductionBlockParams:i,extractMainBlockParams:a}}function gb(e,t){const n=[],{extractConvParams:r,extractSeparableConvParams:o,extractReductionBlockParams:i,extractMainBlockParams:a}=gT(e,n),s=r("entry_flow/conv_in"),c=i("entry_flow/reduction_block_0"),p=i("entry_flow/reduction_block_1"),l={conv_in:s,reduction_block_0:c,reduction_block_1:p},h={};Vt(t,0,1).forEach(w=>{h[`main_block_${w}`]=a(`middle_flow/main_block_${w}`)});const d=i("exit_flow/reduction_block"),b=o("exit_flow/separable_conv"),x={reduction_block:d,separable_conv:b};return Xe(e,n),{params:{entry_flow:l,middle_flow:h,exit_flow:x},paramMappings:n}}function bb(e,t,n){return R(xe(e,t.filters,n,"same"),t.bias)}function hu(e,t,n=!0){let r=n?ie(e):e;return r=rt(r,t.separable_conv0,[1,1]),r=rt(ie(r),t.separable_conv1,[1,1]),r=Ae(r,[3,3],[2,2],"same"),r=R(r,bb(e,t.expansion_conv,[2,2])),r}function bT(e,t){let n=rt(ie(e),t.separable_conv0,[1,1]);return n=rt(ie(n),t.separable_conv1,[1,1]),n=rt(ie(n),t.separable_conv2,[1,1]),n=R(n,e),n}class wb extends Ue{constructor(e){super("TinyXception");this._numMainBlocks=e}forwardInput(e){const{params:t}=this;if(!t)throw new Error("TinyXception - load model before inference");return k(()=>{const n=e.toBatchTensor(112,!0),r=[122.782,117.001,104.298],o=wt(n,r).div(_(256));let i=ie(bb(o,t.entry_flow.conv_in,[2,2]));return i=hu(i,t.entry_flow.reduction_block_0,!1),i=hu(i,t.entry_flow.reduction_block_1),Vt(this._numMainBlocks,0,1).forEach(a=>{i=bT(i,t.middle_flow[`main_block_${a}`])}),i=hu(i,t.exit_flow.reduction_block),i=ie(rt(i,t.exit_flow.separable_conv,[1,1])),i})}async forward(e){return this.forwardInput(await ue(e))}getDefaultModelName(){return"tiny_xception_model"}extractParamsFromWeigthMap(e){return gb(e,this._numMainBlocks)}extractParams(e){return fb(e,this._numMainBlocks)}}function xb(e){const t=[],{extractWeights:n,getRemainingWeights:r}=Ze(e),o=oc(n,t),i=o(512,1,"fc/age"),a=o(512,2,"fc/gender");if(r().length!==0)throw new Error(`weights remaing after extract: ${r().length}`);return{paramMappings:t,params:{fc:{age:i,gender:a}}}}function yb(e){const t=[],n=it(e,t);function r(i){const a=n(`${i}/weights`,2),s=n(`${i}/bias`,1);return{weights:a,bias:s}}const o={fc:{age:r("fc/age"),gender:r("fc/gender")}};return Xe(e,t),{params:o,paramMappings:t}}var Bt;(function(e){e.FEMALE="female",e.MALE="male"})(Bt||(Bt={}));class La extends Ue{constructor(e=new wb(2)){super("AgeGenderNet");this._faceFeatureExtractor=e}get faceFeatureExtractor(){return this._faceFeatureExtractor}runNet(e){const{params:t}=this;if(!t)throw new Error(`${this._name} - load model before inference`);return k(()=>{const n=e instanceof Jt?this.faceFeatureExtractor.forwardInput(e):e,r=pt(n,[7,7],[2,2],"valid").as2D(n.shape[0],-1),o=Bs(r,t.fc.age).as1D(),i=Bs(r,t.fc.gender);return{age:o,gender:i}})}forwardInput(e){return k(()=>{const{age:t,gender:n}=this.runNet(e);return{age:t,gender:rn(n)}})}async forward(e){return this.forwardInput(await ue(e))}async predictAgeAndGender(e){const t=await ue(e),n=await this.forwardInput(t),r=Ie(n.age),o=Ie(n.gender),i=r.map((s,c)=>({ageTensor:s,genderTensor:o[c]})),a=await Promise.all(i.map(async({ageTensor:s,genderTensor:c})=>{const p=(await s.data())[0],l=(await c.data())[0],h=l>.5,d=h?Bt.MALE:Bt.FEMALE,b=h?l:1-l;return s.dispose(),c.dispose(),{age:p,gender:d,genderProbability:b}}));return n.age.dispose(),n.gender.dispose(),t.isBatchInput?a:a[0]}getDefaultModelName(){return"age_gender_model"}dispose(e=!0){this.faceFeatureExtractor.dispose(e),super.dispose(e)}loadClassifierParams(e){const{params:t,paramMappings:n}=this.extractClassifierParams(e);this._params=t,this._paramMappings=n}extractClassifierParams(e){return xb(e)}extractParamsFromWeigthMap(e){const{featureExtractorMap:t,classifierMap:n}=pc(e);return this.faceFeatureExtractor.loadFromWeightMap(t),yb(n)}extractParams(e){const t=512*1+1+(512*2+2),n=e.slice(0,e.length-t),r=e.slice(e.length-t);return this.faceFeatureExtractor.extractWeights(n),this.extractClassifierParams(r)}}class hc extends lc{postProcess(e,t,n){const r=n.map(({width:i,height:a})=>{const s=t/Math.max(a,i);return{width:i*s,height:a*s}}),o=r.length;return k(()=>{const i=(l,h)=>ke([Ge([68],l),Ge([68],h)],1).as2D(1,136).as1D(),a=(l,h)=>{const{width:d,height:b}=r[l];return h(d,b)?Math.abs(d-b)/2:0},s=l=>a(l,(h,d)=>ha(l,(h,d)=>di(s(h),c(h))))).div(ke(Array.from(Array(o),(l,h)=>i(r[h].width,r[h].height))));return p})}forwardInput(e){return k(()=>{const t=this.runNet(e);return this.postProcess(t,e.inputSize,e.inputDimensions.map(([n,r])=>({height:n,width:r})))})}async forward(e){return this.forwardInput(await ue(e))}async detectLandmarks(e){const t=await ue(e),n=k(()=>Ie(this.forwardInput(t))),r=await Promise.all(n.map(async(o,i)=>{const a=Array.from(await o.data()),s=a.filter((p,l)=>Za(l)),c=a.filter((p,l)=>!Za(l));return new Nr(Array(68).fill(0).map((p,l)=>new J(s[l],c[l])),{height:t.getInputHeight(i),width:t.getInputWidth(i)})}));return n.forEach(o=>o.dispose()),t.isBatchInput?r:r[0]}getClassifierChannelsOut(){return 136}}class Sr extends hc{constructor(e=new cc()){super("FaceLandmark68Net",e)}getDefaultModelName(){return"face_landmark_68_model"}getClassifierChannelsIn(){return 256}}function Lb(e){const t=[],{extractDenseBlock3Params:n}=ac(e,t),r={dense0:n("dense0",!0),dense1:n("dense1"),dense2:n("dense2")};return Xe(e,t),{params:r,paramMappings:t}}function vb(e){const t=[],{extractWeights:n,getRemainingWeights:r}=Ze(e),{extractDenseBlock3Params:o}=ic(n,t),i=o(3,32,"dense0",!0),a=o(32,64,"dense1"),s=o(64,128,"dense2");if(r().length!==0)throw new Error(`weights remaing after extract: ${r().length}`);return{paramMappings:t,params:{dense0:i,dense1:a,dense2:s}}}class Sb extends Ue{constructor(){super("TinyFaceFeatureExtractor")}forwardInput(e){const{params:t}=this;if(!t)throw new Error("TinyFaceFeatureExtractor - load model before inference");return k(()=>{const n=e.toBatchTensor(112,!0),r=[122.782,117.001,104.298],o=wt(n,r).div(_(255));let i=rc(o,t.dense0,!0);return i=rc(i,t.dense1),i=rc(i,t.dense2),i=pt(i,[14,14],[2,2],"valid"),i})}async forward(e){return this.forwardInput(await ue(e))}getDefaultModelName(){return"face_feature_extractor_tiny_model"}extractParamsFromWeigthMap(e){return Lb(e)}extractParams(e){return vb(e)}}class ha extends hc{constructor(e=new Sb()){super("FaceLandmark68TinyNet",e)}getDefaultModelName(){return"face_landmark_68_tiny_model"}getClassifierChannelsIn(){return 128}}class pd extends Sr{}function Ib(e,t){return R(v(e,t.weights),t.biases)}function uu(e,t,n,r,o="same"){const{filters:i,bias:a}=t.conv;let s=xe(e,i,n,o);return s=R(s,a),s=Ib(s,t.scale),r?ie(s):s}function Tb(e,t){return uu(e,t,[1,1],!0)}function du(e,t){return uu(e,t,[1,1],!1)}function uc(e,t){return uu(e,t,[2,2],!0,"valid")}function wT(e,t){function n(s,c,p){const l=e(s),h=l.length/(c*p*p);if(tu(h))throw new Error(`depth has to be an integer: ${h}, weights.length: ${l.length}, numFilters: ${c}, filterSize: ${p}`);return k(()=>K(ft(l,[c,h,p,p]),[2,3,1,0]))}function r(s,c,p,l){const h=n(s,c,p),d=ce(e(c));return t.push({paramPath:`${l}/filters`},{paramPath:`${l}/bias`}),{filters:h,bias:d}}function o(s,c){const p=ce(e(s)),l=ce(e(s));return t.push({paramPath:`${c}/weights`},{paramPath:`${c}/biases`}),{weights:p,biases:l}}function i(s,c,p,l){const h=r(s,c,p,`${l}/conv`),d=o(c,`${l}/scale`);return{conv:h,scale:d}}function a(s,c,p,l,h=!1){const d=i((h?.5:1)*s,c,p,`${l}/conv1`),b=i(s,c,p,`${l}/conv2`);return{conv1:d,conv2:b}}return{extractConvLayerParams:i,extractResidualLayerParams:a}}function Ab(e){const{extractWeights:t,getRemainingWeights:n}=Ze(e),r=[],{extractConvLayerParams:o,extractResidualLayerParams:i}=wT(t,r),a=o(4704,32,7,"conv32_down"),s=i(9216,32,3,"conv32_1"),c=i(9216,32,3,"conv32_2"),p=i(9216,32,3,"conv32_3"),l=i(36864,64,3,"conv64_down",!0),h=i(36864,64,3,"conv64_1"),d=i(36864,64,3,"conv64_2"),b=i(36864,64,3,"conv64_3"),x=i(147456,128,3,"conv128_down",!0),w=i(147456,128,3,"conv128_1"),L=i(147456,128,3,"conv128_2"),S=i(589824,256,3,"conv256_down",!0),I=i(589824,256,3,"conv256_1"),N=i(589824,256,3,"conv256_2"),A=i(589824,256,3,"conv256_down_out"),E=k(()=>K(mt(t(256*128),[128,256]),[1,0]));if(r.push({paramPath:"fc"}),n().length!==0)throw new Error(`weights remaing after extract: ${n().length}`);const M={conv32_down:a,conv32_1:s,conv32_2:c,conv32_3:p,conv64_down:l,conv64_1:h,conv64_2:d,conv64_3:b,conv128_down:x,conv128_1:w,conv128_2:L,conv256_down:S,conv256_1:I,conv256_2:N,conv256_down_out:A,fc:E};return{params:M,paramMappings:r}}function xT(e,t){const n=it(e,t);function r(a){const s=n(`${a}/scale/weights`,1),c=n(`${a}/scale/biases`,1);return{weights:s,biases:c}}function o(a){const s=n(`${a}/conv/filters`,4),c=n(`${a}/conv/bias`,1),p=r(a);return{conv:{filters:s,bias:c},scale:p}}function i(a){return{conv1:o(`${a}/conv1`),conv2:o(`${a}/conv2`)}}return{extractConvLayerParams:o,extractResidualLayerParams:i}}function Nb(e){const t=[],{extractConvLayerParams:n,extractResidualLayerParams:r}=xT(e,t),o=n("conv32_down"),i=r("conv32_1"),a=r("conv32_2"),s=r("conv32_3"),c=r("conv64_down"),p=r("conv64_1"),l=r("conv64_2"),h=r("conv64_3"),d=r("conv128_down"),b=r("conv128_1"),x=r("conv128_2"),w=r("conv256_down"),L=r("conv256_1"),S=r("conv256_2"),I=r("conv256_down_out"),N=e.fc;if(t.push({originalPath:"fc",paramPath:"fc"}),!eu(N))throw new Error(`expected weightMap[fc] to be a Tensor2D, instead have ${N}`);const A={conv32_down:o,conv32_1:i,conv32_2:a,conv32_3:s,conv64_down:c,conv64_1:p,conv64_2:l,conv64_3:h,conv128_down:d,conv128_1:b,conv128_2:x,conv256_down:w,conv256_1:L,conv256_2:S,conv256_down_out:I,fc:N};return Xe(e,t),{params:A,paramMappings:t}}function Ut(e,t){let n=Tb(e,t.conv1);return n=du(n,t.conv2),n=R(n,e),n=ie(n),n}function $s(e,t){let n=uc(e,t.conv1);n=du(n,t.conv2);let r=pt(e,2,2,"valid");const o=Ce(r.shape),i=r.shape[3]!==n.shape[3],a=r.shape[1]!==n.shape[1]||r.shape[2]!==n.shape[2];if(a){const s=[...n.shape];s[1]=1;const c=Ce(s);n=Z([n,c],1);const p=[...n.shape];p[2]=1;const l=Ce(p);n=Z([n,l],2)}return r=i?Z([r,o],3):r,n=R(r,n),n=ie(n),n}class vr extends Ue{constructor(){super("FaceRecognitionNet")}forwardInput(e){const{params:t}=this;if(!t)throw new Error("FaceRecognitionNet - load model before inference");return k(()=>{const n=e.toBatchTensor(150,!0).toFloat(),r=[122.782,117.001,104.298],o=wt(n,r).div(_(256));let i=uc(o,t.conv32_down);i=Ae(i,3,2,"valid"),i=Ut(i,t.conv32_1),i=Ut(i,t.conv32_2),i=Ut(i,t.conv32_3),i=$s(i,t.conv64_down),i=Ut(i,t.conv64_1),i=Ut(i,t.conv64_2),i=Ut(i,t.conv64_3),i=$s(i,t.conv128_down),i=Ut(i,t.conv128_1),i=Ut(i,t.conv128_2),i=$s(i,t.conv256_down),i=Ut(i,t.conv256_1),i=Ut(i,t.conv256_2),i=$s(i,t.conv256_down_out);const a=i.mean([1,2]),s=Y(a,t.fc);return s})}async forward(e){return this.forwardInput(await ue(e))}async computeFaceDescriptor(e){const t=await ue(e),n=k(()=>Ie(this.forwardInput(t))),r=await Promise.all(n.map(o=>o.data()));return n.forEach(o=>o.dispose()),t.isBatchInput?r:r[0]}getDefaultModelName(){return"face_recognition_model"}extractParamsFromWeigthMap(e){return Nb(e)}extractParams(e){return Ab(e)}}function cd(e){const t=new vr();return t.extractWeights(e),t}function mo(e,t){const n={descriptor:t};return Object.assign({},e,n)}function ad(e){return typeof e.age=="number"}function fo(e,t){const n={age:t};return Object.assign({},e,n)}function sd(e){return(e.gender===Bt.MALE||e.gender===Bt.FEMALE)&&Xr(e.genderProbability)}function ho(e,t,n){const r={gender:t,genderProbability:n};return Object.assign({},e,r)}function yT(e,t){function n(c,p){const l=ft(e(3*3*c),[3,3,c,1]),h=ce(e(c)),d=ce(e(c)),b=ce(e(c)),x=ce(e(c));return t.push({paramPath:`${p}/filters`},{paramPath:`${p}/batch_norm_scale`},{paramPath:`${p}/batch_norm_offset`},{paramPath:`${p}/batch_norm_mean`},{paramPath:`${p}/batch_norm_variance`}),{filters:l,batch_norm_scale:h,batch_norm_offset:d,batch_norm_mean:b,batch_norm_variance:x}}function r(c,p,l,h,d){const b=ft(e(c*p*l*l),[l,l,c,p]),x=ce(e(p));return t.push({paramPath:`${h}/filters`},{paramPath:`${h}/${d?"batch_norm_offset":"bias"}`}),{filters:b,bias:x}}function o(c,p,l,h){const{filters:d,bias:b}=r(c,p,l,h,!0);return{filters:d,batch_norm_offset:b}}function i(c,p,l){const h=n(c,`${l}/depthwise_conv`),d=o(c,p,1,`${l}/pointwise_conv`);return{depthwise_conv:h,pointwise_conv:d}}function a(){const c=o(3,32,3,"mobilenetv1/conv_0"),p=i(32,64,"mobilenetv1/conv_1"),l=i(64,128,"mobilenetv1/conv_2"),h=i(128,128,"mobilenetv1/conv_3"),d=i(128,256,"mobilenetv1/conv_4"),b=i(256,256,"mobilenetv1/conv_5"),x=i(256,512,"mobilenetv1/conv_6"),w=i(512,512,"mobilenetv1/conv_7"),L=i(512,512,"mobilenetv1/conv_8"),S=i(512,512,"mobilenetv1/conv_9"),I=i(512,512,"mobilenetv1/conv_10"),N=i(512,512,"mobilenetv1/conv_11"),A=i(512,1024,"mobilenetv1/conv_12"),E=i(1024,1024,"mobilenetv1/conv_13");return{conv_0:c,conv_1:p,conv_2:l,conv_3:h,conv_4:d,conv_5:b,conv_6:x,conv_7:w,conv_8:L,conv_9:S,conv_10:I,conv_11:N,conv_12:A,conv_13:E}}function s(){const c=o(1024,256,1,"prediction_layer/conv_0"),p=o(256,512,3,"prediction_layer/conv_1"),l=o(512,128,1,"prediction_layer/conv_2"),h=o(128,256,3,"prediction_layer/conv_3"),d=o(256,128,1,"prediction_layer/conv_4"),b=o(128,256,3,"prediction_layer/conv_5"),x=o(256,64,1,"prediction_layer/conv_6"),w=o(64,128,3,"prediction_layer/conv_7"),L=r(512,12,1,"prediction_layer/box_predictor_0/box_encoding_predictor"),S=r(512,9,1,"prediction_layer/box_predictor_0/class_predictor"),I=r(1024,24,1,"prediction_layer/box_predictor_1/box_encoding_predictor"),N=r(1024,18,1,"prediction_layer/box_predictor_1/class_predictor"),A=r(512,24,1,"prediction_layer/box_predictor_2/box_encoding_predictor"),E=r(512,18,1,"prediction_layer/box_predictor_2/class_predictor"),M=r(256,24,1,"prediction_layer/box_predictor_3/box_encoding_predictor"),D=r(256,18,1,"prediction_layer/box_predictor_3/class_predictor"),$=r(256,24,1,"prediction_layer/box_predictor_4/box_encoding_predictor"),B=r(256,18,1,"prediction_layer/box_predictor_4/class_predictor"),j=r(128,24,1,"prediction_layer/box_predictor_5/box_encoding_predictor"),te=r(128,18,1,"prediction_layer/box_predictor_5/class_predictor"),re={box_encoding_predictor:L,class_predictor:S},he={box_encoding_predictor:I,class_predictor:N},ye={box_encoding_predictor:A,class_predictor:E},Me={box_encoding_predictor:M,class_predictor:D},Tt={box_encoding_predictor:$,class_predictor:B},ln={box_encoding_predictor:j,class_predictor:te};return{conv_0:c,conv_1:p,conv_2:l,conv_3:h,conv_4:d,conv_5:b,conv_6:x,conv_7:w,box_predictor_0:re,box_predictor_1:he,box_predictor_2:ye,box_predictor_3:Me,box_predictor_4:Tt,box_predictor_5:ln}}return{extractMobilenetV1Params:a,extractPredictionLayerParams:s}}function Rb(e){const t=[],{extractWeights:n,getRemainingWeights:r}=Ze(e),{extractMobilenetV1Params:o,extractPredictionLayerParams:i}=yT(n,t),a=o(),s=i(),c=er(n(5118*4),[1,5118,4]),p={extra_dim:c};if(t.push({paramPath:"output_layer/extra_dim"}),r().length!==0)throw new Error(`weights remaing after extract: ${r().length}`);return{params:{mobilenetv1:a,prediction_layer:s,output_layer:p},paramMappings:t}}function LT(e,t){const n=it(e,t);function r(p,l,h){const d=n(`${p}/Conv2d_${l}_pointwise/weights`,4,`${h}/filters`),b=n(`${p}/Conv2d_${l}_pointwise/convolution_bn_offset`,1,`${h}/batch_norm_offset`);return{filters:d,batch_norm_offset:b}}function o(p){const l=`mobilenetv1/conv_${p}`,h=`MobilenetV1/Conv2d_${p}_depthwise`,d=`${l}/depthwise_conv`,b=`${l}/pointwise_conv`,x=n(`${h}/depthwise_weights`,4,`${d}/filters`),w=n(`${h}/BatchNorm/gamma`,1,`${d}/batch_norm_scale`),L=n(`${h}/BatchNorm/beta`,1,`${d}/batch_norm_offset`),S=n(`${h}/BatchNorm/moving_mean`,1,`${d}/batch_norm_mean`),I=n(`${h}/BatchNorm/moving_variance`,1,`${d}/batch_norm_variance`);return{depthwise_conv:{filters:x,batch_norm_scale:w,batch_norm_offset:L,batch_norm_mean:S,batch_norm_variance:I},pointwise_conv:r("MobilenetV1",p,b)}}function i(){return{conv_0:r("MobilenetV1",0,"mobilenetv1/conv_0"),conv_1:o(1),conv_2:o(2),conv_3:o(3),conv_4:o(4),conv_5:o(5),conv_6:o(6),conv_7:o(7),conv_8:o(8),conv_9:o(9),conv_10:o(10),conv_11:o(11),conv_12:o(12),conv_13:o(13)}}function a(p,l){const h=n(`${p}/weights`,4,`${l}/filters`),d=n(`${p}/biases`,1,`${l}/bias`);return{filters:h,bias:d}}function s(p){const l=a(`Prediction/BoxPredictor_${p}/BoxEncodingPredictor`,`prediction_layer/box_predictor_${p}/box_encoding_predictor`),h=a(`Prediction/BoxPredictor_${p}/ClassPredictor`,`prediction_layer/box_predictor_${p}/class_predictor`);return{box_encoding_predictor:l,class_predictor:h}}function c(){return{conv_0:r("Prediction",0,"prediction_layer/conv_0"),conv_1:r("Prediction",1,"prediction_layer/conv_1"),conv_2:r("Prediction",2,"prediction_layer/conv_2"),conv_3:r("Prediction",3,"prediction_layer/conv_3"),conv_4:r("Prediction",4,"prediction_layer/conv_4"),conv_5:r("Prediction",5,"prediction_layer/conv_5"),conv_6:r("Prediction",6,"prediction_layer/conv_6"),conv_7:r("Prediction",7,"prediction_layer/conv_7"),box_predictor_0:s(0),box_predictor_1:s(1),box_predictor_2:s(2),box_predictor_3:s(3),box_predictor_4:s(4),box_predictor_5:s(5)}}return{extractMobilenetV1Params:i,extractPredictionLayerParams:c}}function _b(e){const t=[],{extractMobilenetV1Params:n,extractPredictionLayerParams:r}=LT(e,t),o=e["Output/extra_dim"];if(t.push({originalPath:"Output/extra_dim",paramPath:"output_layer/extra_dim"}),!an(o))throw new Error(`expected weightMap['Output/extra_dim'] to be a Tensor3D, instead have ${o}`);const i={mobilenetv1:n(),prediction_layer:r(),output_layer:{extra_dim:o}};return Xe(e,t),{params:i,paramMappings:t}}function It(e,t,n){return k(()=>{let r=xe(e,t.filters,n,"same");return r=R(r,t.batch_norm_offset),$n(r,0,6)})}const vT=.0010000000474974513;function ST(e,t,n){return k(()=>{let r=en(e,t.filters,n,"same");return r=Ct(r,t.batch_norm_mean,t.batch_norm_variance,t.batch_norm_offset,t.batch_norm_scale,vT),$n(r,0,6)})}function IT(e){return[2,4,6,12].some(t=>t===e)?[2,2]:[1,1]}function Cb(e,t){return k(()=>{let n=null,r=It(e,t.conv_0,[2,2]);const o=[t.conv_1,t.conv_2,t.conv_3,t.conv_4,t.conv_5,t.conv_6,t.conv_7,t.conv_8,t.conv_9,t.conv_10,t.conv_11,t.conv_12,t.conv_13];if(o.forEach((i,a)=>{const s=a+1,c=IT(s);r=ST(r,i.depthwise_conv,c),r=It(r,i.pointwise_conv,[1,1]),s===11&&(n=r)}),n===null)throw new Error("mobileNetV1 - output of conv layer 11 is null");return{out:r,conv11:n}})}function Eb(e,t,n,r,o){const i=e.shape[0],a=Math.min(n,i),s=t.map((l,h)=>({score:l,boxIndex:h})).filter(l=>l.score>o).sort((l,h)=>h.score-l.score),c=l=>l<=r?1:0,p=[];return s.forEach(l=>{if(p.length>=a)return;const h=l.score;for(let d=p.length-1;d>=0;--d){const b=TT(e,l.boxIndex,p[d]);if(b===0)continue;if(l.score*=c(b),l.score<=o)break}h===l.score&&p.push(l.boxIndex)}),p}function TT(e,t,n){const r=e.arraySync(),o=Math.min(r[t][0],r[t][2]),i=Math.min(r[t][1],r[t][3]),a=Math.max(r[t][0],r[t][2]),s=Math.max(r[t][1],r[t][3]),c=Math.min(r[n][0],r[n][2]),p=Math.min(r[n][1],r[n][3]),l=Math.max(r[n][0],r[n][2]),h=Math.max(r[n][1],r[n][3]),d=(a-o)*(s-i),b=(l-c)*(h-p);if(d<=0||b<=0)return 0;const x=Math.max(o,c),w=Math.max(i,p),L=Math.min(a,l),S=Math.min(s,h),I=Math.max(L-x,0)*Math.max(S-w,0);return I/(d+b-I)}function AT(e){const t=Ie(K(e,[1,0])),n=[O(t[2],t[0]),O(t[3],t[1])],r=[R(t[0],F(n[0],_(2))),R(t[1],F(n[1],_(2)))];return{sizes:n,centers:r}}function NT(e,t){const{sizes:n,centers:r}=AT(e),o=Ie(K(t,[1,0])),i=F(v(Se(F(o[2],_(5))),n[0]),_(2)),a=R(v(F(o[0],_(10)),n[0]),r[0]),s=F(v(Se(F(o[3],_(5))),n[1]),_(2)),c=R(v(F(o[1],_(10)),n[1]),r[1]);return K(ke([O(a,i),O(c,s),R(a,i),R(c,s)]),[1,0])}function Ob(e,t,n){return k(()=>{const r=e.shape[0];let o=NT(y(Ot(n.extra_dim,[r,1,1]),[-1,4]),y(e,[-1,4]));o=y(o,[r,o.shape[0]/r,4]);const i=lt(G(t,[0,0,1],[-1,-1,-1]));let a=G(i,[0,0,0],[-1,-1,1]);a=y(a,[r,a.shape[1]]);const s=Ie(o),c=Ie(a);return{boxes:s,scores:c}})}function gr(e,t){return k(()=>{const n=e.shape[0],r=y(fr(e,t.box_encoding_predictor),[n,-1,1,4]),o=y(fr(e,t.class_predictor),[n,-1,3]);return{boxPredictionEncoding:r,classPrediction:o}})}function kb(e,t,n){return k(()=>{const r=It(e,n.conv_0,[1,1]),o=It(r,n.conv_1,[2,2]),i=It(o,n.conv_2,[1,1]),a=It(i,n.conv_3,[2,2]),s=It(a,n.conv_4,[1,1]),c=It(s,n.conv_5,[2,2]),p=It(c,n.conv_6,[1,1]),l=It(p,n.conv_7,[2,2]),h=gr(t,n.box_predictor_0),d=gr(e,n.box_predictor_1),b=gr(o,n.box_predictor_2),x=gr(a,n.box_predictor_3),w=gr(c,n.box_predictor_4),L=gr(l,n.box_predictor_5),S=Z([h.boxPredictionEncoding,d.boxPredictionEncoding,b.boxPredictionEncoding,x.boxPredictionEncoding,w.boxPredictionEncoding,L.boxPredictionEncoding],1),I=Z([h.classPrediction,d.classPrediction,b.classPrediction,x.classPrediction,w.classPrediction,L.classPrediction],1);return{boxPredictions:S,classPredictions:I}})}class bt{constructor({minConfidence:e,maxResults:t}={}){if(this._name="SsdMobilenetv1Options",this._minConfidence=e||.5,this._maxResults=t||100,typeof this._minConfidence!="number"||this._minConfidence<=0||this._minConfidence>=1)throw new Error(`${this._name} - expected minConfidence to be a number between 0 and 1`);if(typeof this._maxResults!="number")throw new Error(`${this._name} - expected maxResults to be a number`)}get minConfidence(){return this._minConfidence}get maxResults(){return this._maxResults}}class Nn extends Ue{constructor(){super("SsdMobilenetv1")}forwardInput(e){const{params:t}=this;if(!t)throw new Error("SsdMobilenetv1 - load model before inference");return k(()=>{const n=e.toBatchTensor(512,!1).toFloat(),r=O(v(n,_(.007843137718737125)),_(1)),o=Cb(r,t.mobilenetv1),{boxPredictions:i,classPredictions:a}=kb(o.out,o.conv11,t.prediction_layer);return Ob(i,a,t.output_layer)})}async forward(e){return this.forwardInput(await ue(e))}async locateFaces(e,t={}){const{maxResults:n,minConfidence:r}=new bt(t),o=await ue(e),{boxes:i,scores:a}=this.forwardInput(o),s=i[0],c=a[0];for(let I=1;I{const[N,A]=[Math.max(0,L[I][0]),Math.min(1,L[I][2])].map(D=>D*w),[E,M]=[Math.max(0,L[I][1]),Math.min(1,L[I][3])].map(D=>D*x);return new fe(p[I],new Ar(E,N,M-E,A-N),{height:o.getInputHeight(0),width:o.getInputWidth(0)})});return s.dispose(),c.dispose(),S}getDefaultModelName(){return"ssd_mobilenetv1_model"}extractParamsFromWeigthMap(e){return _b(e)}extractParams(e){return Rb(e)}}function yc(e){const t=new Nn();return t.extractWeights(e),t}function Uu(e){return yc(e)}class Wu extends Nn{}const Db=.4,Fb=[new J(.738768,.874946),new J(2.42204,2.65704),new J(4.30971,7.04493),new J(10.246,4.59428),new J(12.6868,11.8741)],Mb=[new J(1.603231,2.094468),new J(6.041143,7.080126),new J(2.882459,3.518061),new J(4.266906,5.178857),new J(9.041765,10.66308)],Ub=[117.001,114.697,97.404],Wb="tiny_yolov2_model",Bb="tiny_yolov2_separable_conv_model";const dc=e=>typeof e=="number";function Xs(e){if(!e)throw new Error(`invalid config: ${e}`);if(typeof e.withSeparableConvs!="boolean")throw new Error(`config.withSeparableConvs has to be a boolean, have: ${e.withSeparableConvs}`);if(!dc(e.iouThreshold)||e.iouThreshold<0||e.iouThreshold>1)throw new Error(`config.iouThreshold has to be a number between [0, 1], have: ${e.iouThreshold}`);if(!Array.isArray(e.classes)||!e.classes.length||!e.classes.every(t=>typeof t=="string"))throw new Error(`config.classes has to be an array class names: string[], have: ${JSON.stringify(e.classes)}`);if(!Array.isArray(e.anchors)||!e.anchors.length||!e.anchors.map(t=>t||{}).every(t=>dc(t.x)&&dc(t.y)))throw new Error(`config.anchors has to be an array of { x: number, y: number }, have: ${JSON.stringify(e.anchors)}`);if(e.meanRgb&&(!Array.isArray(e.meanRgb)||e.meanRgb.length!==3||!e.meanRgb.every(dc)))throw new Error(`config.meanRgb has to be an array of shape [number, number, number], have: ${JSON.stringify(e.meanRgb)}`)}function no(e){return k(()=>{const t=v(e,_(.10000000149011612));return R(ie(O(e,t)),t)})}function cn(e,t){return k(()=>{let n=Pe(e,[[0,0],[1,1],[1,1],[0,0]]);return n=xe(n,t.conv.filters,[1,1],"valid"),n=O(n,t.bn.sub),n=v(n,t.bn.truediv),n=R(n,t.conv.bias),no(n)})}function pn(e,t){return k(()=>{let n=Pe(e,[[0,0],[1,1],[1,1],[0,0]]);return n=Xn(n,t.depthwise_filter,t.pointwise_filter,[1,1],"valid"),n=R(n,t.bias),no(n)})}function RT(e,t){const n=Qr(e,t);function r(a,s){const c=ce(e(a)),p=ce(e(a));return t.push({paramPath:`${s}/sub`},{paramPath:`${s}/truediv`}),{sub:c,truediv:p}}function o(a,s,c){const p=n(a,s,3,`${c}/conv`),l=r(s,`${c}/bn`);return{conv:p,bn:l}}const i=eo(e,t);return{extractConvParams:n,extractConvWithBatchNormParams:o,extractSeparableConvParams:i}}function $b(e,t,n,r){const{extractWeights:o,getRemainingWeights:i}=Ze(e),a=[],{extractConvParams:s,extractConvWithBatchNormParams:c,extractSeparableConvParams:p}=RT(o,a);let l;if(t.withSeparableConvs){const[h,d,b,x,w,L,S,I,N]=r,A=t.isFirstLayerConv2d?s(h,d,3,"conv0"):p(h,d,"conv0"),E=p(d,b,"conv1"),M=p(b,x,"conv2"),D=p(x,w,"conv3"),$=p(w,L,"conv4"),B=p(L,S,"conv5"),j=I?p(S,I,"conv6"):void 0,te=N?p(I,N,"conv7"):void 0,re=s(N||I||S,5*n,1,"conv8");l={conv0:A,conv1:E,conv2:M,conv3:D,conv4:$,conv5:B,conv6:j,conv7:te,conv8:re}}else{const[h,d,b,x,w,L,S,I,N]=r,A=c(h,d,"conv0"),E=c(d,b,"conv1"),M=c(b,x,"conv2"),D=c(x,w,"conv3"),$=c(w,L,"conv4"),B=c(L,S,"conv5"),j=c(S,I,"conv6"),te=c(I,N,"conv7"),re=s(N,5*n,1,"conv8");l={conv0:A,conv1:E,conv2:M,conv3:D,conv4:$,conv5:B,conv6:j,conv7:te,conv8:re}}if(i().length!==0)throw new Error(`weights remaing after extract: ${i().length}`);return{params:l,paramMappings:a}}function _T(e,t){const n=it(e,t);function r(s){const c=n(`${s}/sub`,1),p=n(`${s}/truediv`,1);return{sub:c,truediv:p}}function o(s){const c=n(`${s}/filters`,4),p=n(`${s}/bias`,1);return{filters:c,bias:p}}function i(s){const c=o(`${s}/conv`),p=r(`${s}/bn`);return{conv:c,bn:p}}const a=to(n);return{extractConvParams:o,extractConvWithBatchNormParams:i,extractSeparableConvParams:a}}function jb(e,t){const n=[],{extractConvParams:r,extractConvWithBatchNormParams:o,extractSeparableConvParams:i}=_T(e,n);let a;if(t.withSeparableConvs){const s=t.filterSizes&&t.filterSizes.length||9;a={conv0:t.isFirstLayerConv2d?r("conv0"):i("conv0"),conv1:i("conv1"),conv2:i("conv2"),conv3:i("conv3"),conv4:i("conv4"),conv5:i("conv5"),conv6:s>7?i("conv6"):void 0,conv7:s>8?i("conv7"):void 0,conv8:r("conv8")}}else a={conv0:o("conv0"),conv1:o("conv1"),conv2:o("conv2"),conv3:o("conv3"),conv4:o("conv4"),conv5:o("conv5"),conv6:o("conv6"),conv7:o("conv7"),conv8:r("conv8")};return Xe(e,n),{params:a,paramMappings:n}}var Zs;(function(e){e[e.XS=224]="XS",e[e.SM=320]="SM",e[e.MD=416]="MD",e[e.LG=608]="LG"})(Zs||(Zs={}));class Wt{constructor({inputSize:e,scoreThreshold:t}={}){if(this._name="TinyYolov2Options",this._inputSize=e||416,this._scoreThreshold=t||.5,typeof this._inputSize!="number"||this._inputSize%32!==0)throw new Error(`${this._name} - expected inputSize to be a number divisible by 32`);if(typeof this._scoreThreshold!="number"||this._scoreThreshold<=0||this._scoreThreshold>=1)throw new Error(`${this._name} - expected scoreThreshold to be a number between 0 and 1`)}get inputSize(){return this._inputSize}get scoreThreshold(){return this._scoreThreshold}}class ro extends Ue{constructor(e){super("TinyYolov2");Xs(e),this._config=e}get config(){return this._config}get withClassScores(){return this.config.withClassScores||this.config.classes.length>1}get boxEncodingSize(){return 5+(this.withClassScores?this.config.classes.length:0)}runTinyYolov2(e,t){let n=cn(e,t.conv0);return n=Ae(n,[2,2],[2,2],"same"),n=cn(n,t.conv1),n=Ae(n,[2,2],[2,2],"same"),n=cn(n,t.conv2),n=Ae(n,[2,2],[2,2],"same"),n=cn(n,t.conv3),n=Ae(n,[2,2],[2,2],"same"),n=cn(n,t.conv4),n=Ae(n,[2,2],[2,2],"same"),n=cn(n,t.conv5),n=Ae(n,[2,2],[1,1],"same"),n=cn(n,t.conv6),n=cn(n,t.conv7),fr(n,t.conv8,"valid",!1)}runMobilenet(e,t){let n=this.config.isFirstLayerConv2d?no(fr(e,t.conv0,"valid",!1)):pn(e,t.conv0);return n=Ae(n,[2,2],[2,2],"same"),n=pn(n,t.conv1),n=Ae(n,[2,2],[2,2],"same"),n=pn(n,t.conv2),n=Ae(n,[2,2],[2,2],"same"),n=pn(n,t.conv3),n=Ae(n,[2,2],[2,2],"same"),n=pn(n,t.conv4),n=Ae(n,[2,2],[2,2],"same"),n=pn(n,t.conv5),n=Ae(n,[2,2],[1,1],"same"),n=t.conv6?pn(n,t.conv6):n,n=t.conv7?pn(n,t.conv7):n,fr(n,t.conv8,"valid",!1)}forwardInput(e,t){const{params:n}=this;if(!n)throw new Error("TinyYolov2 - load model before inference");return k(()=>{let r=e.toBatchTensor(t,!1).toFloat();return r=this.config.meanRgb?wt(r,this.config.meanRgb):r,r=r.div(_(256)),this.config.withSeparableConvs?this.runMobilenet(r,n):this.runTinyYolov2(r,n)})}async forward(e,t){return await this.forwardInput(await ue(e),t)}async detect(e,t={}){const{inputSize:n,scoreThreshold:r}=new Wt(t),o=await ue(e),i=await this.forwardInput(o,n),a=k(()=>Ie(i)[0].expandDims()),s={width:o.getInputWidth(0),height:o.getInputHeight(0)},c=await this.extractBoxes(a,o.getReshapedInputDimensions(0),r);i.dispose(),a.dispose();const p=c.map(w=>w.box),l=c.map(w=>w.score),h=c.map(w=>w.classScore),d=c.map(w=>this.config.classes[w.label]),b=ta(p.map(w=>w.rescale(n)),l,this.config.iouThreshold,!0),x=b.map(w=>new On(l[w],h[w],d[w],p[w],s));return x}getDefaultModelName(){return""}extractParamsFromWeigthMap(e){return jb(e,this.config)}extractParams(e){const t=this.config.filterSizes||ro.DEFAULT_FILTER_SIZES,n=t?t.length:void 0;if(n!==7&&n!==8&&n!==9)throw new Error(`TinyYolov2 - expected 7 | 8 | 9 convolutional filters, but found ${n} filterSizes in config`);return $b(e,this.config,this.boxEncodingSize,t)}async extractBoxes(e,t,n){const{width:r,height:o}=t,i=Math.max(r,o),a=i/r,s=i/o,c=e.shape[1],p=this.config.anchors.length,[l,h,d]=k(()=>{const L=e.reshape([c,c,p,this.boxEncodingSize]),S=L.slice([0,0,0,0],[c,c,p,4]),I=L.slice([0,0,0,4],[c,c,p,1]),N=this.withClassScores?rn(L.slice([0,0,0,5],[c,c,p,this.config.classes.length]),3):_(0);return[S,I,N]}),b=[],x=await h.array(),w=await l.array();for(let L=0;Ln){const A=(S+Lr(w[L][S][I][0]))/c*a,E=(L+Lr(w[L][S][I][1]))/c*s,M=Math.exp(w[L][S][I][2])*this.config.anchors[I].x/c*a,D=Math.exp(w[L][S][I][3])*this.config.anchors[I].y/c*s,$=A-M/2,B=E-D/2,j={row:L,col:S,anchor:I},{classScore:te,label:re}=this.withClassScores?await this.extractPredictedClass(d,j):{classScore:1,label:0};b.push(zs({box:new Rr($,B,$+M,B+D),score:N,classScore:N*te,label:re},j))}}return l.dispose(),h.dispose(),d.dispose(),b}async extractPredictedClass(e,t){const{row:n,col:r,anchor:o}=t,i=await e.array();return Array(this.config.classes.length).fill(0).map((a,s)=>i[n][r][o][s]).map((a,s)=>({classScore:a,label:s})).reduce((a,s)=>a.classScore>s.classScore?a:s)}}ro.DEFAULT_FILTER_SIZES=[3,16,32,64,128,256,512,1024,1024];class xr extends ro{constructor(e=!0){const t=Object.assign({},{withSeparableConvs:e,iouThreshold:Db,classes:["face"]},e?{anchors:Mb,meanRgb:Ub}:{anchors:Fb,withClassScores:!0});super(t)}get withSeparableConvs(){return this.config.withSeparableConvs}get anchors(){return this.config.anchors}async locateFaces(e,t){const n=await this.detect(e,t);return n.map(r=>new fe(r.score,r.relativeBox,{width:r.imageWidth,height:r.imageHeight}))}getDefaultModelName(){return this.withSeparableConvs?Bb:Wb}extractParamsFromWeigthMap(e){return super.extractParamsFromWeigthMap(e)}}function Fu(e,t=!0){const n=new xr(t);return n.extractWeights(e),n}class Qs extends Wt{constructor(){super(...arguments);this._name="TinyFaceDetectorOptions"}}class xt{async then(e){return e(await this.run())}async run(){throw new Error("ComposableTask - run is not implemented")}}async function br(e,t,n,r,o=({alignedRect:i})=>i){const i=e.map(c=>dn(c)?o(c):c.detection),a=r||(t instanceof ee?await Cn(t,i):await _n(t,i)),s=await n(a);return a.forEach(c=>c instanceof ee&&c.dispose()),s}async function oo(e,t,n,r,o){return br([e],t,async i=>n(i[0]),r,o)}const Gb=.4,Pb=[new J(1.603231,2.094468),new J(6.041143,7.080126),new J(2.882459,3.518061),new J(4.266906,5.178857),new J(9.041765,10.66308)],qb=[117.001,114.697,97.404];class yr extends ro{constructor(){const e={withSeparableConvs:!0,iouThreshold:Gb,classes:["face"],anchors:Pb,meanRgb:qb,isFirstLayerConv2d:!0,filterSizes:[3,16,32,64,128,256,512]};super(e)}get anchors(){return this.config.anchors}async locateFaces(e,t){const n=await this.detect(e,t);return n.map(r=>new fe(r.score,r.relativeBox,{width:r.imageWidth,height:r.imageHeight}))}getDefaultModelName(){return"tiny_face_detector_model"}extractParamsFromWeigthMap(e){return super.extractParamsFromWeigthMap(e)}}const oe={ssdMobilenetv1:new Nn(),tinyFaceDetector:new yr(),tinyYolov2:new xr(),faceLandmark68Net:new Sr(),faceLandmark68TinyNet:new ha(),faceRecognitionNet:new vr(),faceExpressionNet:new da(),ageGenderNet:new La()},vc=(e,t)=>oe.ssdMobilenetv1.locateFaces(e,t),ju=(e,t)=>oe.tinyFaceDetector.locateFaces(e,t),Gu=(e,t)=>oe.tinyYolov2.locateFaces(e,t),Sc=e=>oe.faceLandmark68Net.detectLandmarks(e),Pu=e=>oe.faceLandmark68TinyNet.detectLandmarks(e),qu=e=>oe.faceRecognitionNet.computeFaceDescriptor(e),Hu=e=>oe.faceExpressionNet.predictExpressions(e),zu=e=>oe.ageGenderNet.predictAgeAndGender(e),Ic=e=>oe.ssdMobilenetv1.load(e),Yu=e=>oe.tinyFaceDetector.load(e),Vu=e=>oe.tinyYolov2.load(e),Ku=e=>oe.faceLandmark68Net.load(e),Ju=e=>oe.faceLandmark68TinyNet.load(e),Xu=e=>oe.faceRecognitionNet.load(e),Zu=e=>oe.faceExpressionNet.load(e),Qu=e=>oe.ageGenderNet.load(e),ed=Ic,td=vc,nd=Sc;class Hb extends xt{constructor(e,t,n){super();this.parentTask=e,this.input=t,this.extractedFaces=n}}class Ps extends Hb{async run(){const e=await this.parentTask,t=await br(e,this.input,async n=>await Promise.all(n.map(r=>oe.faceExpressionNet.predictExpressions(r))),this.extractedFaces);return e.map((n,r)=>uo(n,t[r]))}withAgeAndGender(){return new js(this,this.input)}}class qs extends Hb{async run(){const e=await this.parentTask;if(!e)return;const t=await oo(e,this.input,n=>oe.faceExpressionNet.predictExpressions(n),this.extractedFaces);return uo(e,t)}withAgeAndGender(){return new Gs(this,this.input)}}class ao extends Ps{withAgeAndGender(){return new io(this,this.input)}withFaceDescriptors(){return new hn(this,this.input)}}class co extends qs{withAgeAndGender(){return new so(this,this.input)}withFaceDescriptor(){return new un(this,this.input)}}class zb extends xt{constructor(e,t,n){super();this.parentTask=e,this.input=t,this.extractedFaces=n}}class js extends zb{async run(){const e=await this.parentTask,t=await br(e,this.input,async n=>await Promise.all(n.map(r=>oe.ageGenderNet.predictAgeAndGender(r))),this.extractedFaces);return e.map((n,r)=>{const{age:o,gender:i,genderProbability:a}=t[r];return fo(ho(n,i,a),o)})}withFaceExpressions(){return new Ps(this,this.input)}}class Gs extends zb{async run(){const e=await this.parentTask;if(!e)return;const{age:t,gender:n,genderProbability:r}=await oo(e,this.input,o=>oe.ageGenderNet.predictAgeAndGender(o),this.extractedFaces);return fo(ho(e,n,r),t)}withFaceExpressions(){return new qs(this,this.input)}}class io extends js{withFaceExpressions(){return new ao(this,this.input)}withFaceDescriptors(){return new hn(this,this.input)}}class so extends Gs{withFaceExpressions(){return new co(this,this.input)}withFaceDescriptor(){return new un(this,this.input)}}class pa extends xt{constructor(e,t){super();this.parentTask=e,this.input=t}}class hn extends pa{async run(){const e=await this.parentTask,t=await br(e,this.input,n=>Promise.all(n.map(r=>oe.faceRecognitionNet.computeFaceDescriptor(r))),null,n=>n.landmarks.align(null,{useDlibAlignment:!0}));return t.map((n,r)=>mo(e[r],n))}withFaceExpressions(){return new ao(this,this.input)}withAgeAndGender(){return new io(this,this.input)}}class un extends pa{async run(){const e=await this.parentTask;if(!e)return;const t=await oo(e,this.input,n=>oe.faceRecognitionNet.computeFaceDescriptor(n),null,n=>n.landmarks.align(null,{useDlibAlignment:!0}));return mo(e,t)}withFaceExpressions(){return new co(this,this.input)}withAgeAndGender(){return new so(this,this.input)}}class sa extends xt{constructor(e,t,n){super();this.parentTask=e,this.input=t,this.useTinyLandmarkNet=n}get landmarkNet(){return this.useTinyLandmarkNet?oe.faceLandmark68TinyNet:oe.faceLandmark68Net}}class aa extends sa{async run(){const e=await this.parentTask,t=e.map(o=>o.detection),n=this.input instanceof ee?await Cn(this.input,t):await _n(this.input,t),r=await Promise.all(n.map(o=>this.landmarkNet.detectLandmarks(o)));return n.forEach(o=>o instanceof ee&&o.dispose()),e.map((o,i)=>Rn(o,r[i]))}withFaceExpressions(){return new ao(this,this.input)}withAgeAndGender(){return new io(this,this.input)}withFaceDescriptors(){return new hn(this,this.input)}}class ca extends sa{async run(){const e=await this.parentTask;if(!e)return;const{detection:t}=e,n=this.input instanceof ee?await Cn(this.input,[t]):await _n(this.input,[t]),r=await this.landmarkNet.detectLandmarks(n[0]);return n.forEach(o=>o instanceof ee&&o.dispose()),Rn(e,r)}withFaceExpressions(){return new co(this,this.input)}withAgeAndGender(){return new so(this,this.input)}withFaceDescriptor(){return new un(this,this.input)}}class oa extends xt{constructor(e,t=new bt()){super();this.input=e,this.options=t}}class lo extends oa{async run(){const{input:e,options:t}=this,n=t instanceof Qs?r=>oe.tinyFaceDetector.locateFaces(r,t):t instanceof bt?r=>oe.ssdMobilenetv1.locateFaces(r,t):t instanceof Wt?r=>oe.tinyYolov2.locateFaces(r,t):null;if(!n)throw new Error("detectFaces - expected options to be instance of TinyFaceDetectorOptions | SsdMobilenetv1Options | MtcnnOptions | TinyYolov2Options");return n(e)}runAndExtendWithFaceDetections(){return new Promise(async e=>{const t=await this.run();return e(t.map(n=>mn({},n)))})}withFaceLandmarks(e=!1){return new aa(this.runAndExtendWithFaceDetections(),this.input,e)}withFaceExpressions(){return new Ps(this.runAndExtendWithFaceDetections(),this.input)}withAgeAndGender(){return new js(this.runAndExtendWithFaceDetections(),this.input)}}class ia extends oa{async run(){const e=await new lo(this.input,this.options);let t=e[0];return e.forEach(n=>{n.score>t.score&&(t=n)}),t}runAndExtendWithFaceDetection(){return new Promise(async e=>{const t=await this.run();return e(t?mn({},t):void 0)})}withFaceLandmarks(e=!1){return new ca(this.runAndExtendWithFaceDetection(),this.input,e)}withFaceExpressions(){return new qs(this.runAndExtendWithFaceDetection(),this.input)}withAgeAndGender(){return new Gs(this.runAndExtendWithFaceDetection(),this.input)}}function rd(e,t=new bt()){return new ia(e,t)}function po(e,t=new bt()){return new lo(e,t)}async function Tc(e,t){return console.warn("allFacesSsdMobilenetv1 is deprecated and will be removed soon, use the high level api instead"),await po(e,new bt(t?{minConfidence:t}:{})).withFaceLandmarks().withFaceDescriptors()}async function od(e,t={}){return console.warn("allFacesTinyYolov2 is deprecated and will be removed soon, use the high level api instead"),await po(e,new Wt(t)).withFaceLandmarks().withFaceDescriptors()}const id=Tc;function ma(e,t){if(e.length!==t.length)throw new Error("euclideanDistance: arr1.length !== arr2.length");const n=Array.from(e),r=Array.from(t);return Math.sqrt(n.map((o,i)=>o-r[i]).reduce((o,i)=>o+Math.pow(i,2),0))}class Ac{constructor(e,t=.6){this._distanceThreshold=t;const n=Array.isArray(e)?e:[e];if(!n.length)throw new Error("FaceRecognizer.constructor - expected atleast one input");let r=1;const o=()=>`person ${r++}`;this._labeledDescriptors=n.map(i=>{if(i instanceof xn)return i;if(i instanceof Float32Array)return new xn(o(),[i]);if(i.descriptor&&i.descriptor instanceof Float32Array)return new xn(o(),[i.descriptor]);throw new Error("FaceRecognizer.constructor - expected inputs to be of type LabeledFaceDescriptors | WithFaceDescriptor | Float32Array | Array | Float32Array>")})}get labeledDescriptors(){return this._labeledDescriptors}get distanceThreshold(){return this._distanceThreshold}computeMeanDistance(e,t){return t.map(n=>ma(n,e)).reduce((n,r)=>n+r,0)/(t.length||1)}matchDescriptor(e){return this.labeledDescriptors.map(({descriptors:t,label:n})=>new wo(n,this.computeMeanDistance(e,t))).reduce((t,n)=>t.distancee.toJSON())}}static fromJSON(e){const t=e.labeledDescriptors.map(n=>xn.fromJSON(n));return new Ac(t,e.distanceThreshold)}}function Mu(e){const t=new yr();return t.extractWeights(e),t}function Lc(e,t){const{width:n,height:r}=new Qe(t.width,t.height);if(n<=0||r<=0)throw new Error(`resizeResults - invalid dimensions: ${JSON.stringify({width:n,height:r})}`);if(Array.isArray(e))return e.map(o=>Lc(o,{width:n,height:r}));if(dn(e)){const o=e.detection.forSize(n,r),i=e.unshiftedLandmarks.forSize(o.box.width,o.box.height);return Rn(mn(e,o),i)}return Nt(e)?mn(e,e.detection.forSize(n,r)):e instanceof st||e instanceof fe?e.forSize(n,r):e}return fd();})();
/**
* @license
* Copyright 2017 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/** @license See the LICENSE file. */
//# sourceMappingURL=face-api.min.js.map