face-api/dist/face-api.min.js

100 lines
321 KiB
JavaScript

var faceapi=(()=>{var zs=Object.defineProperty,Jb=Object.prototype.hasOwnProperty,Ys=Object.assign,At=(e,t)=>()=>(t||(t={exports:{}},e(t.exports,t)),t.exports),fu=e=>zs(e,"__esModule",{value:!0}),Re=(e,t)=>{fu(e);for(var n in t)zs(e,n,{get:t[n],enumerable:!0})},Xb=(e,t)=>{if(fu(e),typeof t=="object"||typeof t=="function")for(let n in t)!Jb.call(e,n)&&n!=="default"&&zs(e,n,{get:()=>t[n],enumerable:!0});return e},gu=e=>e&&e.__esModule?e:Xb(zs({},"default",{value:e,enumerable:!0}),e);var wu=At((bu,fc)=>{(function(e,t,n){function o(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 r(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 o(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"&&r(l,p),h.state=function(){return r(p,{})}),h}function a(){var s=4022871197,c=function(p){p=p.toString();for(var l=0;l<p.length;l++){s+=p.charCodeAt(l);var h=.02519603282416938*s;s=h>>>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})(bu,typeof fc=="object"&&fc,typeof define=="function"&&define)});var yu=At((xu,gc)=>{(function(e,t,n){function o(a){var s=this,c="";s.x=0,s.y=0,s.z=0,s.w=0,s.next=function(){var l=s.x^s.x<<11;return s.x=s.y,s.y=s.z,s.z=s.w,s.w^=s.w>>>19^l^l>>>8},a===(a|0)?s.x=a:c+=a;for(var p=0;p<c.length+64;p++)s.x^=c.charCodeAt(p)|0,s.next()}function r(a,s){return s.x=a.x,s.y=a.y,s.z=a.z,s.w=a.w,s}function i(a,s){var c=new o(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"&&r(p,c),l.state=function(){return r(c,{})}),l}t&&t.exports?t.exports=i:n&&n.amd?n(function(){return i}):this.xor128=i})(xu,typeof gc=="object"&&gc,typeof define=="function"&&define)});var vu=At((Lu,bc)=>{(function(e,t,n){function o(a){var s=this,c="";s.next=function(){var l=s.x^s.x>>>2;return s.x=s.y,s.y=s.z,s.z=s.w,s.w=s.v,(s.d=s.d+362437|0)+(s.v=s.v^s.v<<4^(l^l<<1))|0},s.x=0,s.y=0,s.z=0,s.w=0,s.v=0,a===(a|0)?s.x=a:c+=a;for(var p=0;p<c.length+64;p++)s.x^=c.charCodeAt(p)|0,p==c.length&&(s.d=s.x<<10^s.x>>>4),s.next()}function r(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 o(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"&&r(p,c),l.state=function(){return r(c,{})}),l}t&&t.exports?t.exports=i:n&&n.amd?n(function(){return i}):this.xorwow=i})(Lu,typeof bc=="object"&&bc,typeof define=="function"&&define)});var Iu=At((Su,wc)=>{(function(e,t,n){function o(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;h<l.length;++h)b[h&7]=b[h&7]<<15^l.charCodeAt(h)+b[h+1&7]<<13;for(;b.length<8;)b.push(0);for(h=0;h<8&&b[h]===0;++h);for(h==8?d=b[7]=-1:d=b[h],p.x=b,p.i=0,h=256;h>0;--h)p.next()}c(s,a)}function r(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 o(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&&r(p,c),l.state=function(){return r(c,{})}),l}t&&t.exports?t.exports=i:n&&n.amd?n(function(){return i}):this.xorshift7=i})(Su,typeof wc=="object"&&wc,typeof define=="function"&&define)});var Au=At((Tu,xc)=>{(function(e,t,n){function o(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<S;++x)l&&(d^=l.charCodeAt((x+32)%l.length)),x===0&&(w=d),d^=d<<10,d^=d>>>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 r(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 o(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&&r(p,c),l.state=function(){return r(c,{})}),l}t&&t.exports?t.exports=i:n&&n.amd?n(function(){return i}):this.xor4096=i})(Tu,typeof xc=="object"&&xc,typeof define=="function"&&define)});var Ru=At((Nu,yc)=>{(function(e,t,n){function o(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<c.length+20;p++)s.b^=c.charCodeAt(p)|0,s.next()}function r(a,s){return s.a=a.a,s.b=a.b,s.c=a.c,s.d=a.d,s}function i(a,s){var c=new o(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"&&r(p,c),l.state=function(){return r(c,{})}),l}t&&t.exports?t.exports=i:n&&n.amd?n(function(){return i}):this.tychei=i})(Nu,typeof yc=="object"&&yc,typeof define=="function"&&define)});var _u=At(()=>{});var Cu=At((DT,Vs)=>{(function(e,t){var n=this,o=256,r=6,i=52,a="random",s=t.pow(o,r),c=t.pow(2,i),p=c*2,l=o-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(r),te=s,oe=0;j<c;)j=(j+oe)*o,te*=o,oe=$.g(1);for(;j>=p;)j/=2,te/=2,oe>>>=1;return(j+oe)/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,oe,he){return he&&(he.S&&x(he,$),j.state=function(){return x($,{})}),oe?(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<o;)B[D]=D++;for(D=0;D<o;D++)B[D]=B[$=l&$+N[D%E]+(A=B[D])],B[$]=A;(M.g=function(j){for(var te,oe=0,he=M.i,ye=M.j,Me=M.S;j--;)te=Me[he=l&he+1],oe=oe*o+Me[l&(Me[he]=Me[ye=l&ye+te])+(Me[ye]=te)];return M.i=he,M.j=ye,oe})(o)}function x(N,A){return A.i=N.i,A.j=N.j,A.S=N.S.slice(),A}function w(N,A){var E=[],M=typeof N,D;if(A&&M=="object")for(D in N)try{E.push(w(N[D],A-1))}catch($){}return E.length?E:M=="string"?N:N+"\0"}function L(N,A){for(var E=N+"",M,D=0;D<E.length;)A[l&D]=l&(M^=A[l&D]*19)+E.charCodeAt(D++);return I(A)}function S(){try{var N;return h&&(N=h.randomBytes)?N=N(o):(N=new Uint8Array(o),(n.crypto||n.msCrypto).getRandomValues(N)),I(N)}catch(M){var A=n.navigator,E=A&&A.plugins;return[+new Date,n,E,n.screen,I(e)]}}function I(N){return String.fromCharCode.apply(0,N)}if(L(t.random(),e),typeof Vs=="object"&&Vs.exports){Vs.exports=d;try{h=_u()}catch(N){}}else typeof define=="function"&&define.amd&&define(function(){return d})})([],Math)});var Ou=At((FT,Eu)=>{var Zb=wu(),Qb=yu(),ew=vu(),tw=Iu(),nw=Au(),ow=Ru(),An=Cu();An.alea=Zb;An.xor128=Qb;An.xorwow=ew;An.xorshift7=tw;An.xor4096=nw;An.tychei=ow;Eu.exports=An});var Du=At((rw,ku)=>{Re(rw,{isNodejs:()=>iw});function iw(){return typeof global=="object"&&!0&&typeof ku!="undefined"&&typeof process!="undefined"&&!!process.version}});var bd=At(sw=>{Re(sw,{AgeGenderNet:()=>va,BoundingBox:()=>_o,Box:()=>de,ComposableTask:()=>xt,ComputeAllFaceDescriptorsTask:()=>hn,ComputeFaceDescriptorsTaskBase:()=>la,ComputeSingleFaceDescriptorTask:()=>un,DetectAllFaceLandmarksTask:()=>ca,DetectAllFacesTask:()=>ur,DetectFaceLandmarksTaskBase:()=>aa,DetectFacesTaskBase:()=>ia,DetectSingleFaceLandmarksTask:()=>pa,DetectSingleFaceTask:()=>sa,Dimensions:()=>Qe,FACE_EXPRESSION_LABELS:()=>da,FaceDetection:()=>fe,FaceDetectionNet:()=>$u,FaceExpressionNet:()=>ma,FaceExpressions:()=>fn,FaceLandmark68Net:()=>Io,FaceLandmark68TinyNet:()=>ua,FaceLandmarkNet:()=>hd,FaceLandmarks:()=>st,FaceLandmarks5:()=>gd,FaceLandmarks68:()=>Ro,FaceMatch:()=>xr,FaceMatcher:()=>Rc,FaceRecognitionNet:()=>So,Gender:()=>Bt,LabeledBox:()=>wr,LabeledFaceDescriptors:()=>xn,NetInput:()=>Jt,NeuralNetwork:()=>Ue,ObjectDetection:()=>On,Point:()=>J,PredictedBox:()=>fd,Rect:()=>No,SsdMobilenetv1:()=>Nn,SsdMobilenetv1Options:()=>bt,TinyFaceDetector:()=>Lo,TinyFaceDetectorOptions:()=>ea,TinyYolov2:()=>yo,TinyYolov2Options:()=>Wt,TinyYolov2SizeType:()=>Qs,allFaces:()=>ad,allFacesSsdMobilenetv1:()=>Nc,allFacesTinyYolov2:()=>sd,awaitMediaLoaded:()=>La,bufferToImage:()=>ya,computeFaceDescriptor:()=>zu,createCanvas:()=>En,createCanvasFromMedia:()=>Ao,createFaceDetectionNet:()=>Bu,createFaceRecognitionNet:()=>ld,createSsdMobilenetv1:()=>vc,createTinyFaceDetector:()=>Wu,createTinyYolov2:()=>Uu,detectAllFaces:()=>hr,detectFaceLandmarks:()=>Tc,detectFaceLandmarksTiny:()=>Hu,detectLandmarks:()=>rd,detectSingleFace:()=>id,draw:()=>Js,env:()=>se,euclideanDistance:()=>fa,extendWithAge:()=>gr,extendWithFaceDescriptor:()=>fr,extendWithFaceDetection:()=>mn,extendWithFaceExpressions:()=>mr,extendWithFaceLandmarks:()=>Rn,extendWithGender:()=>dr,extractFaceTensors:()=>Cn,extractFaces:()=>_n,fetchImage:()=>md,fetchJson:()=>xa,fetchNetWeights:()=>dd,fetchOrThrow:()=>wn,getContext2dOrThrow:()=>He,getMediaDimensions:()=>bn,imageTensorToCanvas:()=>wa,imageToSquare:()=>ba,inverseSigmoid:()=>Gu,iou:()=>ra,isMediaElement:()=>br,isMediaLoaded:()=>To,isWithAge:()=>pd,isWithFaceDetection:()=>Nt,isWithFaceExpressions:()=>ha,isWithFaceLandmarks:()=>dn,isWithGender:()=>cd,loadAgeGenderModel:()=>td,loadFaceDetectionModel:()=>nd,loadFaceExpressionModel:()=>ed,loadFaceLandmarkModel:()=>Xu,loadFaceLandmarkTinyModel:()=>Zu,loadFaceRecognitionModel:()=>Qu,loadSsdMobilenetv1Model:()=>Ac,loadTinyFaceDetectorModel:()=>Ku,loadTinyYolov2Model:()=>Ju,loadWeightMap:()=>ga,locateFaces:()=>od,matchDimensions:()=>ud,minBbox:()=>oa,nets:()=>re,nonMaxSuppression:()=>na,normalize:()=>wt,padToSquare:()=>ta,predictAgeAndGender:()=>Vu,recognizeFaceExpressions:()=>Yu,resizeResults:()=>Sc,resolveInput:()=>gn,shuffleArray:()=>ju,sigmoid:()=>vo,ssdMobilenetv1:()=>Ic,tf:()=>Ks,tinyFaceDetector:()=>Pu,tinyYolov2:()=>qu,toNetInput:()=>ue,utils:()=>Xs,validateConfig:()=>Zs,version:()=>Mu});const Mu={faceapi:Fu,tfjs_core:Lc,env:lr.getFlags()}});const wd="tfjsflags";class _c{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 o=this.urlFlags[e];console.warn(`Setting feature override from URL ${e}: ${o}.`),this.set(e,o)}}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=aw(this.global.location.search);if(wd in e){const t=e[wd].split(",");t.forEach(n=>{const[o,r]=n.split(":");this.urlFlags[o]=cw(o,r)})}}}function aw(e){const t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(n,...o)=>(pw(t,o[0],o[1]),o.join("="))),t}function pw(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}function cw(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 lr}let lr=null;function xd(e){lr=e}let Cc;function Ec(){if(Cc==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");Cc=e}return Cc}function lw(){const e=Ec();return e._tfGlobals==null&&(e._tfGlobals=new Map),e._tfGlobals}function Oc(e,t){const n=lw();if(n.has(e))return n.get(e);{const o=t();return n.set(e,o),n.get(e)}}const yr="Abs",Lr="Acos",vr="Acosh",kn="Add",Sr="AddN",kc="All",Dc="Any",Ir="ArgMax",Tr="ArgMin",Ar="Asin",Nr="Asinh",Rr="Atan",_r="Atanh",Cr="Atan2",Er="AvgPool",Fc="AvgPoolBackprop",Or="AvgPool3D",Mc="AvgPool3DBackprop",kr="BatchMatMul",Dr="BatchToSpaceND",Fr="BroadcastTo",Dn="Cast",Mr="Ceil",Ur="ClipByValue",Uc="Complex",Wr="Concat",Br="Conv2D",Wc="Conv2DBackpropFilter",$r="Conv2DBackpropInput",jr="Conv3D",Bc="Conv3DBackpropFilterV2",$c="Conv3DBackpropInputV2",Gr="Cos",Pr="Cosh",qr="Cumsum",jc="CropAndResize",Gc="DepthToSpace",Hr="DepthwiseConv2dNative",Pc="DepthwiseConv2dNativeBackpropFilter",qc="DepthwiseConv2dNativeBackpropInput",Hc="Diag",zr="Dilation2D",zc="Dilation2DBackpropInput",Yc="Dilation2DBackpropFilter",Yr="Div",Vr="Elu",Vc="EluGrad",Kr="Erf",Kc="Equal",Jr="Exp",Xr="Expm1",Jc="FFT",Xc="Fill",Zc="FlipLeftRight",Zr="Floor",Qr="FloorDiv",ei="FusedBatchNorm",ti="GatherV2",Qc="GatherNd",ep="Greater",ni="GreaterEqual",oi="Identity",tp="IFFT",np="Imag",ri="IsFinite",ii="IsInf",si="IsNan",op="Less",rp="LessEqual",ip="LinSpace",ai="Log",ci="Log1p",sp="LogicalAnd",ap="LogicalNot",cp="LogicalOr",pi="LogSoftmax",li="LRN",pp="LRNBackprop",hi="Max",ui="Maximum",di="MaxPool",lp="MaxPoolBackprop",mi="MaxPool3D",hp="MaxPool3DBackprop",up="MaxPoolWithArgmax",hw="Mean",fi="Min",gi="Minimum",bi="Mod",wi="Multiply",xi="Negate",dp="NotEqual",mp="NonMaxSuppressionV3",fp="NonMaxSuppressionV4",gp="NonMaxSuppressionV5",yi="OnesLike",Li="OneHot",vi="PadV2",uw="Pool",Si="Pow",Ii="Prelu",bp="Prod",wp="Range",xp="Real",Ti="Reciprocal",Ai="Relu",Ni="Reshape",Ri="ResizeNearestNeighbor",yp="ResizeNearestNeighborGrad",_i="ResizeBilinear",Lp="ResizeBilinearGrad",Ci="Relu6",Ei="Reverse",Oi="Round",ki="Rsqrt",vp="ScatterNd",Di="SelectV2",Fi="Selu",Mi="Slice",Ui="Sin",Wi="Sinh",Bi="Sign",$i="Sigmoid",ji="Softplus",Gi="Sqrt",Pi="Sum",qi="SpaceToBatchND",Hi="SplitV",zi="Softmax",Yi="SquaredDifference",Sp="Square",Vi="Sub",Ip="SparseToDense",Tp="StridedSlice",Ki="Tan",Ji="Tanh",Xi="Tile",Ap="TopK",Zi="Transpose",Qi="Unpack",es="UnsortedSegmentSum",ts="ZerosLike",ns="Step",Sa="FromPixels",Np="RotateWithOffset",Ia="_FusedMatMul",Ta="FusedConv2D",Aa="FusedDepthwiseConv2D";const Co=Oc("kernelRegistry",()=>new Map),os=Oc("gradRegistry",()=>new Map);function rs(e,t){const n=Rp(e,t);return Co.get(n)}function Na(e){return os.get(e)}function Ra(e){const t=Co.entries(),n=[];for(;;){const{done:o,value:r}=t.next();if(o)break;const[i,a]=r,[s]=i.split("_");s===e&&n.push(a)}return n}function dw(e){const{kernelName:t,backendName:n}=e,o=Rp(t,n);Co.has(o)&&console.warn(`The kernel '${t}' for backend '${n}' is already registered`),Co.set(o,e)}function _p(e){const{kernelName:t}=e;os.has(t)&&(pe().getBool("DEBUG")&&console.warn(`Overriding the gradient for '${t}'`)),os.set(t,e)}function mw(e,t){const n=Rp(e,t);if(!Co.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);Co.delete(n)}function fw(e){if(!os.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);os.delete(e)}function Rp(e,t){return`${t}_${e}`}const yd={};Re(yd,{arraysEqual:()=>Te,assert:()=>f,assertNonNegativeIntegerDimensions:()=>as,assertNonNull:()=>at,assertShapesMatch:()=>P,bytesFromStringArray:()=>Mp,bytesPerElement:()=>Fp,checkConversionForErrors:()=>vd,clamp:()=>Eo,computeStrides:()=>Gt,createShuffledIndices:()=>Sw,decodeString:()=>Ca,distSquared:()=>xw,encodeString:()=>Up,fetch:()=>Nw,flatten:()=>$t,getArrayFromDType:()=>Op,getTypedArrayFromDType:()=>Oo,hasEncodingLoss:()=>Dp,indexToLoc:()=>_w,inferDtype:()=>ko,inferFromImplicitShape:()=>Cp,isBoolean:()=>Sd,isFunction:()=>jt,isInt:()=>X,isNumber:()=>Id,isScalarShape:()=>yw,isString:()=>Rt,isTypedArray:()=>_e,isValidDtype:()=>kp,locToIndex:()=>Rw,makeOnesTypedArray:()=>ss,makeZerosNestedTypedArray:()=>Aw,makeZerosTypedArray:()=>Pt,nearestDivisor:()=>Do,nearestLargerEven:()=>gw,now:()=>_a,parseAxisParam:()=>z,randUniform:()=>ww,repeatedTry:()=>Iw,rightPad:()=>Fn,shuffle:()=>Ld,sizeFromShape:()=>Q,sizeToSquarishShape:()=>vw,squeezeShape:()=>Ep,sum:()=>bw,tanh:()=>Lw,toNestedArray:()=>Mn,toTypedArray:()=>is});function Ld(e){let t=e.length,n=0,o=0;for(;t>0;)o=Math.random()*t|0,t--,n=e[t],e[t]=e[o],e[o]=n}function Eo(e,t,n){return Math.max(e,Math.min(t,n))}function gw(e){return e%2===0?e:e+1}function bw(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t}function ww(e,t){const n=Math.random();return t*n+(1-n)*e}function xw(e,t){let n=0;for(let o=0;o<e.length;o++){const r=Number(e[o])-Number(t[o]);n+=r*r}return n}function f(e,t){if(!e)throw new Error(typeof t=="string"?t:t())}function P(e,t,n=""){f(Te(e,t),()=>n+` 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 o=0;o<e.length;++o)$t(e[o],t,n);else t.push(e);return t}function Q(e){if(e.length===0)return 1;let t=e[0];for(let n=1;n<e.length;n++)t*=e[n];return t}function yw(e){return e.length===0}function Te(e,t){if(e===t)return!0;if(e==null||t==null)return!1;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function X(e){return e%1===0}function Lw(e){if(Math.tanh!=null)return Math.tanh(e);if(e===Infinity)return 1;if(e===-Infinity)return-1;{const t=Math.exp(2*e);return(t-1)/(t+1)}}function vw(e){const t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function Sw(e){const t=new Uint32Array(e);for(let n=0;n<e;++n)t[n]=n;return Ld(t),t}function Fn(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function Iw(e,t=o=>0,n){return new Promise((o,r)=>{let i=0;const a=()=>{if(e()){o();return}i++;const s=t(i);if(n!=null&&i>=n){r();return}setTimeout(a,s)};a()})}function Cp(e,t){let n=1,o=-1;for(let i=0;i<e.length;++i)if(e[i]>=0)n*=e[i];else if(e[i]===-1){if(o!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${o} and dim ${i}`);o=i}else if(e[i]<0)throw Error(`Shapes can not be < 0. Found ${e[i]} at dim ${i}`);if(o===-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 r=e.slice();return r[o]=t/n,r}function z(e,t){const n=t.length;return e=e==null?t.map((o,r)=>r):[].concat(e),f(e.every(o=>o>=-n&&o<n),()=>`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`),f(e.every(o=>X(o)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(o=>o<0?n+o:o)}function Ep(e,t){const n=[],o=[],r=t!=null&&Array.isArray(t)&&t.length===0,i=t==null||r?null:z(t,e).sort();let a=0;for(let s=0;s<e.length;++s){if(i!=null){if(i[a]===s&&e[s]!==1)throw new Error(`Can't squeeze axis ${s} since its dim '${e[s]}' is not 1`);(i[a]==null||i[a]>s)&&e[s]===1&&(n.push(e[s]),o.push(s)),i[a]<=s&&a++}e[s]!==1&&(n.push(e[s]),o.push(s))}return{newShape:n,keptDims:o}}function Oo(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 Op(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 vd(e,t){for(let n=0;n<e.length;n++){const o=e[n];if(isNaN(o)||!isFinite(o))throw Error(`A tensor of type ${t} being uploaded contains ${o}.`)}}function kp(e){return e==="bool"||e==="complex64"||e==="float32"||e==="int32"||e==="string"}function Dp(e,t){return t==="complex64"||(t==="float32"&&e!=="complex64"||t==="int32"&&e!=="float32"&&e!=="complex64")?!1:!(t==="bool"&&e==="bool")}function _e(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array}function Fp(e){if(e==="float32"||e==="int32")return 4;if(e==="complex64")return 8;if(e==="bool")return 1;throw new Error(`Unknown dtype ${e}`)}function Mp(e){if(e==null)return 0;let t=0;return e.forEach(n=>t+=n.length),t}function Rt(e){return typeof e=="string"||e instanceof String}function Sd(e){return typeof e=="boolean"}function Id(e){return typeof e=="number"}function ko(e){return Array.isArray(e)?ko(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array?"int32":Id(e)?"float32":Rt(e)?"string":Sd(e)?"bool":"float32"}function jt(e){return!!(e&&e.constructor&&e.call&&e.apply)}function Do(e,t){for(let n=t;n<e;++n)if(e%n===0)return n;return e}function Gt(e){const t=e.length;if(t<2)return[];const n=new Array(t-1);n[t-2]=e[t-1];for(let o=t-3;o>=0;--o)n[o]=n[o+1]*e[o+1];return n}function is(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")&&vd(e,t),Tw(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 o=0;o<n.length;++o)Math.round(e[o])!==0&&(n[o]=1);return n}else throw new Error(`Unknown data type ${t}`)}function Td(e,t,n){const o=new Array;if(t.length===1){const r=t[0];for(let i=0;i<r;i++)o[i]=n[e+i]}else{const r=t[0],i=t.slice(1),a=i.reduce((s,c)=>s*c);for(let s=0;s<r;s++)o[s]=Td(e+s*a,i,n)}return o}function Mn(e,t){if(e.length===0)return t[0];const n=e.reduce((o,r)=>o*r);if(n===0)return[];if(n!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}.`);return Td(0,e,t)}function Tw(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function ss(e,t){const n=Pt(e,t);for(let o=0;o<n.length;o++)n[o]=1;return n}function Pt(e,t){if(t==null||t==="float32"||t==="complex64")return new Float32Array(e);if(t==="int32")return new Int32Array(e);if(t==="bool")return new Uint8Array(e);throw new Error(`Unknown data type ${t}`)}function Aw(e,t){const n=e.reduce((o,r)=>o*r,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 _a(){return pe().platform.now()}function as(e){e.forEach(t=>{f(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function Nw(e,t){return pe().platform.fetch(e,t)}function Up(e,t="utf-8"){return t=t||"utf-8",pe().platform.encode(e,t)}function Ca(e,t="utf-8"){return t=t||"utf-8",pe().platform.decode(e,t)}function Rw(e,t,n){if(t===0)return 0;if(t===1)return e[0];let o=e[e.length-1];for(let r=0;r<e.length-1;++r)o+=n[r]*e[r];return o}function _w(e,t,n){if(t===0)return[];if(t===1)return[e];const o=new Array(t);for(let r=0;r<o.length-1;++r)o[r]=Math.floor(e/n[r]),e-=o[r]*n[r];return o[o.length-1]=e,o}class Ad{constructor(e,t){this.backendTimer=e,this.logger=t,t==null&&(this.logger=new Ew)}profileKernel(e,t,n){let o;const r=()=>{o=n()},i=this.backendTimer.time(r);o.map(s=>{s.data().then(c=>{Cw(c,s.dtype,e)})});const a={kernelName:e,outputs:o,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:o,inputs:r,extraInfo:i}=e;n.forEach(a=>{Promise.all([a.data(),o,i]).then(s=>{this.logger.logKernelProfile(t,a,s[0],s[1],r,s[2])})})}}function Cw(e,t,n){if(t!=="float32")return!1;for(let o=0;o<e.length;o++){const r=e[o];if(isNaN(r)||!isFinite(r))return console.warn(`Found ${r} in the result of '${n}'`),!0}return!1}class Ew{logKernelProfile(e,t,n,o,r,i){const a=typeof o=="number"?Fn(`${o}ms`,9):o.error,s=Fn(e,25),c=t.rank,p=t.size,l=Fn(t.shape.toString(),14);let h="";for(const d in r){const b=r[d];if(b!=null){const x=b.shape||t.shape,w=x.length;h+=`${d}: ${w}D ${w>0?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 Nd(e,t,n){const o={},r={};for(let c=0;c<t.length;c++)o[t[c].id]=!0;for(let c=0;c<e.length;c++){const p=e[c],l=p.inputs;for(const h in l){const d=l[h];let b=!1;for(let x=0;x<t.length;x++)if(o[d.id]){p.outputs.forEach(w=>o[w.id]=!0),b=!0,r[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<p.outputs.length;h++)if(i[p.outputs[h].id]){for(const d in l)i[l[d].id]=!0,a[p.id]=!0;break}}const s=[];for(let c=0;c<e.length;c++){const p=e[c];if(r[p.id]&&a[p.id]){const l={};for(const d in p.inputs){const b=p.inputs[d];o[b.id]&&(l[d]=b)}const h=Object.assign({},p);h.inputs=l,h.outputs=p.outputs,s.push(h)}}return s}function Rd(e,t,n,o){for(let r=t.length-1;r>=0;r--){const i=t[r],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]=o(h,p),h.dispose()}}}}const _d=20,cs=3,Wp=7;function Cd(e,t,n,o){const r=Gt(t),i=Ow(e,t,n,r),a=t.length,s=Ea(e,t,n,r,i),c=["Tensor"];return o&&(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 Ow(e,t,n,o){const r=Q(t),i=o[o.length-1],a=new Array(i).fill(0),s=t.length,c=n==="complex64"?ls(e):e;if(s>1)for(let p=0;p<r/i;p++){const l=p*i;for(let h=0;h<i;h++)a[h]=Math.max(a[h],ps(c[l+h],0,n).length)}return a}function ps(e,t,n){let o;return Array.isArray(e)?o=`${parseFloat(e[0].toFixed(Wp))} + ${parseFloat(e[1].toFixed(Wp))}j`:Rt(e)?o=`'${e}'`:n==="bool"?o=Ed(e):o=parseFloat(e.toFixed(Wp)).toString(),Fn(o,t)}function Ed(e){return e===0?"false":"true"}function Ea(e,t,n,o,r,i=!0){const a=n==="complex64"?2:1,s=t[0],c=t.length;if(c===0){if(n==="complex64"){const w=ls(e);return[ps(w[0],0,n)]}return n==="bool"?[Ed(e[0])]:[e[0].toString()]}if(c===1){if(s>_d){const L=cs*a;let S=Array.from(e.slice(0,L)),I=Array.from(e.slice((s-cs)*a,s*a));return n==="complex64"&&(S=ls(S),I=ls(I)),["["+S.map((N,A)=>ps(N,r[A],n)).join(", ")+", ..., "+I.map((N,A)=>ps(N,r[s-cs+A],n)).join(", ")+"]"]}const w=n==="complex64"?ls(e):Array.from(e);return["["+w.map((L,S)=>ps(L,r[S],n)).join(", ")+"]"]}const p=t.slice(1),l=o.slice(1),h=o[0]*a,d=[];if(s>_d){for(let w=0;w<cs;w++){const L=w*h,S=L+h;d.push(...Ea(e.slice(L,S),p,n,l,r,!1))}d.push("...");for(let w=s-cs;w<s;w++){const L=w*h,S=L+h;d.push(...Ea(e.slice(L,S),p,n,l,r,w===s-1))}}else for(let w=0;w<s;w++){const L=w*h,S=L+h;d.push(...Ea(e.slice(L,S),p,n,l,r,w===s-1))}const b=c===2?",":"";d[0]="["+d[0]+b;for(let w=1;w<d.length-1;w++)d[w]=" "+d[w]+b;let x=`,
`;for(let w=2;w<c;w++)x+=`
`;return d[d.length-1]=" "+d[d.length-1]+"]"+(i?"":x),d}function ls(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}class Fo{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=Q(e),n!=null){const o=n.length;f(o===this.size,()=>`Length of values '${o}' 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||Op(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 o of e){if(o<0||o>=this.shape[t]){const r=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(r)}t++}let n=e[e.length-1];for(let o=0;o<e.length-1;++o)n+=this.strides[o]*e[o];return this.values[n]}locToIndex(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];let t=e[e.length-1];for(let n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t}indexToLoc(e){if(this.rank===0)return[];if(this.rank===1)return[e];const t=new Array(this.shape.length);for(let n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return qt().makeTensor(this.values,this.shape,this.dtype)}}let qt=null,Mo=null,kw=null;function Od(e){qt=e}function kd(e){Mo=e}function Dd(e){kw=e}class ee{constructor(e,t,n,o){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=Q(e),this.strides=Gt(e),this.dataId=n,this.id=o,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){const e=await this.data();return Mo.buffer(this.shape,this.dtype,e)}bufferSync(){return Mo.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return Mn(this.shape,e)}arraySync(){return Mn(this.shape,this.dataSync())}async data(){this.throwIfDisposed();const e=qt().read(this.dataId);if(this.dtype==="string"){const t=await e;try{return t.map(n=>Ca(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=>Ca(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 Mo.print(this,e)}clone(){return this.throwIfDisposed(),Mo.clone(this)}toString(e=!1){const t=this.dataSync();return Cd(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Mo.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,o){super(e.shape,e.dtype,e.dataId,o);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 Bp;(function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"})(Bp||(Bp={}));var $p;(function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"})($p||($p={}));var jp;(function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"})(jp||(jp={}));var Gp;(function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"})(Gp||(Gp={}));var Pp;(function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"})(Pp||(Pp={}));const Dw={float32:Gp,int32:$p,bool:jp,complex64:Pp};function Uo(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return Dw[e][t]}function Fw(e){return Uo(e,"int32")}const Fd={};Re(Fd,{assertTypesMatch:()=>qp,getTensorsInContainer:()=>hs,isTensorInList:()=>Mw,makeTypesMatch:()=>V});function V(e,t){if(e.dtype===t.dtype)return[e,t];const n=Uo(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function qp(e,t){f(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function Mw(e,t){return t.some(n=>n.id===e.id)}function hs(e){const t=[],n=new Set;return Md(e,t,n),t}function Md(e,t,n){if(e==null)return;if(e instanceof ee){t.push(e);return}if(!Uw(e))return;const o=e;for(const r in o){const i=o[r];n.has(i)||(n.add(i),Md(i,t,n))}}function Uw(e){return Array.isArray(e)||typeof e=="object"}class Ud{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 us{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new Ud}async ready(){if(this.pendingBackendInit!=null)return this.pendingBackendInit.then(()=>{});if(this.backendInstance!=null)return;const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t],o=await this.initializeBackend(n).success;if(o){await this.setBackend(n);return}}throw new Error("Could not initialize any backends, all backend initializations failed.")}get backend(){if(this.pendingBackendInit!=null)throw new Error(`Backend '${this.backendName}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);if(this.backendInstance==null){const{name:e,asyncInit:t}=this.initializeBackendsAndReturnBest();if(t)throw new Error(`The highest priority backend '${e}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(e)}return this.backendInstance}backendNames(){return Object.keys(this.registryFactory)}findBackend(e){if(!(e in this.registry))if(e in this.registryFactory){const{asyncInit:t}=this.initializeBackend(e);if(t)return null}else return null;return this.registry[e]}findBackendFactory(e){return e in this.registryFactory?this.registryFactory[e].factory:null}registerBackend(e,t,n=1){return e in this.registryFactory?(console.warn(`${e} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[e]={factory:t,priority:n},!0)}async setBackend(e){if(this.registryFactory[e]==null)throw new Error(`Backend name '${e}' not found in registry`);if(this.backendName=e,this.registry[e]==null){this.backendInstance=null;const{success:t,asyncInit:n}=this.initializeBackend(e),o=n?await t:t;if(!o)return!1}return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new Ad(this.backendInstance),!0}setupRegisteredKernels(){const e=Ra(this.backendName);e.forEach(t=>{t.setupFunc!=null&&t.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){const t=Ra(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 o=++this.pendingBackendInitId,r=n.then(i=>o<this.pendingBackendInitId?!1:(this.registry[e]=i,this.pendingBackendInit=null,!0)).catch(i=>(o<this.pendingBackendInitId||(this.pendingBackendInit=null,console.warn(`Initialization of backend ${e} failed`),console.warn(i.stack||i.message)),!1));return this.pendingBackendInit=r,{success:r,asyncInit:!0}}else return this.registry[e]=n,{success:!0,asyncInit:!1}}catch(n){return console.warn(`Initialization of backend ${e} failed`),console.warn(n.stack||n.message),{success:!1,asyncInit:!1}}}removeBackend(e){if(!(e in this.registryFactory))throw new Error(`${e} backend not found in registry`);this.backendName===e&&this.pendingBackendInit!=null&&this.pendingBackendInitId++,e in this.registry&&(this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e]),delete this.registryFactory[e],this.backendName===e&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)}getSortedBackends(){if(Object.keys(this.registryFactory).length===0)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort((e,t)=>this.registryFactory[t].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t],{success:o,asyncInit:r}=this.initializeBackend(n);if(r||o)return{name:n,asyncInit:r}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){const n=this.state.tensorInfo.get(t),o=n.backend,r=this.readSync(t);o.disposeData(t),n.backend=e,e.move(t,r,n.shape,n.dtype),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(e,t){let n=null;if(t==null){if(typeof e!="function")throw new Error("Please provide a function to tidy()");t=e}else{if(typeof e!="string"&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if(typeof t!="function")throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");n=e}let o;return this.scopedRun(()=>this.startScope(n),()=>this.endScope(o),()=>(o=t(),o instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),o))}scopedRun(e,t,n){e();try{const o=n();return t(),o}catch(o){throw t(),o}}nextTensorId(){return us.nextTensorId++}nextVariableId(){return us.nextVariableId++}clone(e){const t=this.makeTensorFromDataId(e.dataId,e.shape,e.dtype),n={x:e},o=i=>({x:()=>{const a="float32",s={x:i},c={dtype:a};return g.runKernelFunc(p=>p.cast(i,a),s,null,Dn,c)}}),r=[];return this.addTapeNode(this.state.activeScope.name,n,[t],o,r,{}),t}runKernel(e,t,n,o,r){const i=null,a=null;return this.runKernelFunc(i,t,a,e,n,o,r)}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){const o=this.backend.numDataIds();let r=0;n.forEach(s=>{r+=s.dtype==="complex64"?3:1});const i=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],a=o-t-r-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,o,r,i,a){let s,c=[];const p=this.isTapeOn();o==null&&(o=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(o,this.backendName);let x;if(b!=null)d=()=>{const L=this.backend.numDataIds();x=b.kernelFunc({inputs:t,attrs:r,backend:this.backend});const S=Array.isArray(x)?x:[x];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(o,L,S);const I=S.map(({dataId:N,shape:A,dtype:E})=>this.makeTensorFromDataId(N,A,E));if(p){let N=this.getTensorsForGradient(o,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(o,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(o,t,()=>d()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(w),s=w.outputs)}),p&&this.addTapeNode(o,t,s,n,c,r),this.state.profiling&&this.state.activeProfile.kernels.push({name:o,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 o=Na(e);if(o!=null){const r=o.inputsToSave||[],i=o.outputsToSave||[];let a;o.saveAllInputs?(f(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),a=Object.keys(t).map(c=>t[c])):a=r.map(c=>t[c]);const s=n.filter((c,p)=>i[p]);return a.concat(s)}return null}makeTensor(e,t,n,o){if(e==null)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",o=o||this.backend;let r=e;n==="string"&&Rt(e[0])&&(r=e.map(s=>Up(s)));const i=o.write(r,t,n),a=new ee(t,n,i,this.nextTensorId());if(this.incRef(a,o),n==="string"){const s=this.state.tensorInfo.get(i),c=Mp(r);this.state.numBytes+=c-s.bytes,s.bytes=c}return a}makeTensorFromDataId(e,t,n,o){n=n||"float32";const r=new ee(t,n,e,this.nextTensorId());return this.incRef(r,o),r}makeVariable(e,t=!0,n,o){n=n||this.nextVariableId().toString(),o!=null&&o!==e.dtype&&(e=e.cast(o));const r=new Ht(e,t,n,this.nextTensorId());if(this.state.registeredVariables[r.name]!=null)throw new Error(`Variable with name ${r.name} was already registered`);return this.state.registeredVariables[r.name]=r,this.incRef(r,this.backend),r}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 o=0;e.dtype!=="complex64"&&e.dtype!=="string"&&(o=e.size*Fp(e.dtype)),this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:o,refCount:0}),this.state.numBytes+=o}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(o=>o.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(const o of this.state.activeProfile.kernels)o.kernelTimeMs=await o.kernelTimeMs,o.extraInfo=await o.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(e,t,n,o,r,i){const a={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:r},s=Na(e);s!=null&&(o=s.gradFunc),o!=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}),o(c.length>1?c:c[0],r,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=hs(e),n=new Set(t.map(r=>r.id));for(let r=0;r<this.state.activeScope.track.length;r++){const i=this.state.activeScope.track[r];!i.kept&&!n.has(i.id)&&i.dispose()}const o=this.state.scopeStack.pop();this.state.activeScope=this.state.scopeStack.length===0?null:this.state.scopeStack[this.state.scopeStack.length-1],t.forEach(r=>{!r.kept&&r.scopeId===o.id&&this.track(r)})}gradients(e,t,n,o=!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 r=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));f(r instanceof ee,()=>"The result y returned by f() must be a tensor.");const i=Nd(this.state.activeTape,t,r);if(!o&&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[r.id]=n==null?Ww(r.shape):n,Rd(a,i,c=>this.tidy(c),Bw);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:r,grads:s}})}customGrad(e){return f(jt(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{f(t.every(r=>r instanceof ee),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let n;const o={};return t.forEach((r,i)=>{o[i]=r}),this.runKernelFunc((r,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),o,(r,i)=>{const a=n.gradFunc(r,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=_a(),n=await this.backend.time(e);return n.wallMs=_a()-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 Ud;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}}us.nextTensorId=0;us.nextVariableId=0;function Ww(e){const t=ss(Q(e),"float32");return g.makeTensor(t,e,"float32")}function $w(){const e=Ec();if(e._tfengine==null){const t=new _c(e);e._tfengine=new us(t)}return xd(e._tfengine.ENV),Od(()=>e._tfengine),e._tfengine}const g=$w();function Bw(e,t){const n={a:e,b:t};return g.runKernelFunc((o,r)=>{const i=o.add(e,t);return r([e,t]),i},n,null,kn)}const Wd={};Re(Wd,{isBrowser:()=>Hp,isMobile:()=>Gw});function jw(){return typeof navigator!="undefined"&&navigator!=null}function Gw(){if(jw()){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 Hp(){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",()=>Hp());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 o=[];for(;Array.isArray(n)||_e(n)&&t!=="string";)o.push(n.length),n=n[0];return Array.isArray(e)&&pe().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&Bd(e,o,[]),o}function Bd(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 o=t.slice(1);for(let r=0;r<e.length;++r)Bd(e[r],o,n.concat(r))}function $d(e,t,n,o){if(e==null)return;if(e!=="numeric"&&e!==t||e==="numeric"&&t==="string")throw new Error(`Argument '${n}' passed to '${o}' must be ${e} tensor, but got ${t} tensor`)}function u(e,t,n,o="numeric"){if(e instanceof ee)return $d(o,e.dtype,t,n),e;let r=ko(e);if(r!=="string"&&["bool","int32","float32"].indexOf(o)>=0&&(r=o),$d(o,r,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,r);!_e(e)&&!Array.isArray(e)&&(e=[e]);const a=!0,s=r!=="string"?is(e,r):$t(e,[],a);return g.makeTensor(s,i,r)}function Zt(e,t,n,o="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);const r=e;return r.map((i,a)=>u(i,`${t}[${a}]`,n),o)}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 o=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1));const r=(...i)=>{g.startScope(n);try{const a=o(...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(r,"name",{value:n,configurable:!0}),r}function Pw(e){const t=u(e,"x","abs"),n={x:t};return g.runKernelFunc((o,r)=>(r([t]),t.dtype==="complex64"?o.complexAbs(t):o.abs(t)),n,null,yr)}const Ee=m({abs_:Pw});function qw(e){const t=u(e,"x","acos"),n={x:t};return g.runKernelFunc((o,r)=>{const i=o.acos(t);return r([t]),i},n,null,Lr)}const zp=m({acos_:qw});function Hw(e){const t=u(e,"x","acosh"),n={x:t};return g.runKernelFunc((o,r)=>{const i=o.acosh(t);return r([t]),i},n,null,vr)}const Yp=m({acosh_:Hw});function zw(e,t){let n=u(e,"a","add"),o=u(t,"b","add");[n,o]=V(n,o);const r=(a,s)=>{const c=a.add(n,o);return s([n,o]),c},i={a:n,b:o};return g.runKernelFunc(r,i,null,kn)}const R=m({add_:zw});function Yw(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 o=(i,a)=>{const s=i.addN(t);return a(t),s},r=t;return g.runKernelFunc(o,r,null,Sr)}const Vp=m({addN_:Yw});function Kp(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function jd(e,t,n){const o=e.length+t.length,r=[];let i=0,a=0;for(let s=0;s<o;s++)n.indexOf(s)===-1?r.push(e[i++]):r.push(t[a++]);return r}function Jp(e,t){const n=[],o=e.length;for(let i=0;i<o;i++)t.indexOf(i)===-1&&n.push(e[i]);const r=t.map(i=>e[i]);return[n,r]}function we(e,t){const n=t.map(o=>1);return jd(e,n,t)}function Vw(e,t,n){f(Kp(t,n),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`)}function ge(e,t){if(Kp(e,t))return null;const n=[];for(let o=0;o<t;++o)e.indexOf(o)===-1&&n.push(o);return e.forEach(o=>n.push(o)),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 o=t-e;o<t;++o)n.push(o);return n}function Kw(e,t){const n=u(e,"x","reshape",null);t=Cp(t,n.size),f(n.size===Q(t),()=>"new shape and old shape must have the same number of elements.");const o={x:n},r={shape:t},i=(a,s)=>(s([n]),a.reshape(n,t));return g.runKernelFunc(i,o,null,Ni,r)}const y=m({reshape_:Kw});function Jw(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<n.rank,()=>`All entries in 'perm' must be between 0 and ${n.rank-1} but got ${t}`)}),n.rank<=1)return n.clone();const o={x:n},r={perm:t};return g.runKernelFunc(i=>i.transpose(n,t),o,null,Zi,r)}const K=m({transpose_:Jw});function Xw(e,t=null,n=!1){let o=u(e,"x","all","bool");const r=s=>{const c=z(t,o.shape);let p=c;const l=ge(p,o.rank);l!=null&&(o=K(o,l),p=De(p.length,o.rank));const h=s.all(o,p);if(n){const d=we(h.shape,c);return y(h,d)}return h},i={x:o},a={axis:t,keepDims:n};return g.runKernelFunc(r,i,null,kc,a)}const Xp=m({all_:Xw});function Zw(e,t=null,n=!1){let o=u(e,"x","any","bool");const r=s=>{const c=z(t,o.shape);let p=c;const l=ge(p,o.rank);l!=null&&(o=K(o,l),p=De(p.length,o.rank));const h=s.any(o,p);if(n){const d=we(h.shape,c);return y(h,d)}return h},i={x:o},a={axis:t,keepDims:n};return g.runKernelFunc(r,i,null,Dc,a)}const Zp=m({any_:Zw});function Qw(e,t=0){let n=u(e,"x","argMax");const o=(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])},r={x:n},i={axis:t};return g.runKernelFunc(o,r,null,Ir,i)}const Qp=m({argMax_:Qw});function ex(e,t=0){let n=u(e,"x","argMin");const o=(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])},r={x:n},i={axis:t};return g.runKernelFunc(o,r,null,Tr,i)}const el=m({argMin_:ex});function tx(e){const t=u(e,"x","asin"),n={x:t};return g.runKernelFunc((o,r)=>{const i=o.asin(t);return r([t]),i},n,null,Ar)}const tl=m({asin_:tx});function nx(e){const t=u(e,"x","asinh"),n={x:t};return g.runKernelFunc((o,r)=>{const i=o.asinh(t);return r([t]),i},n,null,Nr)}const nl=m({asinh_:nx});function ox(e){const t=u(e,"x","atan"),n={x:t};return g.runKernelFunc((o,r)=>{const i=o.atan(t);return r([t]),i},n,null,Rr)}const ol=m({atan_:ox});function rx(e,t){let n=u(e,"a","atan2"),o=u(t,"b","atan2");[n,o]=V(n,o);const r=(a,s)=>{const c=a.atan2(n,o);return s([n,o]),c},i={a:n,b:o};return g.runKernelFunc(r,i,null,Cr)}const rl=m({atan2_:rx});function ix(e){const t=u(e,"x","atanh"),n={x:t};return g.runKernelFunc((o,r)=>{const i=o.atanh(t);return r([t]),i},n,null,_r)}const il=m({atanh_:ix});function sx(e,t){const n=u(e,"x","cast");if(!kp(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 o={x:n},r={dtype:t};return g.runKernelFunc(i=>i.cast(n,t),o,null,Dn,r)}const _=m({cast_:sx});function ax(e,t,n,o,r="NHWC",i){const a=e[3],s=[...t,a],c=yn(r);return je(e,s,n,i,o,null,null,c)}function _t(e,t,n,o,r,i,a="channelsLast"){const[s,c]=Oa(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,o,r,i,!1,a)}function Qt(e,t,n,o,r,i,a="NDHWC"){const[s,c,p]=sl(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,o,r,!1,h,i)}function je(e,t,n,o,r,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]=Oa(n),[S,I]=Oa(o),N=Wo(d,S),A=Wo(b,I),{padInfo:E,outHeight:M,outWidth:D}=cx(r,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,o,r,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]=sl(n),[A,E,M]=sl(o),D=Wo(b,A),$=Wo(x,E),B=Wo(w,M),{padInfo:j,outDepth:te,outHeight:oe,outWidth:he}=px(r,p,l,h,S,I,N,D,$,B,s),ye=i?L*d:L;let Me;return a==="channelsFirst"?Me=[c,ye,te,oe,he]:a==="channelsLast"&&(Me=[c,te,oe,he,ye]),{batchSize:c,dataFormat:a,inDepth:p,inHeight:l,inWidth:h,inChannels:d,outDepth:te,outHeight:oe,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 lx(e,t,n,o,r){o==null&&(o=al(e,t,n));const i=e[0],a=e[1],s=Wn((i-t+2*o)/n+1,r);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*o)/n+1,r);return f(X(c),()=>`The output # of columns (${c}) must be an integer. Change the stride and/or zero pad parameters`),[s,c]}function hx(e,t,n,o,r,i){r==null&&(r=al(e,t,o));const a=e[0],s=e[1],c=e[2],p=Wn((a-t+2*r)/o+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*r)/o+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*r)/o+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 al(e,t,n,o=1){const r=Wo(t,o);return Math.floor((e[0]*(n-1)-n+r)/2)}function Oa(e){return typeof e=="number"?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function sl(e){return typeof e=="number"?[e,e,e]:e}function Wo(e,t){return t<=1?e:e+(e-1)*(t-1)}function cx(e,t,n,o,r,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=lx([t,n],i,o,e,s);l=b[0],h=b[1]}else if(e==="same"){l=Math.ceil(t/o),h=Math.ceil(n/r);const d=Math.max(0,(l-1)*o+i-t),b=Math.max(0,(h-1)*r+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)/o),h=Math.ceil((n-a+1)/r);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)/o+1,s),h=Wn((n-a+x+w)/r+1,s)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:p,outHeight:l,outWidth:h}}function px(e,t,n,o,r,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=hx([t,n,o,1],s,1,r,e,l);d=L[0],b=L[1],x=L[2]}else if(e==="same"){d=Math.ceil(t/r),b=Math.ceil(n/i),x=Math.ceil(o/a);const w=(d-1)*r+s-t,L=(b-1)*i+c-n,S=(x-1)*a+p-o,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)/r),b=Math.ceil((n-c+1)/i),x=Math.ceil((o-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,o]=Oa(e);return t===1&&n===1&&o===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 ux(e,t,n,o,r){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}.`),r!=null&&f(X(o),()=>`Error in avgPool: pad must be an integer when using, dimRoundingMode ${r} but got pad ${o}.`);const p=(b,x)=>{const w=_t(s.shape,t,n,1,o,r);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:o,dimRoundingMode:r};let d=g.runKernelFunc(p,l,null,Er,h);return d=_(d,i.dtype),c?y(d,[d.shape[1],d.shape[2],d.shape[3]]):d}const pt=m({avgPool_:ux});function dx(){pe().set("PROD",!0)}function mx(){pe().set("DEBUG",!0)}function fx(){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().")}Dd(Le);function gx(){g.disposeVariables()}function bx(){return g}function wx(){return g.memory()}function xx(e){return g.profile(e)}function k(e,t){return g.tidy(e,t)}function ve(e){const t=hs(e);t.forEach(n=>n.dispose())}function cl(e){return g.keep(e)}function yx(e){return g.time(e)}function Lx(e){return g.setBackend(e)}function vx(){return g.ready()}function Sx(){return g.backendName}function Ix(e){g.removeBackend(e)}function Tx(e){return g.findBackend(e)}function Ax(e){return g.findBackendFactory(e)}function Nx(e,t,n=1){return g.registerBackend(e,t,n)}function Rx(){return g.backend}function _x(e,t){pe().setPlatform(e,t)}function Cx(e,t,n,o,r,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}'`),r!=null&&f(X(o),()=>`Error in avgPool3d: pad must be an integer when using, dimRoundingMode ${r} but got pad ${o}.`);const l=(x,w)=>{a==null&&(a=[1,1,1]);const L=Qt(c.shape,t,n,a,o,r,i);return w([c]),x.avgPool3d(c,L)},h={x:c},d={filterSize:t,strides:n,pad:o,dimRoundingMode:r,dataFormat:i,dilations:a};let b=g.runKernelFunc(l,h,null,Or,d);return b=_(b,c.dtype),p?y(b,[b.shape[1],b.shape[2],b.shape[3],b.shape[4]]):b}const pl=m({avgPool3d_:Cx});function ll(e,t){const n=e[0].length;e.forEach((r,i)=>{f(r.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<n,()=>`Error in concat${n}D: axis must be between 0 and ${n-1}.`);const o=e[0];e.forEach((r,i)=>{for(let a=0;a<n;a++)f(a===t||r[a]===o[a],()=>`Error in concat${n}D: Shape of tensors[${i}] (${r}) does not match the shape of the rest (${o}) along the non-concatenated axis ${i}.`)})}function hl(e,t){const n=e[0].slice();for(let o=1;o<e.length;o++)n[t]+=e[o][t];return n}function ze(e,t,n,o){if(o==null&&(o=ko(e)),o==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!_e(e)&&!Array.isArray(e)&&typeof e!="number"&&typeof e!="boolean"&&typeof e!="string")throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(t!=null){as(t);const r=Q(t),i=Q(n);f(r===i,()=>`Based on the provided shape, [${t}], the tensor should have ${r} values but has ${i}`);for(let a=0;a<n.length;++a){const s=n[a],c=a===n.length-1?s!==Q(t.slice(a)):!0;f(n[a]===t[a]||!c,()=>`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `)}}return!_e(e)&&!Array.isArray(e)&&(e=[e]),t=t||n,e=o!=="string"?is(e,o):$t(e,[],!0),g.makeTensor(e,t,o)}function Ge(e,t,n){const o=We(e,n);return ze(e,t,o,n)}function Ex(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 o=z(t,n[0].shape)[0],r=hl(n.map(p=>p.shape),o);if(Q(r)===0)return Ge([],r);if(n=n.filter(p=>p.size>0),n.length===1)return n[0];const i=n.map(p=>p.shape);ll(i,o);const a=(p,l)=>{const h=p.concat(n,o);return l(n),h},s=n,c={axis:t};return g.runKernelFunc(a,s,null,Wr,c)}const Z=m({concat_:Ex});function Ox(e,t,n=!1,o=!1){let r=u(e,"a","matMul"),i=u(t,"b","matMul");[r,i]=V(r,i),f(r.rank>=2&&i.rank>=2&&r.rank===i.rank,()=>`Error in matMul: inputs must have the same rank of at least 2, got ranks ${r.rank} and ${i.rank}.`);const a=n?r.shape[r.rank-2]:r.shape[r.rank-1],s=o?i.shape[i.rank-1]:i.shape[i.rank-2],c=n?r.shape[r.rank-1]:r.shape[r.rank-2],p=o?i.shape[i.rank-2]:i.shape[i.rank-1],l=r.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 ${r.shape} and ${i.shape} must match.`),f(a===s,()=>`Error in matMul: inner shapes (${a}) and (${s}) of Tensors with shapes ${r.shape} and ${i.shape} and transposeA=${n} and transposeB=${o} must match.`);const x=r.shape.slice(0,-2).concat([c,p]),w=n?y(r,[d,a,c]):y(r,[d,c,a]),L=o?y(i,[b,p,s]):y(i,[b,s,p]),S=(E,M)=>(M([w,L]),E.batchMatMul(w,L,n,o)),I={a:w,b:L},N={transposeA:n,transposeB:o},A=g.runKernelFunc(S,I,null,kr,N);return y(A,x)}const Y=m({matMul_:Ox});function kx(e,t){let n=u(e,"a","mul"),o=u(t,"b","mul");[n,o]=V(n,o);const r=(a,s)=>{const c=a.multiply(n,o);return s([n,o]),c},i={a:n,b:o};return g.runKernelFunc(r,i,null,wi)}const v=m({mul_:kx});function Dx(e){const t=u(e,"x","sigmoid"),n={x:t};return g.runKernelFunc((o,r)=>{const i=o.sigmoid(t);return r([i]),i},n,null,$i)}const lt=m({sigmoid_:Dx});const Gd={};Re(Gd,{assertParamsValid:()=>ul,computeFlatOffset:()=>Mx,computeOutShape:()=>dl,isSliceContinous:()=>Fx,maskToAxes:()=>ds,parseSliceParams:()=>ms,startForAxis:()=>wl,startIndicesWithElidedDims:()=>fl,stopForAxis:()=>xl,stopIndicesWithElidedDims:()=>gl,stridesForAxis:()=>bl,stridesWithElidedDims:()=>ml});function ul(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 o=0;o<e.rank;++o)f(t[o]+n[o]<=e.shape[o],()=>`Error in slice${e.rank}D: begin[${o}] + size[${o}] (${t[o]+n[o]}) would overflow input.shape[${o}] (${e.shape[o]})`)}function ds(e){const t=[];let n=0;for(;e>0;)e&1&&t.push(n),e/=2,n++;return t}function dl(e,t,n){const o=[];for(let r=0;r<e.length;r++)o[r]=Math.ceil((t[r]-e[r])/n[r]);return o}function ml(e,t,n,o){const r=[...e];for(let i=r.length;i<o.length;i++)r.push(1);for(let i=0;i<n;i++)i===0?r[t]=1:(r.splice(t,0,1),r.pop());return r}function Pd(e,t,n){return n<=e?n:n-(t-1)}function qd(e,t){const n=[];for(let o=0;o<e;o++)n.push(t+o);return n}function fl(e,t,n,o,r){const i=[...r],a=qd(n,t);for(let s=0;s<i.length;s++)if(a.indexOf(s)>-1)i[s]=0;else{const c=Pd(t,n,s);let p=o[c];e&1<<c&&(p=0),i[s]=p}return i}function gl(e,t,n,o,r){const i=[...r],a=qd(n,t);for(let s=0;s<i.length;s++)if(a.indexOf(s)>-1)i[s]=Number.MAX_SAFE_INTEGER;else{const c=Pd(t,n,s);let p=o[c];e&1<<c&&(p=Number.MAX_SAFE_INTEGER),i[s]=p}for(let s=0;s<i.length;s++){const c=r[s];i[s]<0&&(i[s]+=c),i[s]=Eo(0,i[s],r[s])}return i}function bl(e,t,n){let o=e[t];return(n&1<<t||o==null)&&(o=1),o}function wl(e,t,n,o,r,i){let a=t[r];const s=n[r]||1;(e&1<<r||i&1<<r||a==null)&&(s>0?a=Number.MIN_SAFE_INTEGER:a=Number.MAX_SAFE_INTEGER);const c=o[r];return a<0&&(a+=c),a=Eo(0,a,c-1),a}function xl(e,t,n,o,r,i){let a=t[r];const s=n[r]||1;(e&1<<r||i&1<<r||a==null)&&(s>0?a=Number.MAX_SAFE_INTEGER:a=Number.MIN_SAFE_INTEGER);const c=o[r];return a<0&&(a+=c),s>0?a=Eo(0,a,c):a=Eo(-1,a,c-1),a}function Fx(e,t,n){let o=n.length;for(let r=0;r<n.length;r++)if(n[r]>1){o=r;break}for(let r=o+1;r<n.length;r++)if(t[r]>0||n[r]!==e[r])return!1;return!0}function Mx(e,t){let n=e.length>0?e[e.length-1]:1;for(let o=0;o<e.length-1;o++)n+=e[o]*t[o];return n}function ms(e,t,n){let o;typeof t=="number"?o=[t,...new Array(e.rank-1).fill(0)]:t.length<e.rank?o=t.concat(new Array(e.rank-t.length).fill(0)):o=t.slice(),o.forEach(i=>{f(i!==-1,()=>"slice() does not support negative begin indexing.")});let r;return n==null?r=new Array(e.rank).fill(-1):typeof n=="number"?r=[n,...new Array(e.rank-1).fill(-1)]:n.length<e.rank?r=n.concat(new Array(e.rank-n.length).fill(-1)):r=n,r=r.map((i,a)=>i>=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]-o[a])),[o,r]}function Ux(e,t,n){const o=u(e,"x","slice");if(o.rank===0)throw new Error("Slicing scalar is not possible");const[r,i]=ms(o,t,n);ul(o,r,i);const a=(p,l)=>(l([o]),p.slice(o,r,i)),s={x:o},c={begin:t,size:n};return g.runKernelFunc(a,s,null,Mi,c)}const G=m({slice_:Ux});function Wx(e){const t=u(e,"x","tanh"),n={x:t};return g.runKernelFunc((o,r)=>{const i=o.tanh(t);return r([i]),i},n,null,Ji)}const Bo=m({tanh_:Wx});function Bx(e,t,n,o,r,i){const a=u(e,"forgetBias","basicLSTMCell"),s=u(t,"lstmKernel","basicLSTMCell"),c=u(n,"lstmBias","basicLSTMCell"),p=u(o,"data","basicLSTMCell"),l=u(r,"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),Bo(N)),v(l,lt(R(a,A)))),D=v(Bo(M),lt(E));return[M,D]}const yl=m({basicLSTMCell_:Bx});function $x(e,t,n){const o=u(e,"x","batchToSpaceND"),r=t.reduce((c,p)=>c*p);f(o.rank>=1+t.length,()=>`input rank is ${o.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(o.shape[0]%r===0,()=>`input tensor batch is ${o.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${r}`);const i=c=>c.batchToSpaceND(o,t,n),a={x:o},s={blockShape:t,crops:n};return g.runKernelFunc(i,a,null,Dr,s)}const Bn=m({batchToSpaceND_:$x});function Hd(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 jx(e,t,n,o,r,i){i==null&&(i=.001);const a=u(e,"x","batchNorm"),s=u(t,"mean","batchNorm"),c=u(n,"variance","batchNorm");let p;r!=null&&(p=u(r,"scale","batchNorm"));let l;o!=null&&(l=u(o,"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=Hd(a),d=(L,S)=>(S([h,s,c,p]),L.batchNorm(h,ka(s),ka(c),ka(l),ka(p),i)),b={x:h,scale:p,offset:l,mean:s,variance:c},x={varianceEpsilon:i},w=g.runKernelFunc(d,b,null,ei,x);return y(w,a.shape)}function ka(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_:jx});function Gx(e,t,n,o,r,i){const a=u(e,"x","batchNorm"),s=u(t,"mean","batchNorm"),c=u(n,"variance","batchNorm");let p;r!=null&&(p=u(r,"scale","batchNorm"));let l;return o!=null&&(l=u(o,"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 Ll=m({batchNorm2d_:Gx});function Px(e,t,n,o,r,i){const a=u(e,"x","batchNorm"),s=u(t,"mean","batchNorm"),c=u(n,"variance","batchNorm");let p;r!=null&&(p=u(r,"scale","batchNorm"));let l;return o!=null&&(l=u(o,"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 vl=m({batchNorm3d_:Px});function qx(e,t,n,o,r,i){const a=u(e,"x","batchNorm"),s=u(t,"mean","batchNorm"),c=u(n,"variance","batchNorm");let p;r!=null&&(p=u(r,"scale","batchNorm"));let l;return o!=null&&(l=u(o,"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 Sl=m({batchNorm4d_:qx});function Hx(e){const t=u(e,"x","clone",null),n=()=>g.makeTensorFromDataId(t.dataId,t.shape,t.dtype),o={x:t};return g.runKernelFunc(n,o,null,oi)}const Et=m({clone_:Hx});function zx(e,t){let n=u(e,"broadcastTo","x");const o=n.shape;if(t.some(l=>!(l>0)||l%1!==0))throw new Error(`broadcastTo(): Invalid broadcast shape [${t}].`);if(t.length<n.rank)throw new Error(`broadcastTo(): shape.length=${t.length} < input.rank=${n.rank}.`);if(t.length>n.rank){const l=n.shape.slice();for(;l.length<t.length;)l.unshift(1);n=y(n,l)}const r=n.shape,i=Array.from(t);for(let l=t.length-1;l>=0;l--)if(r[l]===t[l])i[l]=1;else if(n.shape[l]!==1)throw new Error(`broadcastTo(): [${o}] 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:r};return g.runKernelFunc(s,c,null,Fr,p)}const $o=m({broadcastTo_:zx});function Be(e,t="float32",n){return t=t||"float32",as(e),new Fo(e,t,n)}function Yx(e){const t=u(e,"x","ceil"),n={x:t};return g.runKernelFunc(o=>o.ceil(t),n,null,Mr)}const Il=m({ceil_:Yx});function Vx(e,t,n){const o=u(e,"x","clipByValue");f(t<=n,()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`);const r={x:o},i={clipValueMin:t,clipValueMax:n};return g.runKernelFunc((a,s)=>{const c=a.clip(o,t,n);return s([o]),c},r,null,Ur,i)}const $n=m({clipByValue_:Vx});function Kx(e,t){const n=u(e,"real","complex"),o=u(t,"imag","complex");P(n.shape,o.shape,`real and imag shapes, ${n.shape} and ${o.shape}, must match in call to tf.complex().`);const r=a=>a.complex(n,o),i={real:n,imag:o};return g.runKernelFunc(r,i,null,Uc)}const Ye=m({complex_:Kx});function Jx(e){return Z(e,0)}const Tl=m({concat1d_:Jx});function Xx(e,t){return Z(e,t)}const Al=m({concat2d_:Xx});function Zx(e,t){return Z(e,t)}const Nl=m({concat3d_:Zx});function Qx(e,t){return Z(e,t)}const Rl=m({concat4d_:Qx});function ey(e,t,n,o,r="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(o),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`);const h=r==="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(r),N=je(p.shape,c.shape,n,i,o,a,!1,I),A=L.conv2d(p,c,N);return S([p,c]),A},b={x:p,filter:c},x={strides:n,pad:o,dataFormat:r,dilations:i,dimRoundingMode:a},w=g.runKernelFunc(d,b,null,Br,x);return l?y(w,[w.shape[1],w.shape[2],w.shape[3]]):w}const xe=m({conv2d_:ey});function ty(e,t,n,o,r="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(o),()=>`Error in conv1d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`),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(r==="NWC",()=>`Error in conv1d: got dataFormat of ${r} 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,o,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 _l=m({conv1d_:ty});function ny(e,t,n,o,r,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(r),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${a} but got pad ${r}.`);const d=(L,S)=>{const I=1,N=yn(i),A=je(s,n.shape,o,I,r,a,!1,N),E=L.conv2dDerInput(c,n,A);return S([c,n]),E},b={dy:c,filter:n},x={strides:o,pad:r,dataFormat:i,dimRoundingMode:a,inputShape:s},w=g.runKernelFunc(d,b,null,$r,x);return p?y(w,[w.shape[1],w.shape[2],w.shape[3]]):w}const jo=m({conv2DBackpropInput_:ny});function oy(e,t,n,o,r,i){const a=u(e,"x","conv2dTranspose"),s=u(t,"filter","conv2dTranspose");return jo(n,a,s,o,r,"NHWC",i)}const Cl=m({conv2dTranspose_:oy});function ry(e,t,n,o,r="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(r==="NDHWC",()=>`Error in conv3d: got dataFormat of ${r} but only NDHWC is currently supported.`);const l=(x,w)=>{const L=Ln(c.shape,s.shape,n,i,o),S=x.conv3d(c,s,L);return w([c,s]),S},h={x:c,filter:s},d={strides:n,pad:o,dataFormat:r,dilations:i},b=g.runKernelFunc(l,h,null,jr,d);return p?y(b,[b.shape[1],b.shape[2],b.shape[3],b.shape[4]]):b}const El=m({conv3d_:ry});function iy(e,t,n,o,r){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,o,w,r);return x.conv3dDerInput(a,n,L)},h={dy:a},d={pad:r},b=g.runKernelFunc(l,h,null,$c,d);return s?y(b,[b.shape[1],b.shape[2],b.shape[3],b.shape[4]]):b}const Da=m({conv3DBackpropInput_:iy});function sy(e,t,n,o,r){const i=u(e,"x","conv3dTranspose"),a=u(t,"filter","conv3dTranspose");return Da(n,i,a,o,r)}const Ol=m({conv3dTranspose_:sy});function ay(e){const t=u(e,"x","cos"),n={x:t};return g.runKernelFunc((o,r)=>{const i=o.cos(t);return r([t]),i},n,null,Gr)}const jn=m({cos_:ay});function cy(e){const t=u(e,"x","cosh"),n={x:t};return g.runKernelFunc((o,r)=>{const i=o.cosh(t);return r([t]),i},n,null,Pr)}const fs=m({cosh_:cy});function py(e,t=0,n=!1,o=!1){const r=u(e,"x","cumsum"),i=(c,p)=>{const l=ge([t],r.rank);let h=r;l!=null&&(h=K(r,l));const d=De(1,r.rank)[0];let b=c.cumsum(h,d,n,o);if(p([r]),l!=null){const x=Un(l);b=K(b,x)}return b},a={x:r},s={axis:t,exclusive:n,reverse:o};return g.runKernelFunc(i,a,null,qr,s)}const gs=m({cumsum_:py});function ly(e,t,n="NHWC"){const o=u(e,"x","depthToSpace"),r=n==="NHWC"?o.shape[1]:o.shape[2],i=n==="NHWC"?o.shape[2]:o.shape[3],a=n==="NHWC"?o.shape[3]:o.shape[1];f(r*t>=0,()=>`Negative dimension size caused by overflow when multiplying
${r} and ${t} for depthToSpace with input shape
${o.shape}`),f(i*t>=0,()=>`Negative dimension size caused by overflow when multiplying
${i} and ${t} for depthToSpace with input shape
${o.shape}`),f(a%(t*t)===0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${a} for depthToSpace with input shape ${o.shape}`);const s=l=>l.depthToSpace(o,t,n),c={x:o},p={blockSize:t,dataFormat:n};return g.runKernelFunc(s,c,null,Gc,p)}const kl=m({depthToSpace_:ly});function hy(e,t,n,o,r="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(o),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`);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,o,a,!0),I=w.depthwiseConv2D(p,c,S);return L([p,c]),I},d={x:p,filter:c},b={strides:n,pad:o,dataFormat:r,dilations:i,dimRoundingMode:a},x=g.runKernelFunc(h,d,null,Hr,b);return l?y(x,[x.shape[1],x.shape[2],x.shape[3]]):x}const en=m({depthwiseConv2d_:hy});function uy(e){const t=u(e,"x","diag"),n=r=>{const i=y(t,[t.size]),a=r.diag(i),s=[...e.shape,...e.shape];return y(a,s)},o={x:t};return g.runKernelFunc(n,o,null,Hc)}const Dl=m({diag_:uy});function dy(e,t,n,o,r=[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:o,dilations:r},d=g.runKernel(zr,l,h);return p?y(d,[d.shape[1],d.shape[2],d.shape[3]]):d}const Fl=m({dilation2d_:dy});function my(e,t){let n=u(e,"a","floorDiv"),o=u(t,"b","floorDiv");[n,o]=V(n,o);const r=(a,s)=>{const c=a.floorDiv(n,o);return s([n,o]),c},i={a:n,b:o};return g.runKernelFunc(r,i,null,Qr)}const bs=m({floorDiv_:my});function fy(e,t){let n=u(e,"a","div"),o=u(t,"b","div");if([n,o]=V(n,o),n.dtype==="int32"&&o.dtype==="int32")return bs(n,o);const r=(s,c)=>{const p=s.realDivide(n,o);return c([n,o]),p},i={a:n,b:o},a={};return g.runKernelFunc(r,i,null,Yr,a)}const F=m({div_:fy});function gy(e,t){const n=e.length,o=[];for(let r=0;r<n;r++){const i=n-1-r,a=e[i]||1,s=t[t.length-1-r]||1;s>1&&a===1&&o.unshift(i)}return o}function ae(e,t){const n=[];for(let o=0;o<t.length;o++){const r=e[e.length-o-1],i=t.length-o-1,a=t[i];(r==null||r===1&&a>1)&&n.unshift(i)}return n}function q(e,t){const n=[],o=Math.max(e.length,t.length);for(let r=0;r<o;r++){let i=e[e.length-r-1];i==null&&(i=1);let a=t[t.length-r-1];if(a==null&&(a=1),i===1)n.unshift(a);else if(a===1)n.unshift(i);else if(i!==a){const s=`Operands could not be broadcast together with shapes ${e} and ${t}.`;throw Error(s)}else n.unshift(i)}return n}function by(e,t){let n=u(e,"a","equal"),o=u(t,"b","equal");[n,o]=V(n,o),q(n.shape,o.shape);const r=a=>a.equal(n,o),i={a:n,b:o};return g.runKernelFunc(r,i,null,Kc)}const tn=m({equal_:by});function wy(e,t,n){const o=u(t,"a","where"),r=u(n,"b","where"),i=u(e,"condition","where","bool"),a=q(o.shape,r.shape),s=$o(o,a),c=$o(r,a);i.rank===1&&f(i.shape[0]===o.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,Di)}const Oe=m({where_:wy});function xy(e){const t=u(e,"x","zerosLike"),n={x:t};return g.runKernelFunc(o=>o.zerosLike(t),n,null,ts)}const W=m({zerosLike_:xy});function yy(e,t){let n=u(e,"a","div"),o=u(t,"b","div");[n,o]=V(n,o);const r=F(n,o),i=W(r),a=tn(o,i);return Oe(a,i,r)}const Ml=m({divNoNan_:yy});function Ly(e,t){const n=u(e,"t1","dot"),o=u(t,"t2","dot");f((n.rank===1||n.rank===2)&&(o.rank===1||o.rank===2),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${o.rank}.`);const r=n.rank===1?n.size:n.shape[1],i=o.rank===1?o.size:o.shape[0];if(f(r===i,()=>`Error in dot: inner dimensions of inputs must match, but got ${r} and ${i}.`),n.rank===1&&o.rank===1){const a=y(n,[1,-1]),s=y(o,[-1,1]),c=Y(a,s);return y(c,[])}else if(n.rank===1&&o.rank===2){const a=y(n,[1,-1]),s=y(o,[o.shape[0],o.shape[1]]),c=Y(a,s);return y(c,[c.size])}else if(n.rank===2&&o.rank===1){const a=y(o,[-1,1]),s=Y(n,a);return y(s,[s.size])}else{const a=y(o,[o.shape[0],o.shape[1]]),s=Y(n,a);return s}}const Ul=m({dot_:Ly});function vy(e){const t=u(e,"x","elu"),n=(r,i)=>{const a=r.elu(t);return i([a]),a},o={x:t};return g.runKernelFunc(n,o,null,Vr)}const ws=m({elu_:vy});function Sy(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=_(t,"float32"));const n={x:t};return g.runKernelFunc((o,r)=>{const i=o.erf(t);return r([t]),i},n,null,Kr)}const Wl=m({erf_:Sy});function Iy(e){const t=u(e,"x","exp"),n={x:t};return g.runKernelFunc((o,r)=>{const i=o.exp(t);return r([i]),i},n,null,Jr)}const Se=m({exp_:Iy});function Ty(e,t=0){const n=null,o=u(e,"x","expandDims",n);f(t<=o.rank,()=>"Axis must be <= rank of the tensor");const r=o.shape.slice();return t<0&&(f(-(o.rank+1)<=t,()=>`Axis must be in the interval [${-(o.rank+1)}, ${o.rank}]`),t=o.rank+t+1),r.splice(t,0,1),y(o,r)}const et=m({expandDims_:Ty});function Ay(e){const t=u(e,"x","expm1"),n={x:t};return g.runKernelFunc((o,r)=>{const i=o.expm1(t);return r([t]),i},n,null,Xr)}const Bl=m({expm1_:Ay});function Ny(e,t){const n=null,o=u(e,"x","tile",n);f(o.rank===t.length,()=>`Error in transpose: rank of input ${o.rank} must match length of reps ${t}.`);const r=(c,p)=>{const l=c.tile(o,t);return p([o]),l},i=[o],a={x:o},s={reps:t};return g.runKernelFunc(r,a,null,Xi,s,i)}const Ot=m({tile_:Ny});function Ry(e,t,n,o="float32"){t==null&&(t=e);const r=Be([e,t],o),i=e<=t?e:t;for(let s=0;s<i;++s)r.set(1,s,s);const a=y(r.toTensor(),[e,t]);if(n==null)return a;if(n.length===1)return Ot(et(a,0),[n[0],1,1]);if(n.length===2)return Ot(et(et(a,0),0),[n[0],n[1],1,1]);if(n.length===3)return Ot(et(et(et(a,0),0),0),[n[0],n[1],n[2],1,1]);throw new Error(`eye() currently supports only 1D and 2D batchShapes, but received ${n.length}D.`)}const xs=m({eye_:Ry});function _y(e){f(e.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);const t={input:e};return g.runKernelFunc(n=>{const o=e.shape[e.shape.length-1],r=e.size/o,i=e.as2D(r,o),a=n.fft(i);return a.reshape(e.shape)},t,null,Jc)}const Gn=m({fft_:_y});function Pe(e,t,n){const o={shape:e,value:t,dtype:n};return g.runKernelFunc(r=>r.fill(e,t,n),{},null,Xc,o)}function Cy(e){const t=u(e,"x","floor"),n={x:t};return g.runKernelFunc(o=>o.floor(t),n,null,Zr)}const Pn=m({floor_:Cy});const Fa=30;function Ey(e){return e<=Fa?e:Do(e,Math.floor(Math.sqrt(e)))}const zd={};Re(zd,{collectGatherOpShapeInfo:()=>$l,computeOutShape:()=>ky,segOpComputeOptimalWindowSize:()=>Oy});function Oy(e,t){let n=!1,o;for(e<=Fa?(o=e,n=!0):o=Do(e,Math.floor(Math.sqrt(e)));!n;)o>t||o===e?n=!0:o=Do(e,o+1);return o}function ky(e,t,n){const o=[],r=e.length;for(let i=0;i<r;i++)i!==t?o.push(e[i]):o.push(n);return o}function $l(e,t,n){const o=e.shape[n],r=[];let i=1,a=1;for(let s=0;s<n;s++)r.push(e.shape[s]),i*=e.shape[s];for(let s=0;s<t.rank;s++)r.push(t.shape[s]);for(let s=n+1;s<e.rank;s++)r.push(e.shape[s]),a*=e.shape[s];return{batchSize:i,sliceSize:a,dimSize:o,outputShape:r}}function Dy(e,t,n=0){const o=u(e,"x","gather"),r=u(t,"indices","gather","int32"),i={x:o,indices:r},a={axis:n},s=(c,p)=>{const l=z(n,o.shape)[0],h=$l(o,r,l),d=c.gather(o,y(r,[r.size]),l);return p([o,r]),y(d,h.outputShape)};return g.runKernelFunc(s,i,null,ti,a)}const qn=m({gather_:Dy});function Fy(e,t){let n=u(e,"a","greater"),o=u(t,"b","greater");[n,o]=V(n,o),q(n.shape,o.shape);const r=a=>a.greater(n,o),i={a:n,b:o};return g.runKernelFunc(r,i,null,ep)}const tt=m({greater_:Fy});function My(e,t){let n=u(e,"a","greaterEqual"),o=u(t,"b","greaterEqual");[n,o]=V(n,o),q(n.shape,o.shape);const r=(a,s)=>{const c=a.greaterEqual(n,o);return s([n,o]),c},i={a:n,b:o};return g.runKernelFunc(r,i,null,ni)}const ht=m({greaterEqual_:My});function Uy(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 o=e.shape[e.shape.length-1],r=e.size/o,i=y(e,[r,o]),a=n.ifft(i);return y(a,e.shape)},t,null,tp)}const vn=m({ifft_:Uy});function Wy(e){const t=u(e,"input","imag"),n=r=>r.imag(t),o={input:t};return g.runKernelFunc(n,o,null,np)}const nn=m({imag_:Wy});function By(e){const t=u(e,"input","real"),n=r=>r.real(t),o={input:t};return g.runKernelFunc(n,o,null,xp)}const zt=m({real_:By});function $y(e,t){const n=u(e,"x","reverse"),o=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)},r={x:n},i={dims:t};return g.runKernelFunc(o,r,null,Ei,i)}const Ve=m({reverse_:$y});function C(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=[],o=[];return ze(e,n,o,t)}function jy(e){const t=e.shape[e.shape.length-1],n=e.size/t;let o;if(t<=2){const r=y(e,[n,t]);o=vn(r)}else{const r=[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),C(-1)),p=Z([i,s],1),l=Z([a,c],1),h=y(Ye(p,l),[r[0],r[1]]);o=vn(h)}if(o=zt(o),e.rank===3&&e.shape[0]!==0){const r=o,i=e.shape[0];o=y(o,[i,o.shape[0]/i,o.shape[1]]),r.dispose()}return o}const ys=m({irfft_:jy});function Gy(e){const t=u(e,"x","isFinite"),n={x:t};return g.runKernelFunc(o=>o.isFinite(t),n,null,ri)}const jl=m({isFinite_:Gy});function Py(e){const t=u(e,"x","isInf"),n={x:t};return g.runKernelFunc(o=>o.isInf(t),n,null,ii)}const Gl=m({isInf_:Py});function qy(e){const t=u(e,"x","isNaN"),n={x:t};return g.runKernelFunc(o=>o.isNaN(t),n,null,si)}const Pl=m({isNaN_:qy});function Hy(e,t){let n=u(e,"a","maximum"),o=u(t,"b","maximum");[n,o]=V(n,o),n.dtype==="bool"&&(n=_(n,"int32"),o=_(o,"int32")),q(n.shape,o.shape);const r=(a,s)=>{const c=a.maximum(n,o);return s([n,o]),c},i={a:n,b:o};return g.runKernelFunc(r,i,null,ui)}const kt=m({maximum_:Hy});function zy(e,t=.2){const n=u(e,"x","leakyRelu");return kt(v(C(t),n),n)}const ql=m({leakyRelu_:zy});function Yy(e,t){let n=u(e,"a","less"),o=u(t,"b","less");[n,o]=V(n,o),q(n.shape,o.shape);const r=a=>a.less(n,o),i={a:n,b:o};return g.runKernelFunc(r,i,null,op)}const Hn=m({less_:Yy});function Vy(e,t){let n=u(e,"a","lessEqual"),o=u(t,"b","lessEqual");[n,o]=V(n,o),q(n.shape,o.shape);const r=(a,s)=>{const c=a.lessEqual(n,o);return s([n,o]),c},i={a:n,b:o};return g.runKernelFunc(r,i,null,rp)}const ut=m({lessEqual_:Vy});function Hl(e,t,n){if(n<=0)throw new Error("The number of values should be positive.");const o={start:e,stop:t,num:n};return g.runKernelFunc(r=>r.linspace(e,t,n),{},null,ip,o)}function Ky(e,t=5,n=1,o=1,r=.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,o,r);return b([a,x]),x},p={x:a},l={depthRadius:t,bias:n,alpha:o,beta:r},h=g.runKernelFunc(c,p,null,li,l);return s?y(h,[h.shape[1],h.shape[2],h.shape[3]]):h}const zl=m({localResponseNormalization_:Ky});function Jy(e){const t=u(e,"x","log"),n={x:t};return g.runKernelFunc((o,r)=>{const i=o.log(t);return r([t]),i},n,null,ai)}const yt=m({log_:Jy});function Xy(e){const t=u(e,"x","log1p"),n={x:t};return g.runKernelFunc((o,r)=>{const i=o.log1p(t);return r([t]),i},n,null,ci)}const Ls=m({log1p_:Xy});function Zy(e){return f(jt(e),()=>"The f passed in grad(f) must be a function"),(t,n)=>{const o=u(t,"x","tf.grad",null),r=n!=null?u(n,"dy","tf.grad"):null;return g.tidy(()=>{const{value:i,grads:a}=g.gradients(()=>e(o),[o],r);return r!=null&&P(i.shape,r.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Ma(a),a[0]})}}function Qy(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 o=Zt(t,"args","tf.grads",null),r=n!=null?u(n,"dy","tf.grads"):null;return g.tidy(()=>{const{value:i,grads:a}=g.gradients(()=>e(...o),o,r);return r!=null&&P(i.shape,r.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Ma(a),a})}}function eL(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:o,value:r}=g.gradients(()=>e(t),[t],n);return Ma(o),{grad:o[0],value:r}}}function tL(e){return f(jt(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{f(Array.isArray(t)&&t.every(r=>r 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 o=g.gradients(()=>e(...t),t,n);return n!=null&&P(o.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Ma(o.grads),o}}function Yl(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 o=n?t.filter(p=>!p.trainable):null,r=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 ${r} 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])}),o!=null&&o.forEach(p=>c[p.name]=null),{value:a,grads:c}}function Ke(e){return g.customGrad(e)}function Ma(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 nL(e){const t=u(e,"x","neg"),n={x:t};return g.runKernelFunc(o=>o.neg(t),n,null,xi)}const ne=m({neg_:nL});function oL(e){const t=u(e,"x","softplus"),n={x:t};return g.runKernelFunc((o,r)=>{const i=o.softplus(t);return r([t]),i},n,null,ji)}const vs=m({softplus_:oL});function rL(e){const t=u(e,"x","logSigmoid"),n=Ke(o=>{const r=ne(vs(ne(o))),i=a=>{const s=v(a,lt(ne(o)));return s};return{value:r,gradFunc:i}});return n(t)}const Vl=m({logSigmoid_:rL});function iL(e,t=null,n=!1){const o=u(e,"x","max"),r=(s,c)=>{const p=z(t,o.shape);let l=p;const h=ge(l,o.rank);let d=o;h!=null&&(d=K(o,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,o.shape));x=y(x,w),b.dispose()}return c([o,x]),x},i={x:o},a={reductionIndices:t,keepDims:n};return g.runKernelFunc(r,i,null,hi,a)}const dt=m({max_:iL});function sL(e,t){let n=u(e,"a","sub"),o=u(t,"b","sub");[n,o]=V(n,o);const r=(a,s)=>{const c=a.subtract(n,o);return s([n,o]),c},i={a:n,b:o};return g.runKernelFunc(r,i,null,Vi)}const O=m({sub_:sL});function aL(e,t=null,n=!1){let o=u(e,"x","sum");o.dtype==="bool"&&(o=_(o,"int32"));const r=(s,c)=>{c([o]);const p=z(t,o.shape),l=ge(p,o.rank);let h=p,d=o;l!=null&&(d=K(o,l),h=De(h.length,o.rank));let b=s.sum(d,h);if(n){const x=we(b.shape,p);b=y(b,x)}return b},i={x:o},a={axis:t,keepDims:n};return g.runKernelFunc(r,i,null,Pi,a)}const U=m({sum_:aL});function cL(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 o=(a,s)=>{const c=!0,p=dt(e,t,!0),l=O(e,p),h=O(_(l,"float32"),yt(U(Se(l),t,c)));return s([h]),h},r={logits:n},i={axis:t};return g.runKernelFunc(o,r,null,pi,i)}const Kl=m({logSoftmax_:cL});function pL(e,t=null,n=!1){const o=u(e,"x","logSumExp"),r=z(t,o.shape),i=dt(o,r,!0),a=O(o,i),s=Se(a),c=U(s,r),p=yt(c),l=R(y(i,p.shape),p);if(n){const h=we(l.shape,r);return y(l,h)}return l}const Ss=m({logSumExp_:pL});function lL(e,t){const n=u(e,"a","logicalAnd","bool"),o=u(t,"b","logicalAnd","bool");q(n.shape,o.shape);const r={a:n,b:o};return g.runKernelFunc(i=>i.logicalAnd(n,o),r,null,sp)}const Lt=m({logicalAnd_:lL});function hL(e){const t=u(e,"x","logicalNot","bool"),n={x:t};return g.runKernelFunc(o=>o.logicalNot(t),n,null,ap)}const zn=m({logicalNot_:hL});function uL(e,t){const n=u(e,"a","logicalOr","bool"),o=u(t,"b","logicalOr","bool");q(n.shape,o.shape);const r={a:n,b:o};return g.runKernelFunc(i=>i.logicalOr(n,o),r,null,cp)}const Is=m({logicalOr_:uL});function dL(e,t){const n=u(e,"a","logicalXor","bool"),o=u(t,"b","logicalXor","bool");return q(n.shape,o.shape),Lt(Is(e,t),zn(Lt(e,t)))}const Jl=m({logicalXor_:dL});function mL(e,t,n,o,r){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}'`),r!=null&&f(X(o),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${r} but got pad ${o}.`);const p=(b,x)=>{const w=_t(s.shape,t,n,1,o,r);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:o,dimRoundingMode:r},d=g.runKernelFunc(p,l,null,di,h);return c?y(d,[d.shape[1],d.shape[2],d.shape[3]]):d}const Ae=m({maxPool_:mL});function fL(e,t=[1,1,1],n,o,r,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}'`),r!=null&&f(X(o),()=>`Error in maxPool3d: pad must be an integer when using, dimRoundingMode ${r} but got pad ${o}.`);const l=(x,w)=>{a==null&&(a=[1,1,1]);const L=Qt(c.shape,t,n,a,o,r,i),S=x.maxPool3d(c,L);return w([c,S]),S},h={x:c},d={filterSize:t,strides:n,pad:o,dimRoundingMode:r,dataFormat:i,dilations:a},b=g.runKernelFunc(l,h,null,mi,d);return p?y(b,[b.shape[1],b.shape[2],b.shape[3],b.shape[4]]):b}const Xl=m({maxPool3d_:fL});function gL(e,t,n,o,r=!1){const i=u(e,"x","maxPoolWithArgmax"),a={x:i},s={filterSize:t,strides:n,pad:o,includeBatchInIndex:r},c=g.runKernel(up,a,s);return{result:c[0],indexes:c[1]}}const Zl=m({maxPoolWithArgmax_:gL});function Ce(e,t="float32"){if(t==="complex64"){const o=Ce(e,"float32"),r=Ce(e,"float32");return Ye(o,r)}const n=Pt(Q(e),t);return g.makeTensor(n,e,t)}function vt(e,t="float32"){if(t==="complex64"){const o=vt(e,"float32"),r=Ce(e,"float32");return Ye(o,r)}const n=ss(Q(e),t);return g.makeTensor(n,e,t)}function bL(e,t=null,n=!1){const o=u(e,"x","mean"),r=z(t,o.shape),i=Jp(o.shape,r),a=i[1],s=Q(a),c=Ke(p=>{const l=C(s),h=l.dtype===p.dtype?p:_(p,l.dtype),d=F(h,l),b=U(d,t,n),x=w=>{const L=p.shape.slice();r.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(o)}const Sn=m({mean_:bL});function wL(e,t=null,n=!1){const o=u(e,"x","min"),r=(s,c)=>{const p=z(t,o.shape);let l=p;const h=ge(l,o.rank);let d=o;h!=null&&(d=K(o,h),l=De(l.length,o.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([o,x]),x},i={x:o},a={axis:t,keepDims:n};return g.runKernelFunc(r,i,null,fi,a)}const In=m({min_:wL});function xL(e,t){let n=u(e,"a","minimum"),o=u(t,"b","minimum");[n,o]=V(n,o),n.dtype==="bool"&&(n=_(n,"int32"),o=_(o,"int32")),q(n.shape,o.shape);const r=(a,s)=>{const c=a.minimum(n,o);return s([n,o]),c},i={a:n,b:o};return g.runKernelFunc(r,i,null,gi)}const Yn=m({minimum_:xL});function yL(e,t){let n=u(e,"a","mod"),o=u(t,"b","mod");[n,o]=V(n,o);const r=(a,s)=>{const c=a.mod(n,o);return s([n,o]),c},i={a:n,b:o};return g.runKernelFunc(r,i,null,bi)}const Ts=m({mod_:yL});function LL(e){const t=u(e,"x","square"),n={},o=[t],r=[];return g.runKernelFunc((i,a)=>(a([t]),i.square(t)),{x:t},null,"Square",n,o,r)}const H=m({square_:LL});function vL(e,t=null,n=!1){e=u(e,"x","moments");const o=z(t,e.shape),r=Sn(e,o,n);let i=r.shape;n||(i=we(r.shape,o));const a=H(O(_(e,"float32"),y(r,i))),s=Sn(a,o,n);return{mean:r,variance:s}}const Ql=m({moments_:vL});function SL(e,t,n,o){const r=u(t,"data","multiRNNCell"),i=Zt(n,"c","multiRNNCell"),a=Zt(o,"h","multiRNNCell");let s=r;const c=[];for(let h=0;h<e.length;h++){const d=e[h](s,i[h],a[h]);c.push(d[0]),c.push(d[1]),s=d[1]}const p=[],l=[];for(let h=0;h<c.length;h+=2)p.push(c[h]),l.push(c[h+1]);return[p,l]}const eh=m({multiRNNCell_:SL});function IL(e,t,n,o=!1){const r=u(e,"logits","multinomial"),i=r.size,a=r.rank;if(i<2)throw new Error(`Error in multinomial: you need at least 2 outcomes, but got ${i}.`);if(a>2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${a}`);n=n||Math.random();const s=a===1?y(r,[1,-1]):r,c=g.runKernelFunc(p=>p.multinomial(s,o,t,n),{logits2D:s});return a===1?y(c,[c.size]):c}const th=m({multinomial_:IL});function TL(e,t){let n=u(e,"a","notEqual"),o=u(t,"b","notEqual");[n,o]=V(n,o),q(n.shape,o.shape);const r=a=>a.notEqual(n,o),i={a:n,b:o};return g.runKernelFunc(r,i,null,dp)}const Vn=m({notEqual_:TL});function AL(e,t,n=1,o=0){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);const r=u(e,"indices","oneHot","int32"),i=[...r.shape,t],a=(p,l)=>(l([r]),y(p.oneHot(y(r,[r.size]),t,n,o),i)),s={indices:r},c={depth:t,onValue:n,offValue:o};return g.runKernelFunc(a,s,null,Li,c)}const Go=m({oneHot_:AL});function NL(e){const t=u(e,"x","onesLike"),n=(r,i)=>{if(t.dtype==="complex64"){const a=Ua(zt(t)),s=W(nn(t));return Ye(a,s)}return r.onesLike(t)},o={x:t};return g.runKernelFunc(n,o,null,yi)}const Ua=m({onesLike_:NL});function RL(e,t){const n=u(e,"v1","outerProduct"),o=u(t,"v2","outerProduct");f(n.rank===1&&o.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${o.rank}.`);const r=y(n,[-1,1]),i=y(o,[1,-1]);return Y(r,i)}const nh=m({outerProduct_:RL});function _L(e,t,n=0){const o=u(e,"x","pad");if(o.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");const r=(s,c)=>(c([o]),s.pad(o,t,n)),i={paddings:t,constantValue:n},a={x:o};return g.runKernelFunc(r,a,null,vi,i)}const qe=m({pad_:_L});function CL(e,t,n=0){return f(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),qe(e,[t],n)}const oh=m({pad1d_:CL});function EL(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."),qe(e,t,n)}const rh=m({pad2d_:EL});function OL(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."),qe(e,t,n)}const ih=m({pad3d_:OL});function kL(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."),qe(e,t,n)}const sh=m({pad4d_:kL});function DL(e,t,n){const o=u(e,"x","spaceToBatchND");f(o.rank>=1+t.length,()=>`input rank ${o.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(o.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 ${o.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`);const r=s=>s.spaceToBatchND(o,t,n),i={x:o},a={blockShape:t,paddings:n};return g.runKernelFunc(r,i,null,qi,a)}const Kn=m({spaceToBatchND_:DL});function UL(e,t,n,o,r,i){r==null&&(r=[1,1]),i==null&&(i=1),o===0&&(o="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,r),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${i} and dilations '${r}'`);const p=_t(s.shape,t,i,r,o),l=[p.dilationHeight,p.dilationWidth];let h;o==="same"?h=ML([p.filterHeight,p.filterWidth],l):h=[[0,0],[0,0]];const d=l[0]===1&&l[1]===1,[b,x]=FL([p.inHeight,p.inWidth],l,h),w=d?o:"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 FL(e,t,n){const o=n.map(l=>l[0]),r=n.map(l=>l[1]),i=e.concat(o,r),a=t.map((l,h)=>(l-i[h]%l)%l),s=r.map((l,h)=>l+a[h]),c=t.map((l,h)=>[o[h],s[h]]),p=t.map((l,h)=>[0,a[h]]);return[c,p]}function ML(e,t){const n=e.map((a,s)=>a+(a-1)*(t[s]-1)),o=n.map(a=>a-1),r=o.map(a=>Math.floor(a/2)),i=o.map((a,s)=>a-r[s]);return o.map((a,s)=>[r[s],i[s]])}const ah=m({pool_:UL});function WL(e,t){let n=u(e,"base","pow"),o=u(t,"exp","pow");[n,o]=V(n,o);const r={a:n,b:o},i=(a,s)=>{const c=a.pow(n,o);return s([n,o,c]),c};return g.runKernelFunc(i,r,null,Si)}const Je=m({pow_:WL});function BL(e,t){const n=u(e,"x","prelu"),o=u(t,"alpha","prelu"),r=(a,s)=>{const c=a.prelu(n,o);return s([n,o]),c},i={x:n,alpha:o};return g.runKernelFunc(r,i,null,Ii)}const As=m({prelu_:BL});function ch(e,t=!1){console.log(e.toString(t))}function $L(e,t=null,n=!1){let o=u(e,"x","prod");const r=s=>{o.dtype==="bool"&&(o=_(o,"int32"));const c=z(t,o.shape),p=ge(c,o.rank);let l=c,h=o;p!=null&&(h=K(o,p),l=De(l.length,o.rank));let d=s.prod(h,l);if(n){const b=we(d.shape,c);d=y(d,b)}return d},i={x:o},a={axis:t,keepDims:n};return g.runKernelFunc(r,i,null,bp,a)}const ph=m({prod_:$L});function jL(e,t,n){const o=Q(e);let r=null;if(n==null||n==="float32")r=new Float32Array(o);else if(n==="int32")r=new Int32Array(o);else if(n==="bool")r=new Uint8Array(o);else throw new Error(`Unknown data type ${n}`);for(let i=0;i<o;i++)r[i]=t();return g.makeTensor(r,e,n)}const lh=m({rand_:jL});const Yd={};Re(Yd,{TEST_EPSILON_FLOAT16:()=>Vd,expectArrayBuffersEqual:()=>VL,expectArraysClose:()=>PL,expectArraysEqual:()=>HL,expectNumbersClose:()=>zL,expectPromiseToFail:()=>qL,expectValuesInRange:()=>YL,testEpsilon:()=>hh});const GL=.001,Vd=.1;function PL(e,t,n){return n==null&&(n=hh()),uh(e,t,(o,r)=>dh(o,r,n))}function hh(){return g.backend.floatPrecision()===32?GL:Vd}function uh(e,t,n){let o=!0;if((_e(e)||_e(t))&&(o=!1),_e(e)&&_e(t)&&(o=!0),o){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 r=_e(e)?e:$t(e),i=_e(t)?t:$t(t);if(r.length!==i.length)throw new Error(`Arrays have different lengths actual: ${r.length} vs expected: ${i.length}.
Actual: ${r}.
Expected: ${i}.`);for(let a=0;a<i.length;++a){const s=r[a],c=i[a];if(!n(s,c))throw new Error(`Arrays differ: actual[${a}] = ${s}, expected[${a}] = ${c}.
Actual: ${r}.
Expected: ${i}.`)}}function qL(e,t){e().then(()=>t.fail(),()=>t())}function HL(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])?uh(e,n,(o,r)=>o==r):uh(e,t,(o,r)=>dh(o,r,0))}function zL(e,t,n){if(n==null&&(n=hh()),!dh(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function dh(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function YL(e,t,n){for(let o=0;o<e.length;o++)if(e[o]<t||e[o]>n)throw new Error(`Value out of range:${e[o]} low: ${t}, high: ${n}`)}function VL(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}const Wa=gu(Ou());class Ns{constructor(e,t,n,o,r){this.mean=e,this.stdDev=t,this.dtype=n,this.nextVal=NaN,this.truncated=o,this.truncated&&(this.upper=this.mean+this.stdDev*2,this.lower=this.mean-this.stdDev*2);const i=r||Math.random();this.random=Wa.alea(i.toString())}nextValue(){if(!isNaN(this.nextVal)){const o=this.nextVal;return this.nextVal=NaN,o}let e,t,n=!1;for(;!n;){let o,r,i;do o=2*this.random()-1,r=2*this.random()-1,i=o*o+r*r;while(i>=1||i===0);const a=Math.sqrt(-2*Math.log(i)/i);e=this.mean+this.stdDev*o*a,t=this.mean+this.stdDev*r*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 Kd{constructor(e,t,n,o){this.alpha=e,this.beta=1/t,this.dtype=n;const r=o||Math.random();this.randu=Wa.alea(r.toString()),this.randn=new Ns(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,o,r,i;for(;;){do o=this.randn.nextValue(),i=1+this.c*o;while(i<=0);if(i*=i*i,e=o*o,t=1-.331*e*e,n=.5*e+this.d*(1-i+Math.log(i)),r=this.randu(),r<t||Math.log(r)<n)break}return i=1/this.beta*this.d*i,this.alpha<1&&(i*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(i)}convertValue(e){return this.dtype==="float32"?e:Math.round(e)}}class Jd{constructor(e=0,t=1,n,o){if(this.canReturnFloat=()=>this.dtype==null||this.dtype==="float32",this.min=e,this.range=t-e,this.dtype=n,o==null&&(o=Math.random()),typeof o=="number"&&(o=o.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=Wa.alea(o)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}function KL(e,t,n=1,o="float32",r){if(n==null&&(n=1),o==null&&(o="float32"),o!=="float32"&&o!=="int32")throw new Error(`Unsupported data type ${o}`);const i=new Kd(t,n,o,r),a=Be(e,o);for(let s=0;s<a.values.length;s++)a.values[s]=i.nextValue();return a.toTensor()}const mh=m({randomGamma_:KL});function JL(e,t=0,n=1,o,r){if(o!=null&&o==="bool")throw new Error(`Unsupported data type ${o}`);const i=new Ns(t,n,o,!1,r),a=Be(e,o);for(let s=0;s<a.values.length;s++)a.values[s]=i.nextValue();return a.toTensor()}const fh=m({randomNormal_:JL});function XL(e,t=0,n=1,o="float32",r){const i=Be(e,o),a=new Jd(t,n,null,r);for(let s=0;s<i.values.length;s++)i.values[s]=a.nextValue();return i.toTensor()}const Rs=m({randomUniform_:XL});function ce(e,t){at(e);const n=We(e,t);if(n.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");const o=null;return ze(e,o,n,t)}function Po(e,t,n=1,o="float32"){if(n===0)throw new Error("Cannot have a step of zero");const r=()=>{const a=e===t,s=e<t&&n<0,c=t<e&&n>1;if(a||s||c)return Ce([0],o);const p=Math.abs(Math.ceil((t-e)/n)),l=Pt(p,o);t<e&&n===1&&(n=-1),l[0]=e;for(let h=1;h<l.length;h++)l[h]=l[h-1]+n;return ce(l,o)},i={start:e,stop:t,step:n,dtype:o};return g.runKernelFunc(r,{},null,wp,i)}function ZL(e){const t=u(e,"x","reciprocal"),n={x:t};return g.runKernelFunc((o,r)=>{const i=o.reciprocal(t);return r([t]),i},n,null,Ti)}const gh=m({reciprocal_:ZL});function QL(e){const t=u(e,"x","relu"),n=(r,i)=>(i([t]),t.dtype==="bool"?_(t,"int32"):r.relu(t)),o={x:t};return g.runKernelFunc(n,o,null,Ai)}const ie=m({relu_:QL});function ev(e){const t=u(e,"x","relu6"),n=(r,i)=>(i([t]),t.dtype==="bool"?_(t,"int32"):r.relu6(t)),o={x:t};return g.runKernelFunc(n,o,null,Ci)}const _s=m({relu6_:ev});function tv(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 bh=m({reverse1d_:tv});function nv(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 wh=m({reverse2d_:nv});function ov(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 xh=m({reverse3d_:ov});function rv(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 yh=m({reverse4d_:rv});function Lh(e,t,n=0){let o=[];if(typeof t=="number")f(e.shape[n]%t===0,()=>"Number of splits must evenly divide the axis."),o=new Array(t).fill(e.shape[n]/t);else{const r=t.reduce((a,s)=>(s===-1&&(a+=1),a),0);f(r<=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."),o=t}return o}function iv(e,t,n=0){const o=u(e,"x","split"),r=(s,c)=>{const p=z(n,o.shape)[0],l=Lh(o,t,p);return s.split(o,l,p)},i={x:o},a={numOrSizeSplits:t,axis:n};return g.runKernelFunc(r,i,null,Hi,a)}const Yt=m({split_:iv});function sv(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 o=e.size/n;let r;if(t!=null&&t<n){const x=e.shape.map(L=>0),w=e.shape.map(L=>L);w[e.shape.length-1]=t,r=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,r=Z([e,Ce(x)],e.shape.length-1),n=t}else r=e;const i=W(r),a=y(Ye(r,i),[o,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=r.shape.slice();return b[r.shape.length-1]=c,y(Ye(h[0],d[0]),b)}const Jn=m({rfft_:sv});function av(e){const t=u(e,"x","round"),n={x:t};return g.runKernelFunc(o=>o.round(t),n,null,Oi)}const vh=m({round_:av});function cv(e){const t=u(e,"x","rsqrt"),n={x:t};return g.runKernelFunc((o,r)=>{const i=o.rsqrt(t);return r([t]),i},n,null,ki)}const Cs=m({rsqrt_:cv});function pv(e){const t=u(e,"x","selu"),n=(r,i)=>{const a=r.selu(t);return i([t]),a},o={x:t};return g.runKernelFunc(n,o,null,Fi)}const Sh=m({selu_:pv});function lv(e,t,n,o,r,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,o,r,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_:lv});async function hv(e,t){const n=u(e,"x","setdiff1d"),o=u(t,"y","setdiff1d");f(n.dtype===o.dtype,()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${o.dtype}).`),f(n.rank===1,()=>`x should be 1D tensor, but got x (${n.shape}).`),f(o.rank===1,()=>`y should be 1D tensor, but got y (${o.shape}).`);const r=await n.data(),i=await o.data(),a=new Set(i);let s=0;for(let l=0;l<r.length;l++)a.has(r[l])||s++;const c=new Fo([s],n.dtype),p=new Fo([s],"int32");for(let l=0,h=0;l<r.length;l++)a.has(r[l])||(c.values[h]=r[l],p.values[h]=l,h++);return[c.toTensor(),p.toTensor()]}const Ih=hv;function uv(e){const t=u(e,"x","sign"),n={x:t};return g.runKernelFunc(o=>o.sign(t),n,null,Bi)}const Th=m({sign_:uv});function dv(e){const t=u(e,"x","sin"),n={x:t};return g.runKernelFunc((o,r)=>{const i=o.sin(t);return r([t]),i},n,null,Ui)}const Es=m({sin_:dv});function mv(e){const t=u(e,"x","sinh"),n={x:t};return g.runKernelFunc((o,r)=>{const i=o.sinh(t);return r([t]),i},n,null,Wi)}const Os=m({sinh_:mv});function fv(e,t,n){const o=u(e,"x","slice1d");return f(o.rank===1,()=>`slice1d expects a rank-1 tensor, but got a rank-${o.rank} tensor`),G(o,[t],[n])}const Ah=m({slice1d_:fv});function gv(e,t,n){const o=u(e,"x","slice2d");return f(o.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${o.rank} tensor`),G(o,t,n)}const Nh=m({slice2d_:gv});function bv(e,t,n){const o=u(e,"x","slice3d");return f(o.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${o.rank} tensor`),G(o,t,n)}const ks=m({slice3d_:bv});function wv(e,t,n){const o=u(e,"x","slice4d");return f(o.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${o.rank} tensor`),G(o,t,n)}const Rh=m({slice4d_:wv});function xv(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 o={logits:n},r={dim:t};return g.runKernelFunc((i,a)=>{const s=i.softmax(n,t);return a([s]),s},o,null,zi,r)}const on=m({softmax_:xv});function yv(e){const t=u(e,"x","sqrt"),n={x:t};return g.runKernelFunc((o,r)=>{const i=o.sqrt(t);return r([t]),i},n,null,Gi)}const me=m({sqrt_:yv});function Lv(e,t){let n=u(e,"a","squaredDifference"),o=u(t,"b","squaredDifference");[n,o]=V(n,o),q(n.shape,o.shape);const r=(s,c)=>{const p=s.squaredDifference(n,o);return c([n,o]),p},i={a:n,b:o},a={};return g.runKernelFunc(r,i,null,Yi,a)}const Zn=m({squaredDifference_:Lv});function vv(e,t){const n=u(e,"x","squeeze");return y(n,Ep(n.shape,t).newShape)}const Qn=m({squeeze_:vv});function Sv(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 o=n[0].rank,r=n[0].shape,i=n[0].dtype;f(t<=o,()=>"Axis must be <= rank of the tensor"),n.forEach(s=>{P(r,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_:Sv});function Iv(e,t=0){const n=u(e,"x","step"),o={x:n},r={alpha:t};return g.runKernelFunc(i=>i.step(n,t),o,null,ns,r)}const Dt=m({step_:Iv});function Tv(e,t,n,o,r=0,i=0,a=0,s=0,c=0){o==null&&(o=new Array(t.length));let p=u(e,"x","stridedSlice");const l=b=>{const x=ds(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=ds(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=fl(r,D,$,t,p.shape),n=gl(i,D,$,n,p.shape),o=ml(o,D,$,p.shape)}else for(let D=0;D<p.rank;D++)t[D]=wl(r,t,o,p.shape,D,a),n[D]=xl(i,n,o,p.shape,D,a),o[D]=bl(o,D,a);const I=ds(c);I.forEach(D=>{n[D]=t[D]+1,o[D]=1});const N=dl(t,n,o),A=N.filter((D,$)=>I.indexOf($)===-1),E=o.every(D=>D===1);if(E)return y(G(p,t,N),A);const M=b.stridedSlice(p,t,n,o);return y(M,A)},h={x:p},d={begin:t,end:n,strides:o,beginMask:r,endMask:i,ellipsisMask:a,newAxisMask:s,shrinkAxisMask:c};return g.runKernelFunc(l,h,null,Tp,d)}const _h=m({stridedSlice_:Tv});function Av(e){const t=u(e,"x","tan"),n={x:t};return g.runKernelFunc((o,r)=>{const i=o.tan(t);return r([t]),i},n,null,Ki)}const Ch=m({tan_:Av});function mt(e,t,n){if(at(e),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");const o=We(e,n);if(o.length!==2&&o.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(o.length===1&&t==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return ze(e,t,o,n)}function eo(e,t,n){if(at(e),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");const o=We(e,n);if(o.length!==3&&o.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(o.length===1&&t==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return ze(e,t,o,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 o=We(e,n);if(o.length!==4&&o.length!==1)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(o.length===1&&t==null)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return ze(e,t,o,n)}function Eh(e,t,n){if(at(e),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");const o=We(e,n);if(o.length!==5&&o.length!==1)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(o.length===1&&t==null)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return ze(e,t,o,n)}function Oh(e,t,n){if(at(e),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");const o=We(e,n);if(o.length!==6&&o.length!==1)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(o.length===1&&t==null)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return t=t||o,ze(e,t,o,n)}function Nv(e,t=1,n=!0){const o=u(e,"x","topk");if(o.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");const r=o.shape[o.shape.length-1];if(t>r)throw new Error(`'k' passed to topk() must be <= the last dimension (${r}) but got ${t}`);const i={x:o},a={k:t,sorted:n},[s,c]=g.runKernelFunc(p=>p.topk(o,t,n),i,null,Ap,a);return{values:s,indices:c}}const kh=m({topk_:Nv});function Rv(e,t=0,n=1,o,r){if(o!=null&&o==="bool")throw new Error("Unsupported data type $ { dtype }");const i=new Ns(t,n,o,!0,r),a=Be(e,o);for(let s=0;s<a.values.length;s++)a.values[s]=i.nextValue();return a.toTensor()}const Dh=m({truncatedNormal_:Rv});function _v(e,t,n){const o=u(e,"x","unsortedSegmentSum"),r=u(t,"segmentIds","unsortedSegmentSum","int32");f(X(n),()=>"numSegments must be of dtype int");const i={x:o,segmentIds:r},a={numSegments:n},s=(c,p)=>{const l=c.unsortedSegmentSum(o,r,n);return p([r]),l};return g.runKernelFunc(s,i,null,es,a)}const Ds=m({unsortedSegmentSum_:_v});function Cv(e,t=0){const n=u(e,"x","unstack");f(t>=-n.shape.length&&t<n.shape.length,()=>`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`),t<0&&(t+=n.shape.length);const o={value:n},r={axis:t},i=a=>a.unstack(n,t);return g.runKernelFunc(i,o,null,Qi,r)}const Ie=m({unstack_:Cv});function Fh(e,t=!0,n,o){return g.makeVariable(e,t,n,o)}function Ba(e,t){const n=[];for(let i=0;i<t.length;i++)t[i]&&n.push(i);const o=Be(e,"int32"),r=Be([n.length,e.length],"int32");for(let i=0;i<n.length;i++){const a=o.indexToLoc(n[i]),s=i*e.length;r.values.set(a,s)}return r.toTensor()}async function Ev(e){const t=u(e,"condition","whereAsync","bool"),n=await t.data(),o=Ba(t.shape,n);return e!==t&&t.dispose(),o}const Fs=Ev;async function Ov(e,t,n){const o=u(e,"tensor","boolMask"),r=u(t,"mask","boolMask","bool"),i=n==null?0:n,a=r.rank,s=o.shape;f(a>0,()=>"mask cannot be scalar"),P(s.slice(i,i+a),r.shape,"mask's shape must match the first K dimensions of tensor's shape,");let c=1;for(let w=i;w<i+a;w++)c*=s[w];const p=s.slice(0,i).concat([c],s.slice(i+a)),l=y(o,p),h=y(r,[-1]),d=await Fs(h),b=Qn(d,[1]),x=qn(l,b,i);return e!==o&&o.dispose(),t!==r&&r.dispose(),b.dispose(),l.dispose(),h.dispose(),d.dispose(),x}const Xd=Ov;function kv(e,t){Le("strict variants of ops have been deprecated and will be removed in future");const n=u(e,"a","notEqualStrict"),o=u(t,"b","notEqualStrict");return P(n.shape,o.shape,"Error in notEqualStrict: "),Vn(n,o)}function Dv(e,t){Le("strict variants of ops have been deprecated and will be removed in future");const n=u(e,"a","lessStrict"),o=u(t,"b","lessStrict");return P(n.shape,o.shape,"Error in lessStrict: "),Hn(n,o)}function Fv(e,t){Le("strict variants of ops have been deprecated and will be removed in future");const n=u(e,"a","equalStrict"),o=u(t,"b","equalStrict");return P(n.shape,o.shape,"Error in equalStrict: "),tn(n,o)}function Mv(e,t){Le("strict variants of ops have been deprecated and will be removed in future");const n=u(e,"a","lessEqualStrict"),o=u(t,"b","lessEqualStrict");return P(n.shape,o.shape,"Error in lessEqualStrict: "),ut(n,o)}function Uv(e,t){Le("strict variants of ops have been deprecated and will be removed in future");const n=u(e,"a","greaterStrict"),o=u(t,"b","greaterStrict");return P(n.shape,o.shape,"Error in greaterStrict: "),tt(n,o)}function Wv(e,t){Le("strict variants of ops have been deprecated and will be removed in future");const n=u(e,"a","greaterEqualStrict"),o=u(t,"b","greaterEqualStrict");return P(n.shape,o.shape,"Error in greaterEqualStrict: "),ht(n,o)}const Zd=m({equalStrict_:Fv}),Qd=m({greaterEqualStrict_:Wv}),em=m({greaterStrict_:Uv}),tm=m({lessEqualStrict_:Mv}),nm=m({lessStrict_:Dv}),om=m({notEqualStrict_:kv});function Bv(e,t){Le("strict variants of ops have been deprecated and will be removed in future");const n=u(e,"a","addStrict"),o=u(t,"b","addStrict");return P(n.shape,o.shape,"Error in addStrict: "),R(n,o)}function $v(e,t){Le("strict variants of ops have been deprecated and will be removed in future");const n=u(e,"a","subStrict"),o=u(t,"b","subStrict");return P(n.shape,o.shape,"Error in subStrict: "),O(n,o)}function jv(e,t){return Le("strict variants of ops have been deprecated and will be removed in future"),P(e.shape,t.shape,"Error in powStrict: "),Je(e,t)}function Gv(e,t){Le("strict variants of ops have been deprecated and will be removed in future");const n=u(e,"a","mul"),o=u(t,"b","mul");return P(n.shape,o.shape,"Error in multiplyStrict: "),v(n,o)}function Pv(e,t){Le("strict variants of ops have been deprecated and will be removed in future");const n=u(e,"a","div"),o=u(t,"b","div");return P(n.shape,o.shape,"Error in divideStrict: "),F(n,o)}function qv(e,t){Le("strict variants of ops have been deprecated and will be removed in future");const n=u(e,"a","modStrict"),o=u(t,"b","modStrict");return P(n.shape,o.shape,"Error in modStrict: "),Ts(n,o)}function Hv(e,t){Le("strict variants of ops have been deprecated and will be removed in future");const n=u(e,"a","minimumStrict"),o=u(t,"b","minimumStrict");return P(n.shape,o.shape,"Error in minimumStrict: "),Yn(n,o)}function zv(e,t){Le("strict variants of ops have been deprecated and will be removed in future");const n=u(e,"a","maximumStrict"),o=u(t,"b","maximumStrict");return P(n.shape,o.shape,"Error in maximumStrict: "),kt(n,o)}function Yv(e,t){Le("strict variants of ops have been deprecated and will be removed in future");const n=u(e,"a","squaredDifferenceStrict"),o=u(t,"b","squaredDifferenceStrict");return P(n.shape,o.shape,"Error in squaredDifferenceStrict: "),Zn(n,o)}const rm=m({addStrict_:Bv}),im=m({divStrict_:Pv}),sm=m({maximumStrict_:zv}),am=m({minimumStrict_:Hv}),cm=m({modStrict_:qv}),pm=m({mulStrict_:Gv}),lm=m({powStrict_:jv}),hm=m({squaredDifferenceStrict_:Yv}),um=m({subStrict_:$v});function Vv(e,t="euclidean",n=null,o=!1){e=u(e,"x","norm");const r=dm(e,t,n);let i=r.shape;if(o){const a=z(n,e.shape);i=we(r.shape,a)}return y(r,i)}function dm(e,t,n=null){if(e.rank===0)return Ee(e);if(e.rank!==1&&n===null)return dm(y(e,[-1]),t,n);if(e.rank===1||typeof n=="number"||Array.isArray(n)&&n.length===1){if(t===1)return U(Ee(e),n);if(t===Infinity)return dt(Ee(e),n);if(t===-Infinity)return In(Ee(e),n);if(t==="euclidean"||t===2)return me(U(Je(Ee(e),C(2,"int32")),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(n)&&n.length===2){if(t===1)return dt(U(Ee(e),n[0]),n[1]-1);if(t===Infinity)return dt(U(Ee(e),n[1]),n[0]);if(t===-Infinity)return In(U(Ee(e),n[1]),n[0]);if(t==="fro"||t==="euclidean")return me(U(H(e),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${n}`)}const qo=m({norm_:Vv});function Kv(e,t,n,o,r=!0){const i=u(e,"v","movingAverage"),a=u(t,"x","movingAverage"),s=u(n,"decay","movingAverage");qp(i,a),f(Te(i.shape,a.shape),()=>"Shape mismatch in v and x");const c=C(1),p=O(c,s);let l=v(O(a,i),p);if(r){f(o!=null,()=>"When using zeroDebias: true, step is required.");const h=u(o,"step","movingAverage");l=F(l,O(c,Je(s,h)))}return R(i,l)}const mm=m({movingAverage_:Kv});const fm={};Re(fm,{calculateShapes:()=>gm,validateInput:()=>$a,validateUpdateShape:()=>Mh});function Mh(e,t,n){const o=t.rank>1?t.shape[t.rank-1]:1,r=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: ${o}, and batchDim: ${r}.`;if(n.rank<r)throw new Error(i+` update.rank < ${r}. `);if(e.length<o+(n.rank-r))throw new Error(i+` Output shape length < ${o+(n.rank-r)}`);if(n.rank!==r+e.length-o)throw new Error(i+` update.rank != ${r+e.length-o}`);for(let a=0;a<r;++a)if(n.shape[a]!==t.shape[a])throw new Error(i+` updates.shape[${a}] (${n.shape[a]}) != indices.shape[${a}] (${t.shape[a]}).`);for(let a=0;a<n.rank-r;++a)if(n.shape[a+r]!==e[a+o])throw new Error(i+` updates.shape[${a+r}] (${n.shape[a+r]}) != shape[${a+r}] (${e[a+r]})`)}function $a(e,t,n){if(t.rank<1)throw new Error(`tf.scatterND() expects the indices to be rank 1 or higher, but the rank was ${t.rank}.`);if(e.rank<1)throw new Error(`tf.scatterND() expects the updates to be rank 1 or higher, but the rank was ${e.rank}.`);if(t.dtype!=="int32")throw new Error(`The dtype of 'indices' should be int32, but got dtype: ${t.dtype}`);if(n.length<1)throw new Error(`Output rank must be greater or equal to 1, but got shape: ${n}`);if(n.length===0){if(t.size===0)throw new Error(`Indices specified for empty output. indices shape: ${t.shape}`);if(e.size===0)throw new Error(`Updates specified for empty output. updates shape: ${e.shape}`)}Mh(n,t,e)}function gm(e,t,n){const o=t.shape.length,r=o>1?t.shape[o-1]:1,i=n.length;let a=1;for(let h=r;h<i;++h)a*=n[h];const s=r<1?1:r,c=Q(t.shape)/s,p=[...Gt(n.slice(0,r)),1],l=Q(n);return{sliceRank:r,numUpdates:c,sliceSize:a,strides:p,outputSize:l}}function Jv(e,t,n){const o=u(e,"indices","scatterND","int32"),r=u(t,"updates","scatterND");$a(r,o,n);const i=c=>c.scatterND(o,r,n),a={indices:o,updates:r},s={shape:n};return g.runKernelFunc(i,a,null,vp,s)}const bm=m({scatterND_:Jv});function wm(e,t,n,o){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 r=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===r))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${r}]`);if(t.dtype!==o.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}function Xv(e,t,n,o=0){const r=u(e,"sparseIndices","sparseToDense","int32"),i=u(t,"sparseValues","sparseToDense"),a=u(o,"defaultValue","sparseToDense",i.dtype);wm(r,i,n,a);const s={sparseIndices:r,sparseValues:i,defaultValue:a},c={outputShape:n};return g.runKernelFunc(p=>p.sparseToDense(r,i,n,a),s,null,Ip,c)}const xm=m({sparseToDense_:Xv});function Zv(e,t){const n=u(t,"indices","gatherND","int32"),o=u(e,"x","gatherND"),r=a=>a.gatherND(o,n),i={params:o,indices:n};return g.runKernelFunc(r,i,null,Qc)}const ym=m({gatherND_:Zv});function Lm(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 o=0;o<e.shape.length;o++)t[o]==null&&e.shape[o]!=null?n.push(e.shape[o]):n.push(t[o]);return n}return t}function Qv(e,t,n,o){const r=u(e,"x","dropout");if(f(r.dtype==="float32",()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${r.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?r.clone():r;const i=Lm(r,n),a=1-t,s=F(Pn(R(Rs(i,0,1,"float32",o),a)),a);return v(r,s)}const vm=m({dropout_:Qv});function ja(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function Ho(e,t,n){const o=1-e%2,r=new Float32Array(e);for(let i=0;i<e;++i){const a=2*Math.PI*i/(e+o-1);r[i]=t-n*Math.cos(a)}return ce(r,"float32")}async function eS(e,t,n=1){const o=u(e,"predictions","inTopK"),r=u(t,"targets","inTopK");f(o.rank>1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${o.rank}`),f(o.rank-1===r.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${o.rank} and targets rank ${r.rank}`),P(o.shape.slice(0,o.shape.length-1),r.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");const i=o.shape[o.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 o.data(),s=await r.data(),[c,p]=[a.length/i,i],l=Oo("bool",c);for(let h=0;h<c;h++){const d=h*p,b=a.subarray(d,d+p),x=[];for(let w=0;w<b.length;w++)x.push({value:b[w],index:w});x.sort((w,L)=>L.value-w.value),l[h]=0;for(let w=0;w<n;w++)if(x[w].index===s[h]){l[h]=1;break}}return e!==o&&o.dispose(),t!==r&&r.dispose(),Ge(l,r.shape,"bool")}const Sm=eS;function tS(e,t,n,o,r,i="NHWC",a){let s=e;e.rank===3&&(s=y(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let c=t;c.rank===3&&(c=y(t,[1,t.shape[0],t.shape[1],t.shape[2]])),f(s.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${s.shape}.`),f(c.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${c.shape}.`),f(n.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`);const p=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(r),()=>`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode ${a} but got pad ${r}.`);const h=x=>{const w=1,L=yn(i),S=je(s.shape,n,o,w,r,a,!1,L);return x.conv2dDerFilter(s,c,S)},d={x:s,dy:c},b={strides:o,pad:r,dataFormat:i,dimRoundingMode:a};return g.runKernelFunc(h,d,null,Wc,b)}const zo=m({conv2DBackpropFilter_:tS});function to(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 no(e,t){let n=t;const o=ae(e.shape,t.shape);return o.length>0&&(n=U(n,o)),y(n,e.shape)}function oo(e,t,n){if(t==="linear")return e;if(t==="relu")return ie(e);if(t==="elu")return ws(e);if(t==="relu6")return _s(e);if(t==="prelu")return As(e,n);throw new Error(`Unknown fused activation ${t}.`)}const ro=(e,t)=>{const n=e>0;return!n||t==="linear"};function nS({x:e,filter:t,strides:n,pad:o,dataFormat:r="NHWC",dilations:i=[1,1],dimRoundingMode:a,bias:s,activation:c="linear",preluActivationWeights:p}){if(c=c||"linear",ro(g.state.gradientDepth,c)===!1){let E=xe(e,t,n,o,r,i,a);return s!=null&&(E=R(E,s)),oo(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(o),()=>`Error in fused conv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`),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(r==="NHWC",()=>`Error in conv2d: got dataFormat of ${r} but only NHWC is currently supported.`);const x=je(d.shape,h.shape,n,i,o,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=to(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 oe=jo($.shape,te,D,n,o),he=zo($,te,D.shape,n,o),ye=[oe,he];if(j!=null){const Me=no(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:o,dataFormat:r,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 oS=m({fusedConv2d_:nS});function rS(e,t,n,o){let r=e;e.rank===3&&(r=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(r,i,o),s={x:r,dy:i};return g.runKernelFunc(a,s,null,Pc)}const Ga=m({depthwiseConv2dNativeBackpropFilter_:rS});function iS(e,t,n,o){let r=t,i=!1;t.rank===3&&(i=!0,r=y(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const a=p=>p.depthwiseConv2DDerInput(r,n,o),s={dy:r},c=g.runKernelFunc(a,s,null,qc);return i?y(c,[c.shape[1],c.shape[2],c.shape[3]]):c}const Pa=m({depthwiseConv2dNativeBackpropInput_:iS});function sS({x:e,filter:t,strides:n,pad:o,dataFormat:r="NHWC",dilations:i=[1,1],dimRoundingMode:a,bias:s,activation:c="linear",preluActivationWeights:p}){if(ro(g.state.gradientDepth,c)===!1){let E=en(e,t,n,o,r,i,a);return s!=null&&(E=R(E,s)),oo(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(o),()=>`Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode ${a} but got pad ${o}.`);const x=je(d.shape,h.shape,n,i,o,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=to(E,B,c),oe=Pa($.shape,te,D,x),he=Ga($,te,D.shape,x);if(j!=null){const ye=no(w,te);return[oe,he,ye]}return[oe,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:o,dataFormat:r,dilations:i,dimRoundingMode:a,activation:c};if(s==null){const E=Ke((M,D,$)=>{let B=g.runKernelFunc(I,N,null,Aa,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,Aa,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 aS=m({fusedDepthwiseConv2d_:sS});function cS({a:e,b:t,transposeA:n=!1,transposeB:o=!1,bias:r,activation:i="linear",preluActivationWeights:a}){if(ro(g.state.gradientDepth,i)===!1){let j=Y(e,t,n,o);return r!=null&&(j=R(j,r)),oo(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=o?c.shape[c.rank-1]:c.shape[c.rank-2],h=n?s.shape[s.rank-1]:s.shape[s.rank-2],d=o?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=${o} 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=o?y(c,[L,d,l]):y(c,[L,l,d]);let A;r!=null&&(A=u(r,"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[oe,he,ye,Me]=te,Tt=to(y(j,ye.shape),ye,i);let ln,xo;if(!n&&!o?(ln=Y(Tt,he,!1,!0),xo=Y(oe,Tt,!0,!1)):!n&&o?(ln=Y(Tt,he,!1,!1),xo=Y(Tt,oe,!0,!1)):n&&!o?(ln=Y(he,Tt,!1,!0),xo=Y(oe,Tt,!1,!1)):(ln=Y(he,Tt,!0,!0),xo=Y(Tt,oe,!0,!0)),r!=null){const Kb=no(Me,Tt);return[ln,xo,Kb]}else return[ln,xo]},D=j=>{const te=j.fusedBatchMatMul({a:I,b:N,transposeA:n,transposeB:o,bias:A,activation:i,preluActivationWeights:E});return te},$={a:I,b:N,bias:A,preluActivationWeights:E},B={transposeA:n,transposeB:o,activation:i};if(r==null){const j=Ke((te,oe,he)=>{const ye=g.runKernelFunc(D,$,null,Ia,B);return he([te,oe,ye]),{value:y(ye,S),gradFunc:M}});return j(I,N)}else{const j=Ke((te,oe,he,ye)=>{const Me=g.runKernelFunc(D,$,null,Ia,B);return ye([te,oe,Me,he]),{value:y(Me,S),gradFunc:M}});return j(I,N,A)}}const pS=m({fusedMatMul_:cS});const Uh={};Re(Uh,{conv2d:()=>oS,depthwiseConv2d:()=>aS,matMul:()=>pS});function lS(e){return Ho(e,.54,.46)}const Im=m({hammingWindow_:lS});function hS(e){return Ho(e,.5,.5)}const qa=m({hannWindow_:hS});function uS(e,t,n,o=!1,r=0){let i=0;const a=[];for(;i+t<=e.size;)a.push(G(e,i,t)),i+=n;if(o)for(;i<e.size;){const s=i+t-e.size,c=Z([G(e,i,t-s),Pe([s],r)]);a.push(c),i+=n}return a.length===0?mt([],[0,t]):y(Z(a),[a.length,t])}const Ha=m({frame_:uS});function dS(e,t,n,o,r=qa){o==null&&(o=ja(t));const i=Ha(e,t,n),a=v(i,r(t)),s=[];for(let c=0;c<i.shape[0];c++)s.push(Jn(G(a,[c,0],[1,t]),o));return Z(s)}const Tm=m({stft_:dS});function mS(e,t,n,o,r,i){const a=u(e,"image","cropAndResize"),s=u(t,"boxes","cropAndResize","float32"),c=u(n,"boxInd","cropAndResize","int32");r=r||"bilinear",i=i||0;const p=s.shape[0];f(a.rank===4,()=>`Error in cropAndResize: image must be rank 4,but got rank ${a.rank}.`),f(s.rank===2&&s.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${p},4] but had shape ${s.shape}.`),f(c.rank===1&&c.shape[0]===p,()=>`Error in cropAndResize: boxInd must be have size [${p}] but had shape ${s.shape}.`),f(o.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${o.length}.`),f(o[0]>=1&&o[1]>=1,()=>`cropSize must be atleast [1,1], but was ${o}`),f(r==="bilinear"||r==="nearest",()=>`method must be bilinear or nearest, but was ${r}`);const l=x=>x.cropAndResize(a,s,c,o,r,i),h={image:a,boxes:s,boxInd:c},d={method:r,extrapolationValue:i,cropSize:o},b=g.runKernelFunc(l,h,null,jc,d);return b}const Am=m({cropAndResize_:mS});function fS(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},o=g.runKernel(Zc,n,{});return o}const Nm=m({flipLeftRight_:fS});function gS(e,t,n=0,o=.5){const r=u(e,"image","rotateWithOffset","float32");f(r.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${r.rank}.`);const i={image:r},a={radians:t,fillValue:n,center:o},s=g.runKernel(Np,i,a);return s}const Rm=m({rotateWithOffset_:gS});function St(e,t,n,o,r,i){o==null&&(o=.5),r==null&&(r=Number.NEGATIVE_INFINITY),i==null&&(i=0);const a=e.shape[0];return n=Math.min(n,a),f(0<=o&&o<=1,()=>`iouThreshold must be in [0, 1], but was '${o}'`),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:o,scoreThreshold:r,softNmsSigma:i}}function bS(e,t,n,o=.5,r=Number.NEGATIVE_INFINITY){const i=u(e,"boxes","nonMaxSuppression"),a=u(t,"scores","nonMaxSuppression"),s=St(i,a,n,o,r);n=s.maxOutputSize,o=s.iouThreshold,r=s.scoreThreshold;const c={maxOutputSize:n,iouThreshold:o,scoreThreshold:r};return g.runKernelFunc(p=>p.nonMaxSuppression(i,a,n,o,r),{boxes:i,scores:a},null,mp,c)}const _m=m({nonMaxSuppression_:bS});function Cm(e,t,n){const o=wS(e,t,n),r=o<0?-(o+1):o;e.splice(r,0,t)}function wS(e,t,n){return yS(e,t,n||xS)}function xS(e,t){return e>t?1:e<t?-1:0}function yS(e,t,n){let o=0,r=e.length,i=0,a=!1;for(;o<r;){i=o+(r-o>>>1);const s=n(t,e[i]);s>0?o=i+1:(r=i,a=!s)}return a?o:-o-1}function za(e,t,n,o,r){return Wh(e,t,n,o,r,0).selectedIndices}function Ya(e,t,n,o,r,i){return Wh(e,t,n,o,r,0,!1,i,!0)}function Va(e,t,n,o,r,i){return Wh(e,t,n,o,r,i,!0)}function Wh(e,t,n,o,r,i,a=!1,s=!1,c=!1){const p=[];for(let L=0;L<t.length;L++)t[L]>r&&p.push({score:t[L],boxIndex:L,suppressBeginIndex:0});p.sort(Em);const l=i>0?-.5/i:0,h=[],d=[];for(;h.length<n&&p.length>0;){const L=p.pop(),{score:S,boxIndex:I,suppressBeginIndex:N}=L;if(S<r)break;let A=!1;for(let E=h.length-1;E>=N;--E){const M=LS(e,I,h[E]);if(M>=o){A=!0;break}if(L.score=L.score*vS(o,l,M),L.score<=r)break}L.suppressBeginIndex=h.length,A||(L.score===S?(h.push(I),d.push(L.score)):L.score>r&&Cm(p,L,Em))}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=C(b,"int32")),w}function LS(e,t,n){const o=e.subarray(t*4,t*4+4),r=e.subarray(n*4,n*4+4),i=Math.min(o[0],o[2]),a=Math.min(o[1],o[3]),s=Math.max(o[0],o[2]),c=Math.max(o[1],o[3]),p=Math.min(r[0],r[2]),l=Math.min(r[1],r[3]),h=Math.max(r[0],r[2]),d=Math.max(r[1],r[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 vS(e,t,n){const o=Math.exp(t*n*n);return n<=e?o:0}function Em(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function SS(e,t,n,o=.5,r=Number.NEGATIVE_INFINITY){const i=u(e,"boxes","nonMaxSuppressionAsync"),a=u(t,"scores","nonMaxSuppressionAsync"),s=St(i,a,n,o,r);n=s.maxOutputSize,o=s.iouThreshold,r=s.scoreThreshold;const c=await Promise.all([i.data(),a.data()]),p=c[0],l=c[1],h=za(p,l,n,o,r);return i!==e&&i.dispose(),a!==t&&a.dispose(),h}const Om=SS;function IS(e,t,n,o=.5,r=Number.NEGATIVE_INFINITY,i=0){const a=u(e,"boxes","nonMaxSuppression"),s=u(t,"scores","nonMaxSuppression"),c=St(a,s,n,o,r,i);n=c.maxOutputSize,o=c.iouThreshold,r=c.scoreThreshold,i=c.softNmsSigma;const p={boxes:a,scores:s},l={maxOutputSize:n,iouThreshold:o,scoreThreshold:r,softNmsSigma:i},h=g.runKernel(gp,p,l);return{selectedIndices:h[0],selectedScores:h[1]}}const km=m({nonMaxSuppressionWithScore_:IS});async function TS(e,t,n,o=.5,r=Number.NEGATIVE_INFINITY,i=0){const a=u(e,"boxes","nonMaxSuppressionAsync"),s=u(t,"scores","nonMaxSuppressionAsync"),c=St(a,s,n,o,r,i);n=c.maxOutputSize,o=c.iouThreshold,r=c.scoreThreshold,i=c.softNmsSigma;const p=await Promise.all([a.data(),s.data()]),l=p[0],h=p[1],d=Va(l,h,n,o,r,i);return a!==e&&a.dispose(),s!==t&&s.dispose(),d}const Dm=TS;function AS(e,t,n,o=.5,r=Number.NEGATIVE_INFINITY,i=!1){const a=u(e,"boxes","nonMaxSuppression"),s=u(t,"scores","nonMaxSuppression"),c=St(a,s,n,o,r,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(fp,d,b);return{selectedIndices:x[0],validOutputs:x[1]}}const Fm=m({nonMaxSuppressionPadded_:AS});async function NS(e,t,n,o=.5,r=Number.NEGATIVE_INFINITY,i=!1){const a=u(e,"boxes","nonMaxSuppressionAsync"),s=u(t,"scores","nonMaxSuppressionAsync"),c=St(a,s,n,o,r,null),p=c.maxOutputSize,l=c.iouThreshold,h=c.scoreThreshold,[d,b]=await Promise.all([a.data(),s.data()]),x=Ya(d,b,p,l,h,i);return a!==e&&a.dispose(),s!==t&&s.dispose(),x}const Mm=NS;function RS(e,t,n=!1){const o=u(e,"images","resizeBilinear");f(o.rank===3||o.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${o.rank}.`),f(t.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`);let r=o,i=!1;o.rank===3&&(i=!0,r=y(o,[1,o.shape[0],o.shape[1],o.shape[2]]));const[a,s]=t,c=(d,b)=>(b([r]),d.resizeBilinear(r,a,s,n)),p={images:r},l={alignCorners:n,size:t},h=g.runKernelFunc(c,p,null,_i,l);return i?y(h,[h.shape[1],h.shape[2],h.shape[3]]):h}const Um=m({resizeBilinear_:RS});function _S(e,t,n=!1){const o=u(e,"images","resizeNearestNeighbor");f(o.rank===3||o.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${o.rank}.`),f(t.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),f(o.dtype==="float32"||o.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype");let r=o,i=!1;o.rank===3&&(i=!0,r=y(o,[1,o.shape[0],o.shape[1],o.shape[2]]));const[a,s]=t,c={images:r},p={alignCorners:n,size:t},l=(d,b)=>(b([r]),d.resizeNearestNeighbor(r,a,s,n)),h=g.runKernelFunc(l,c,null,Ri,p);return i?y(h,[h.shape[1],h.shape[2],h.shape[3]]):h}const Wm=m({resizeNearestNeighbor_:_S});function CS(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 o=u(e,"a","bandPart");f(o.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${o.rank}.`);const r=o.shape,[i,a]=o.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(Po(0,i,1,"int32"),[-1,1]),c=Po(0,a,1,"int32"),p=O(s,c),l=Lt(ut(p,C(+t,"int32")),ht(p,C(-n,"int32"))),h=Ce([i,a],o.dtype);return y(ke(Ie(y(o,[-1,i,a])).map(d=>Oe(l,d,h))),r)}const Bm=m({bandPart_:CS});function ES(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 r=e[0].shape[0];for(let i=1;i<e.length;++i)f(e[i].shape[0]===r,()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[i].shape[0]} vs. ${r})`)}else t=!0,e=Yt(e,e.shape[0],0).map(r=>Qn(r,[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=[],o=e;for(let r=0;r<e.length;++r)n.push(g.tidy(()=>{let i=o[r];if(r>0)for(let a=0;a<r;++a){const s=v(U(v(n[a],i)),n[a]);i=O(i,s)}return F(i,qo(i,"euclidean"))}));return t?ke(n,0):n}const $m=m({gramSchmidt_:ES});function OS(e,t=!1){if(f(e.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`),e.rank===2)return jm(e,t);{const n=e.shape.slice(0,e.shape.length-2).reduce((c,p)=>c*p),o=Ie(y(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),r=[],i=[];o.forEach(c=>{const[p,l]=jm(c,t);r.push(p),i.push(l)});const a=y(ke(r,0),e.shape),s=y(ke(i,0),e.shape);return[a,s]}}function jm(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],o=e.shape[1];let r=xs(n),i=Et(e);const a=mt([[1]],[1,1]);let s=Et(a);const c=n>=o?o:n;for(let p=0;p<c;++p){const l=i,h=s,d=r;[s,i,r]=g.tidy(()=>{const b=G(i,[p,p],[n-p,1]),x=qo(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,o]),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,o]),B],0)}const D=K(E),$=G(r,[0,p],[n,r.shape[1]-p]);if(p===0)r=O($,Y(Y($,s),D));else{const B=O($,Y(Y($,s),D));r=Z([G(r,[0,0],[n,p]),B],1)}return[s,i,r]}),ve([l,h,d])}return!t&&n>o&&(r=G(r,[0,0],[n,o]),i=G(i,[0,0],[o,o])),[r,i]})}const Gm=m({qr_:OS});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 kS(e,t,n=be.SUM_BY_NONZERO_WEIGHTS){const o=u(e,"losses","computeWeightedLoss");let r=null;t!=null&&(r=u(t,"weights","computeWeightedLoss"));const i=r==null?o:v(o,r);if(n===be.NONE)return i;if(n===be.SUM)return U(i);if(n===be.MEAN){if(r==null)return Sn(i);{const a=o.size/r.size,s=F(U(i),U(r));return a>1?F(s,C(a)):s}}if(n===be.SUM_BY_NONZERO_WEIGHTS){if(r==null)return F(U(i),C(o.size));{const a=v(r,vt(o.shape)),s=_(U(Vn(a,C(0))),"float32");return F(U(i),s)}}throw Error(`Unknown reduction: ${n}`)}const $e=m({computeWeightedLoss_:kS});function DS(e,t,n,o=be.SUM_BY_NONZERO_WEIGHTS){const r=u(e,"labels","absoluteDifference"),i=u(t,"predictions","absoluteDifference");let a=null;n!=null&&(a=u(n,"weights","absoluteDifference")),P(r.shape,i.shape,"Error in absoluteDifference: ");const s=Ee(O(r,i));return $e(s,a,o)}const Pm=m({absoluteDifference_:DS});function FS(e,t,n,o,r=be.SUM_BY_NONZERO_WEIGHTS){const i=u(e,"labels","cosineDistance"),a=u(t,"predictions","cosineDistance");let s=null;o!=null&&(s=u(o,"weights","cosineDistance")),P(i.shape,a.shape,"Error in cosineDistance: ");const c=C(1),p=O(c,U(v(i,a),n,!0));return $e(p,s,r)}const qm=m({cosineDistance_:FS});function MS(e,t,n,o=be.SUM_BY_NONZERO_WEIGHTS){let r=u(e,"labels","hingeLoss");const i=u(t,"predictions","hingeLoss");let a=null;n!=null&&(a=u(n,"weights","hingeLoss")),P(r.shape,i.shape,"Error in hingeLoss: ");const s=C(1);r=O(v(C(2),r),s);const c=ie(O(s,v(r,i)));return $e(c,a,o)}const Hm=m({hingeLoss_:MS});function US(e,t,n,o=1,r=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=C(o),p=Ee(O(a,i)),l=Yn(p,c),h=O(p,l),d=R(v(C(.5),H(l)),v(c,h));return $e(d,s,r)}const zm=m({huberLoss_:US});function WS(e,t,n,o=1e-7,r=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=C(1),p=C(o),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,r)}const Ym=m({logLoss_:WS});function BS(e,t,n,o=be.SUM_BY_NONZERO_WEIGHTS){const r=u(e,"labels","meanSquaredError"),i=u(t,"predictions","meanSquaredError");let a=null;n!=null&&(a=u(n,"weights","meanSquaredError")),P(r.shape,i.shape,"Error in meanSquaredError: ");const s=Zn(r,i);return $e(s,a,o)}const Vm=m({meanSquaredError_:BS});function $S(e,t){const n=u(e,"labels","sigmoidCrossEntropyWithLogits"),o=u(t,"logits","sigmoidCrossEntropyWithLogits");P(n.shape,o.shape,"Error in sigmoidCrossEntropyWithLogits: ");const r=ie(o),i=v(o,n),a=Ls(Se(ne(Ee(o))));return R(O(r,i),a)}function jS(e,t,n,o=0,r=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: "),o>0){const p=C(o),l=C(1),h=C(.5);i=R(v(i,O(l,p)),v(h,p))}const c=$S(i,a);return $e(c,s,r)}const Km=m({sigmoidCrossEntropy_:jS});function GS(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 o=Ke((r,i,a)=>{const s=!0,c=Ss(i,[n],s),p=O(_(i,"float32"),c);a([r,p]);const l=ne(v(p,r)),h=U(l,[n]),d=(b,x)=>{const[w,L]=x,S=we(b.shape,[n]);return[v(y(b,S),O(_(w,"float32"),Se(L))),v(y(b,S),O(Se(L),_(w,"float32")))]};return{value:h,gradFunc:d}});return o(e,t)}function PS(e,t,n,o=0,r=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: "),o>0){const p=C(o),l=C(1),h=C(i.shape[1]);i=R(v(i,O(l,p)),F(p,h))}const c=GS(i,a);return $e(c,s,r)}const Jm=m({softmaxCrossEntropy_:PS});const Bh={};Re(Bh,{abs:()=>Ee,acos:()=>zp,acosh:()=>Yp,add:()=>R,addN:()=>Vp,addStrict:()=>rm,all:()=>Xp,any:()=>Zp,argMax:()=>Qp,argMin:()=>el,asin:()=>tl,asinh:()=>nl,atan:()=>ol,atan2:()=>rl,atanh:()=>il,avgPool:()=>pt,avgPool3d:()=>pl,basicLSTMCell:()=>yl,batchNorm:()=>Ct,batchNorm2d:()=>Ll,batchNorm3d:()=>vl,batchNorm4d:()=>Sl,batchToSpaceND:()=>Bn,booleanMaskAsync:()=>Xd,broadcastTo:()=>$o,buffer:()=>Be,cast:()=>_,ceil:()=>Il,clipByValue:()=>$n,clone:()=>Et,complex:()=>Ye,concat:()=>Z,concat1d:()=>Tl,concat2d:()=>Al,concat3d:()=>Nl,concat4d:()=>Rl,conv1d:()=>_l,conv2d:()=>xe,conv2dTranspose:()=>Cl,conv3d:()=>El,conv3dTranspose:()=>Ol,cos:()=>jn,cosh:()=>fs,cosineWindow:()=>Ho,cumsum:()=>gs,depthToSpace:()=>kl,depthwiseConv2d:()=>en,diag:()=>Dl,dilation2d:()=>Fl,div:()=>F,divNoNan:()=>Ml,divStrict:()=>im,dot:()=>Ul,dropout:()=>vm,elu:()=>ws,enclosingPowerOfTwo:()=>ja,equal:()=>tn,equalStrict:()=>Zd,erf:()=>Wl,exp:()=>Se,expandDims:()=>et,expm1:()=>Bl,eye:()=>xs,fft:()=>Gn,fill:()=>Pe,floor:()=>Pn,floorDiv:()=>bs,fused:()=>Uh,gather:()=>qn,gatherND:()=>ym,greater:()=>tt,greaterEqual:()=>ht,greaterEqualStrict:()=>Qd,greaterStrict:()=>em,ifft:()=>vn,imag:()=>nn,image:()=>Ka,inTopKAsync:()=>Sm,irfft:()=>ys,isFinite:()=>jl,isInf:()=>Gl,isNaN:()=>Pl,leakyRelu:()=>ql,less:()=>Hn,lessEqual:()=>ut,lessEqualStrict:()=>tm,lessStrict:()=>nm,linalg:()=>Qm,linspace:()=>Hl,localResponseNormalization:()=>zl,log:()=>yt,log1p:()=>Ls,logSigmoid:()=>Vl,logSoftmax:()=>Kl,logSumExp:()=>Ss,logicalAnd:()=>Lt,logicalNot:()=>zn,logicalOr:()=>Is,logicalXor:()=>Jl,losses:()=>ef,matMul:()=>Y,max:()=>dt,maxPool:()=>Ae,maxPool3d:()=>Xl,maxPoolWithArgmax:()=>Zl,maximum:()=>kt,maximumStrict:()=>sm,mean:()=>Sn,min:()=>In,minimum:()=>Yn,minimumStrict:()=>am,mod:()=>Ts,modStrict:()=>cm,moments:()=>Ql,movingAverage:()=>mm,mul:()=>v,mulStrict:()=>pm,multiRNNCell:()=>eh,multinomial:()=>th,neg:()=>ne,norm:()=>qo,notEqual:()=>Vn,notEqualStrict:()=>om,oneHot:()=>Go,ones:()=>vt,onesLike:()=>Ua,op:()=>m,outerProduct:()=>nh,pad:()=>qe,pad1d:()=>oh,pad2d:()=>rh,pad3d:()=>ih,pad4d:()=>sh,pool:()=>ah,pow:()=>Je,powStrict:()=>lm,prelu:()=>As,print:()=>ch,prod:()=>ph,rand:()=>lh,randomGamma:()=>mh,randomNormal:()=>fh,randomUniform:()=>Rs,range:()=>Po,real:()=>zt,reciprocal:()=>gh,relu:()=>ie,relu6:()=>_s,reshape:()=>y,reverse:()=>Ve,reverse1d:()=>bh,reverse2d:()=>wh,reverse3d:()=>xh,reverse4d:()=>yh,rfft:()=>Jn,round:()=>vh,rsqrt:()=>Cs,scalar:()=>C,scatterND:()=>bm,selu:()=>Sh,separableConv2d:()=>Xn,setdiff1dAsync:()=>Ih,sigmoid:()=>lt,sign:()=>Th,signal:()=>Zm,sin:()=>Es,sinh:()=>Os,slice:()=>G,slice1d:()=>Ah,slice2d:()=>Nh,slice3d:()=>ks,slice4d:()=>Rh,softmax:()=>on,softplus:()=>vs,spaceToBatchND:()=>Kn,sparseToDense:()=>xm,spectral:()=>Xm,split:()=>Yt,sqrt:()=>me,square:()=>H,squaredDifference:()=>Zn,squaredDifferenceStrict:()=>hm,squeeze:()=>Qn,stack:()=>ke,step:()=>Dt,stridedSlice:()=>_h,sub:()=>O,subStrict:()=>um,sum:()=>U,tan:()=>Ch,tanh:()=>Bo,tensor:()=>Ge,tensor1d:()=>ce,tensor2d:()=>mt,tensor3d:()=>eo,tensor4d:()=>ft,tensor5d:()=>Eh,tensor6d:()=>Oh,tile:()=>Ot,topk:()=>kh,transpose:()=>K,truncatedNormal:()=>Dh,unsortedSegmentSum:()=>Ds,unstack:()=>Ie,variable:()=>Fh,where:()=>Oe,whereAsync:()=>Fs,zeros:()=>Ce,zerosLike:()=>W});const Xm={fft:Gn,ifft:vn,rfft:Jn,irfft:ys},Zm={hammingWindow:Im,hannWindow:qa,frame:Ha,stft:Tm},Ka={flipLeftRight:Nm,resizeNearestNeighbor:Wm,resizeBilinear:Um,rotateWithOffset:Rm,cropAndResize:Am,nonMaxSuppression:_m,nonMaxSuppressionAsync:Om,nonMaxSuppressionWithScore:km,nonMaxSuppressionWithScoreAsync:Dm,nonMaxSuppressionPadded:Fm,nonMaxSuppressionPaddedAsync:Mm},Qm={bandPart:Bm,gramSchmidt:$m,qr:Gm},ef={absoluteDifference:Pm,computeWeightedLoss:$e,cosineDistance:qm,hingeLoss:Hm,huberLoss:zm,logLoss:Ym,meanSquaredError:Vm,sigmoidCrossEntropy:Km,softmaxCrossEntropy:Jm};kd(Bh);const Ms={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};const Ja=4;async function HS(e,t){const n=[],o=[],r=Array.isArray(e)?e.map(a=>a.name):Object.keys(e);for(let a=0;a<r.length;++a){const s=r[a],c=Array.isArray(e)?e[a].tensor:e[s];if(c.dtype!=="float32"&&c.dtype!=="int32"&&c.dtype!=="bool"&&c.dtype!=="string"&&c.dtype!=="complex64")throw new Error(`Unsupported dtype in weight '${s}': ${c.dtype}`);const p={name:s,shape:c.shape,dtype:c.dtype};if(c.dtype==="string"){const l=new Promise(async h=>{const d=await c.bytes(),b=d.reduce((L,S)=>L+S.length,0)+Ja*d.length,x=new Uint8Array(b);let w=0;for(let L=0;L<d.length;L++){const S=d[L],I=new Uint8Array(new Uint32Array([S.length]).buffer);x.set(I,w),w+=Ja,x.set(S,w),w+=S.length}h(x)});o.push(l)}else o.push(c.data());t!=null&&(p.group=t),n.push(p)}const i=await Promise.all(o);return{data:qS(i),specs:n}}function $h(e,t){const n={};let o,r=0;for(const i of t){const a=i.name,s=i.dtype,c=i.shape,p=Q(c);let l;if("quantization"in i){const h=i.quantization;if(h.dtype==="uint8"||h.dtype==="uint16"){if(!("min"in h&&"scale"in h))throw new Error(`Weight ${i.name} with quantization ${h.dtype} doesn't have corresponding metadata min and scale.`)}else if(h.dtype==="float16"){if(s!=="float32")throw new Error(`Weight ${i.name} is quantized with ${h.dtype} which only supports weights of type float32 not ${s}.`)}else throw new Error(`Weight ${i.name} has unknown quantization dtype ${h.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);const d=Ms[h.dtype],b=e.slice(r,r+p*d),x=h.dtype==="uint8"?new Uint8Array(b):new Uint16Array(b);if(s==="float32")if(h.dtype==="uint8"||h.dtype==="uint16"){l=new Float32Array(x.length);for(let w=0;w<x.length;w++){const L=x[w];l[w]=L*h.scale+h.min}}else if(h.dtype==="float16")o===void 0&&(o=zS()),l=o(x);else throw new Error(`Unsupported quantization type ${h.dtype} for weight type float32.`);else if(s==="int32"){if(h.dtype!=="uint8"&&h.dtype!=="uint16")throw new Error(`Unsupported quantization type ${h.dtype} for weight type int32.`);l=new Int32Array(x.length);for(let w=0;w<x.length;w++){const L=x[w];l[w]=Math.round(L*h.scale+h.min)}}else throw new Error(`Unsupported dtype in weight '${a}': ${s}`);r+=p*d}else if(s==="string"){const h=Q(i.shape);l=[];for(let d=0;d<h;d++){const b=new Uint32Array(e.slice(r,r+Ja))[0];r+=Ja;const x=new Uint8Array(e.slice(r,r+b));l.push(x),r+=b}}else{const h=Ms[s],d=e.slice(r,r+p*h);if(s==="float32")l=new Float32Array(d);else if(s==="int32")l=new Int32Array(d);else if(s==="bool")l=new Uint8Array(d);else if(s==="complex64"){l=new Float32Array(d);const b=new Float32Array(l.length/2),x=new Float32Array(l.length/2);for(let S=0;S<b.length;S++)b[S]=l[S*2],x[S]=l[S*2+1];const w=Ge(b,c,"float32"),L=Ge(x,c,"float32");n[a]=Ye(w,L)}else throw new Error(`Unsupported dtype in weight '${a}': ${s}`);r+=p*h}s!=="complex64"&&(n[a]=Ge(l,c,s))}return n}function qS(e){if(e===null)throw new Error(`Invalid input value: ${JSON.stringify(e)}`);let t=0;const n=[];e.forEach(i=>{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 o=new Uint8Array(t);let r=0;return n.forEach(i=>{o.set(new Uint8Array(i.buffer),r),r+=i.byteLength}),o.buffer}const YS=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function tf(e){return YS?Buffer.byteLength(e):new Blob([e]).size}function Us(e){if(e.length===1)return e[0];let t=0;e.forEach(r=>{t+=r.byteLength});const n=new Uint8Array(t);let o=0;return e.forEach(r=>{n.set(new Uint8Array(r),o),o+=r.byteLength}),n.buffer}function jh(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 Ws(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:tf(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:tf(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:e.weightData.byteLength}}function VS(){const e=n=>{let o=n<<13,r=0;for(;(o&8388608)===0;)r-=8388608,o<<=1;return o&=~8388608,r+=947912704,o|r},t=new Uint32Array(2048);t[0]=0;for(let n=1;n<1024;n++)t[n]=e(n);for(let n=1024;n<2048;n++)t[n]=939524096+(n-1024<<13);return t}function KS(){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 JS(){const e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function zS(){const e=VS(),t=KS(),n=JS();return o=>{const r=new ArrayBuffer(4*o.length),i=new Uint32Array(r);for(let a=0;a<o.length;a++){const s=o[a],c=e[n[s>>10]+(s&1023)]+t[s>>10];i[a]=c}return new Float32Array(r)}}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 o=[],r=t==="load"?Ne.getInstance().loadRouters:Ne.getInstance().saveRouters;return r.forEach(i=>{const a=i(e,n);a!==null&&o.push(a)}),o}}const XS=e=>Ne.registerSaveRouter(e),ZS=e=>Ne.registerLoadRouter(e),QS=e=>Ne.getSaveHandlers(e),eI=(e,t)=>Ne.getLoadHandlers(e,t);const Yo="://";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(Yo)&&(e=e.slice(0,e.indexOf(Yo))),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 Xa(e){if(e.indexOf(Yo)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Ft.getSchemes().join(",")}`);return{scheme:e.split(Yo)[0],path:e.split(Yo)[1]}}async function nf(e,t,n=!1){f(e!==t,()=>`Old path and new path are the same: '${e}'`);const o=Ne.getLoadHandlers(e);f(o.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),f(o.length<2,()=>`Copying failed because more than one (${o.length}) load handlers for source URL ${e}.`);const r=o[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 (${o.length}) save handlers for destination URL ${t}.`);const a=i[0],s=Xa(e).scheme,c=Xa(e).path,p=s===Xa(e).scheme,l=await r.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 of(){const e=Ft.getSchemes(),t={};for(const n of e){const o=await Ft.getManager(n).listModels();for(const r in o){const i=n+Yo+r;t[i]=o[r]}}return t}async function rf(e){const t=Xa(e),n=Ft.getManager(t.scheme);return n.removeModel(t.path)}async function sf(e,t){const n=!1;return nf(e,t,n)}async function af(e,t){const n=!0;return nf(e,t,n)}const tI="model",nI=".json",oI=".weights.bin";function cf(e){return new Promise(t=>setTimeout(t)).then(e)}class Vo{constructor(e){if(!pe().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(Vo.URL_SCHEME)&&(e=e.slice(Vo.URL_SCHEME.length)),(e==null||e.length===0)&&(e=tI),this.modelTopologyFileName=e+nI,this.weightDataFileName=e+oI}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}],o={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:n},r=window.URL.createObjectURL(new Blob([JSON.stringify(o)],{type:"application/json"})),i=this.jsonAnchor==null?document.createElement("a"):this.jsonAnchor;if(i.download=this.modelTopologyFileName,i.href=r,await cf(()=>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 cf(()=>a.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:Ws(e)}}}}Vo.URL_SCHEME="downloads://";class rI{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,o)=>{const r=new FileReader;r.onload=i=>{const a=JSON.parse(i.target.result),s=a.modelTopology;if(s==null){o(new Error(`modelTopology field is missing from file ${e.name}`));return}t.length===0&&n({modelTopology:s});const c=a.weightsManifest;if(c==null){o(new Error(`weightManifest field is missing from file ${e.name}`));return}let p;try{p=this.checkManifestAndWeightFiles(c,t)}catch(b){o(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:Us(d),format:a.format,generatedBy:a.generatedBy,convertedBy:a.convertedBy,userDefinedMetadata:a.userDefinedMetadata})},w.onerror=L=>o(`Failed to weights data from file of path '${x}'.`),w.readAsArrayBuffer(p[x])})})},r.onerror=i=>o(`Failed to read model topology and weights manifest JSON from file '${e.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),r.readAsText(e)})}checkManifestAndWeightFiles(e,t){const n=[],o=t.map(i=>jh(i.name)),r={};for(const i of e)i.paths.forEach(a=>{const s=jh(a);if(n.indexOf(s)!==-1)throw new Error(`Duplicate file basename found in weights manifest: '${s}'`);if(n.push(s),o.indexOf(s)===-1)throw new Error(`Weight file with basename '${s}' is not provided.`);r[a]=t[o.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 r}}const sI=e=>pe().getBool("IS_BROWSER")&&(!Array.isArray(e)&&e.startsWith(Vo.URL_SCHEME))?iI(e.slice(Vo.URL_SCHEME.length)):null;Ne.registerSaveRouter(sI);function iI(e="model"){return new Vo(e)}function aI(e){return new rI(e)}function Gh(e,t,n,o){a(e),n=n==null?0:n,o=o==null?1:o,s(n,o);let r=0;const i=c=>(c.then(p=>{const l=n+ ++r/e.length*(o-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 Ph(e,t){t==null&&(t={});const n=t.fetchFunc==null?pe().platform.fetch:t.fetchFunc,o=e.map(h=>n(h,t.requestInit,{isBinary:!0})),r=0,i=.5,a=t.onProgress==null?await Promise.all(o):await Gh(o,t.onProgress,r,i),s=a.map(h=>h.arrayBuffer()),c=.5,p=1,l=t.onProgress==null?await Promise.all(s):await Gh(s,t.onProgress,c,p);return l}async function cI(e,t="",n,o){const r=a=>Ph(a,{requestInit:o}),i=pf(r);return i(e,t,n)}function pf(e){return async(t,n="",o)=>{const r=t.map(()=>!1),i={},a=o!=null?o.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=Ms[S]*Q(L.shape),N=()=>{r[x]=!0,i[x]==null&&(i[x]=[]),i[x].push({manifestEntry:L,groupOffset:w,sizeBytes:I})};o!=null?o.forEach((A,E)=>{A===L.name&&(N(),a[E]=!0)}):N(),s.push(L.name),w+=I})}),!a.every(b=>b)){const b=o.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=r.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<x;A++)w+=l[d+A].byteLength;const L=new ArrayBuffer(w),S=new Uint8Array(L);let I=0;for(let A=0;A<x;A++){const E=new Uint8Array(l[d+A]);S.set(E,I),I+=E.byteLength}const N=i[b];N.forEach(A=>{const E=L.slice(A.groupOffset,A.groupOffset+A.sizeBytes),M=$h(E,[A.manifestEntry]);for(const D in M)h[D]=M[D]}),d+=x}),h}}const pI="application/octet-stream",lI="application/json";class qh{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}],o={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(o)],{type:lI}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:pI}),"model.weights.bin");const r=await this.fetch(this.path,t);if(r.ok)return{modelArtifactsInfo:Ws(e),responses:[r]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${r.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,o=t.weightsManifest,r=t.generatedBy,i=t.convertedBy,a=t.format,s=t.userDefinedMetadata;if(n==null&&o==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);let c,p;if(o!=null){const l=await this.loadWeights(o);[c,p]=l}return{modelTopology:n,weightSpecs:c,weightData:p,userDefinedMetadata:s,generatedBy:r,convertedBy:i,format:a}}async loadWeights(e){const t=Array.isArray(this.path)?this.path[1]:this.path,[n,o]=hI(t),r=this.weightPathPrefix||n,i=[];for(const c of e)i.push(...c.weights);const a=[];e.forEach(c=>{c.paths.forEach(p=>{a.push(r+p+o)})});const s=await Ph(a,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[i,Us(s)]}}qh.URL_SCHEME_REGEX=/^https?:\/\//;function hI(e){const t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),o=e.substring(0,t),r=n>t?e.substring(n):"";return[o+"/",r]}function Hh(e){return e.match(qh.URL_SCHEME_REGEX)!=null}const lf=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let n=!0;if(Array.isArray(e)?n=e.every(o=>Hh(o)):n=Hh(e),n)return zh(e,t)}return null};Ne.registerSaveRouter(lf);Ne.registerLoadRouter(lf);function zh(e,t){return new qh(e,t)}function uI(e,t){return zh(e,t)}class Yh{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}}class dI{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}}function mI(e,t,n,o){if(arguments.length===1){const r=e.modelTopology!=null||e.weightSpecs!=null;return r?new Yh(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 Yh({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 Yh({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:o})}function fI(e){return new dI(e)}const Ko={};Re(Ko,{browserFiles:()=>aI,browserHTTPRequest:()=>uI,concatenateArrayBuffers:()=>Us,copyModel:()=>sf,decodeWeights:()=>$h,encodeWeights:()=>HS,fromMemory:()=>mI,getLoadHandlers:()=>eI,getModelArtifactsInfoForJSON:()=>Ws,getSaveHandlers:()=>QS,http:()=>zh,isHTTPScheme:()=>Hh,listModels:()=>of,loadWeights:()=>cI,moveModel:()=>af,registerLoadRouter:()=>ZS,registerSaveRouter:()=>XS,removeModel:()=>rf,weightsLoaderFactory:()=>pf,withSaveHandler:()=>fI});function gI(e,t,n){const o=u(e,"labels","confusionMatrix"),r=u(t,"predictions","confusionMatrix");f(n==null||n>0&&Number.isInteger(n),()=>`If provided, numClasses must be a positive integer, but got ${n}`),f(o.rank===1,()=>`Expected the rank of labels to be 1, but got ${o.rank}`),f(r.rank===1,()=>`Expected the rank of predictions to be 1, but got ${r.rank}`),f(o.shape[0]===r.shape[0],()=>`Mismatch in the number of examples: ${o.shape[0]} vs. ${r.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=Go(_(o,"int32"),n),a=Go(_(r,"int32"),n),s=K(i);return _(Y(s,a),"int32")}const bI=m({confusionMatrix_:gI});const hf={};Re(hf,{confusionMatrix:()=>bI});const Jo={};Re(Jo,{fromPixels:()=>yI,toPixels:()=>xI});let Xo;function wI(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,o=!1,r=!1,i=!1,a=!1;if(e.data instanceof Uint8Array)n=!0;else if(typeof ImageData!="undefined"&&e instanceof ImageData)o=!0;else if(typeof HTMLVideoElement!="undefined"&&e instanceof HTMLVideoElement)r=!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(r){const b=2;if(r&&e.readyState<b)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.")}const s=rs(Sa,g.backendName);if(s!=null){const b={pixels:e},x={numChannels:t};return g.runKernel(Sa,b,x)}const[c,p]=r?[e.videoWidth,e.videoHeight]:[e.width,e.height];let l;a?l=e.getContext("2d").getImageData(0,0,c,p).data:o||n?l=e.data:(i||r)&&(Xo==null&&(Xo=document.createElement("canvas").getContext("2d")),Xo.canvas.width=c,Xo.canvas.height=p,Xo.drawImage(e,0,0,c,p),l=Xo.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;x<b;x++)for(let w=0;w<t;++w)h[x*t+w]=l[x*4+w]}const d=[p,c,t];return eo(h,d,"int32")}async function xI(e,t){let n=u(e,"img","toPixels");if(!(e instanceof ee)){const L=n;n=_(L,"int32"),L.dispose()}if(n.rank!==2&&n.rank!==3)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${n.rank}.`);const[o,r]=n.shape.slice(0,2),i=n.rank===2?1:n.shape[2];if(i>4||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(r*o*4);for(let L=0;L<o*r;++L){let S,I,N,A;i===1?(S=a[L]*x,I=a[L]*x,N=a[L]*x,A=255):i===3?(S=a[L*3]*x,I=a[L*3+1]*x,N=a[L*3+2]*x,A=255):i===4&&(S=a[L*4]*x,I=a[L*4+1]*x,N=a[L*4+2]*x,A=a[L*4+3]*x);const E=L*4;w[E+0]=Math.round(S),w[E+1]=Math.round(I),w[E+2]=Math.round(N),w[E+3]=Math.round(A)}if(t!=null){t.width=r,t.height=o;const L=t.getContext("2d"),S=new ImageData(w,r,o);L.putImageData(S,0,0)}return n!==e&&n.dispose(),w}const yI=m({fromPixels_:wI});const uf={};Re(uf,{prepareAndValidate:()=>df});function df(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,o=n[n.length-1];let r=1;for(let p=0;p<n.length-1;++p)r*=n[p];const i=e.shape,a=n.slice();a.pop();let s=1;for(let p=o;p<e.rank;++p)s*=i[p],a.push(i[p]);const c=[...Gt(e.shape).map(p=>p/s),1].slice(0,o);return[a,r,s,c]}const mf={};Re(mf,{Serializable:()=>Vh,SerializationMap:()=>io,registerClass:()=>nt});class Vh{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}}class io{constructor(){this.classNameMap={}}static getMap(){return io.instance==null&&(io.instance=new io),io.instance}static register(e){io.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."),io.register(e)}const Lc="2.3.0";class rt extends Vh{minimize(e,t=!1,n){const{value:o,grads:r}=this.computeGradients(e,n);if(n!=null){const i=n.map(a=>({name:a.name,tensor:r[a.name]}));this.applyGradients(i)}else this.applyGradients(r);return ve(r),t?o:(o.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return Yl(e,t)}dispose(){this.iterations_!=null&&ve(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:C(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(rt,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});class so extends rt{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,o)=>{const r=g.registeredVariables[n],i=!1;this.accumulatedGrads[o]==null&&(this.accumulatedGrads[o]={originalName:`${n}/accum_grad`,variable:k(()=>W(r).variable(i))}),this.accumulatedUpdates[o]==null&&(this.accumulatedUpdates[o]={originalName:`${n}/accum_var`,variable:k(()=>W(r).variable(i))});const a=Array.isArray(e)?e[o].tensor:e[n];if(a==null)return;const s=this.accumulatedGrads[o].variable,c=this.accumulatedUpdates[o].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),r);r.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(o=>({originalName:o.name,variable:o.tensor.variable(n)})),this.accumulatedUpdates=e.slice(t,t*2).map(o=>({originalName:o.name,variable:o.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)}}so.className="Adadelta";nt(so);class ao extends rt{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,o)=>{const r=g.registeredVariables[n];if(this.accumulatedGrads[o]==null){const s=!1;this.accumulatedGrads[o]={originalName:`${n}/accumulator`,variable:k(()=>Pe(r.shape,this.initialAccumulatorValue).variable(s))}}const i=Array.isArray(e)?e[o].tensor:e[n];if(i==null)return;const a=this.accumulatedGrads[o].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),r);r.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)}}ao.className="Adagrad";nt(ao);class co extends rt{constructor(e,t,n,o=null){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=o,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],k(()=>{this.accBeta1=C(t).variable(),this.accBeta2=C(n).variable()}),o==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),o=O(1,this.accBeta2);t.forEach((r,i)=>{const a=g.registeredVariables[r],s=!1;this.accumulatedFirstMoment[i]==null&&(this.accumulatedFirstMoment[i]={originalName:`${r}/m`,variable:k(()=>W(a).variable(s))}),this.accumulatedSecondMoment[i]==null&&(this.accumulatedSecondMoment[i]={originalName:`${r}/v`,variable:k(()=>W(a).variable(s))});const c=Array.isArray(e)?e[i].tensor:e[r];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,o);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(o=>({originalName:o.name,variable:o.tensor.variable(n)})),this.accumulatedSecondMoment=e.slice(t,t*2).map(o=>({originalName:o.name,variable:o.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)}}co.className="Adam";nt(co);class po extends rt{constructor(e,t,n,o=null,r=0){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=o,this.decay=r,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],k(()=>{this.iteration=C(0).variable(),this.accBeta1=C(t).variable()}),o==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),o=F(-this.learningRate,R(v(this.iteration,this.decay),1));t.forEach((r,i)=>{const a=g.registeredVariables[r],s=!1;this.accumulatedFirstMoment[i]==null&&(this.accumulatedFirstMoment[i]={originalName:`${r}/m`,variable:W(a).variable(s)}),this.accumulatedWeightedInfNorm[i]==null&&(this.accumulatedWeightedInfNorm[i]={originalName:`${r}/v`,variable:W(a).variable(s)});const c=Array.isArray(e)?e[i].tensor:e[r];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(o,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)}}po.className="Adamax";nt(po);class rn extends rt{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,o)=>{const r=Array.isArray(e)?e[o].tensor:e[n];if(r==null)return;const i=g.registeredVariables[n];k(()=>{const a=R(v(this.c,r),i);i.assign(a)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=cl(C(-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)}}rn.className="SGD";nt(rn);class lo extends rn{constructor(e,t,n=!1){super(e);this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=C(this.momentum)}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);t.forEach((n,o)=>{const r=g.registeredVariables[n];if(this.accumulations[o]==null){const s=!1;this.accumulations[o]={originalName:`${n}/momentum`,variable:k(()=>W(r).variable(s))}}const i=this.accumulations[o].variable,a=Array.isArray(e)?e[o].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))),r):s=R(v(this.c,c),r),i.assign(c),r.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)}}lo.className="Momentum";nt(lo);class ho extends rt{constructor(e,t=.9,n=0,o=null,r=!1){super();if(this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=o,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=r,o==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,o)=>{const r=g.registeredVariables[n],i=!1;this.accumulatedMeanSquares[o]==null&&(this.accumulatedMeanSquares[o]={originalName:`${n}/rms`,variable:k(()=>W(r).variable(i))}),this.accumulatedMoments[o]==null&&(this.accumulatedMoments[o]={originalName:`${n}/momentum`,variable:k(()=>W(r).variable(i))}),this.accumulatedMeanGrads[o]==null&&this.centered&&(this.accumulatedMeanGrads[o]={originalName:`${n}/mg`,variable:k(()=>W(r).variable(i))});const a=Array.isArray(e)?e[o].tensor:e[n];if(a==null)return;const s=this.accumulatedMeanSquares[o].variable,c=this.accumulatedMoments[o].variable;k(()=>{const p=R(v(s,this.decay),v(H(a),1-this.decay));if(this.centered){const l=this.accumulatedMeanGrads[o].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(r,b);r.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(r,h);r.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(o=>({originalName:o.name,variable:o.tensor.variable(n)})),this.accumulatedMoments=e.slice(t,t*2).map(o=>({originalName:o.name,variable:o.tensor.variable(n)})),this.centered&&(this.accumulatedMeanGrads=e.slice(t*2,t*3).map(o=>({originalName:o.name,variable:o.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)}}ho.className="RMSProp";nt(ho);class Tn{static sgd(e){return new rn(e)}static momentum(e,t,n=!1){return new lo(e,t,n)}static rmsprop(e,t=.9,n=0,o=null,r=!1){return new ho(e,t,n,o,r)}static adam(e=.001,t=.9,n=.999,o=null){return new co(e,t,n,o)}static adadelta(e=.001,t=.95,n=null){return new so(e,t,n)}static adamax(e=.002,t=.9,n=.999,o=null,r=0){return new po(e,t,n,o,r)}static adagrad(e,t=.1){return new ao(e,t)}}lo,rn,so,ao,ho,po,co;const LI={sgd:Tn.sgd,momentum:Tn.momentum,adadelta:Tn.adadelta,adagrad:Tn.adagrad,rmsprop:Tn.rmsprop,adamax:Tn.adamax,adam:Tn.adam};const vI=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:e=>e())();function SI(){return new Promise(e=>vI(()=>e()))}function II(e,t,n){const o=n*(typeof e=="number"?e:e[0]),r=t*(typeof e=="number"?e:e[1]);return[o,r]}function TI(e,t,n,o=!0){let r=[];if(o)r=r.concat(t.slice(0)),r.push(e[0]/n),r=r.concat(e.slice(1));else{r=r.concat(e[0]);const i=t.length;for(let a=0;a<i;++a)r=r.concat([e[a+1]/t[a],t[a]]);r=r.concat(e.slice(i+1))}return r}function AI(e,t,n=!0){const o=[];if(n){o.push(t);for(let r=t+1;r<e;++r)r<=2*t?(o.push(r),o.push(r-(t+1))):o.push(r)}else{const r=[],i=[];for(let a=1;a<e;++a)a>=t*2+1||a%2===1?i.push(a):r.push(a);o.push(...r),o.push(0),o.push(...i)}return o}function NI(e,t,n,o=!0){const r=[];o?r.push(e[0]/n):r.push(e[0]*n);for(let i=1;i<e.length;++i)i<=t.length?o?r.push(t[i-1]*e[i]):r.push(e[i]/t[i-1]):r.push(e[i]);return r}function RI(e,t){const n=[0];for(let o=0;o<t;++o)n.push(e[o][0]);return n}function _I(e,t,n){const o=e.slice(0,1);for(let r=0;r<n;++r)o.push(e[r+1]-t[r][0]-t[r][1]);return o}const Kh=1.7580993408473768,Jh=1.0507009873554805;const CI=.3275911,EI=.254829592,OI=-.284496736,kI=1.421413741,DI=-1.453152027,FI=1.061405429;function MI(...e){pe().getBool("IS_TEST")||console.warn(...e)}function UI(...e){pe().getBool("IS_TEST")||console.log(...e)}function WI(e,t){if(e.length!==t.length)throw new Error(`Cannot merge real and imag arrays of different lengths. real:${e.length}, imag: ${t.length}.`);const n=new Float32Array(e.length*2);for(let o=0;o<n.length;o+=2)n[o]=e[o/2],n[o+1]=t[o/2];return n}function BI(e){const t=new Float32Array(e.length/2),n=new Float32Array(e.length/2);for(let o=0;o<e.length;o+=2)t[o/2]=e[o],n[o/2]=e[o+1];return{real:t,imag:n}}function $I(e){const t=Math.ceil(e.length/4),n=new Float32Array(t),o=new Float32Array(t);for(let r=0;r<e.length;r+=4)n[Math.floor(r/4)]=e[r],o[Math.floor(r/4)]=e[r+1];return{real:n,imag:o}}function jI(e){const t=Math.floor(e.length/4),n=new Float32Array(t),o=new Float32Array(t);for(let r=2;r<e.length;r+=4)n[Math.floor(r/4)]=e[r],o[Math.floor(r/4)]=e[r+1];return{real:n,imag:o}}function GI(e,t){const n=e[t*2],o=e[t*2+1];return{real:n,imag:o}}function PI(e,t,n,o){e[o*2]=t,e[o*2+1]=n}function qI(e,t){const n=new Float32Array(e/2),o=new Float32Array(e/2);for(let r=0;r<Math.ceil(e/2);r++){const i=(t?2:-2)*Math.PI*(r/e);n[r]=Math.cos(i),o[r]=Math.sin(i)}return{real:n,imag:o}}function HI(e,t,n){const o=(n?2:-2)*Math.PI*(e/t),r=Math.cos(o),i=Math.sin(o);return{real:r,imag:i}}const ff={};Re(ff,{ERF_A1:()=>EI,ERF_A2:()=>OI,ERF_A3:()=>kI,ERF_A4:()=>DI,ERF_A5:()=>FI,ERF_P:()=>CI,PARALLELIZE_THRESHOLD:()=>Fa,SELU_SCALE:()=>Jh,SELU_SCALEALPHA:()=>Kh,applyActivation:()=>oo,assertAndGetBroadcastShape:()=>q,assertAxesAreInnerMostDims:()=>Vw,assertParamsConsistent:()=>ll,assignToTypedArray:()=>PI,axesAreInnerMostDims:()=>Kp,calculateShapes:()=>gm,castTensor:()=>zI,combineLocations:()=>jd,complexWithEvenIndex:()=>$I,complexWithOddIndex:()=>jI,computeConv2DInfo:()=>je,computeConv3DInfo:()=>Ln,computeDefaultPad:()=>al,computeDilation2DInfo:()=>ax,computeOptimalWindowSize:()=>Ey,computeOutAndReduceShapes:()=>Jp,computeOutShape:()=>hl,computePool2DInfo:()=>_t,computePool3DInfo:()=>Qt,convertConv2DDataFormat:()=>yn,eitherStridesOrDilationsAreOne:()=>le,expandShapeToKeepDim:()=>we,exponent:()=>HI,exponents:()=>qI,getAxesPermutation:()=>ge,getBroadcastDims:()=>gy,getComplexWithIndex:()=>GI,getFusedBiasGradient:()=>no,getFusedDyActivation:()=>to,getImageCenter:()=>II,getInnerMostAxes:()=>De,getPermuted:()=>AI,getReductionAxes:()=>ae,getReshaped:()=>TI,getReshapedPermuted:()=>NI,getSliceBeginCoords:()=>RI,getSliceSize:()=>_I,getUndoAxesPermutation:()=>Un,linspaceImpl:()=>VI,log:()=>UI,mergeRealAndImagArrays:()=>WI,prepareAndValidate:()=>df,prepareSplitSize:()=>Lh,reshapeTensor:()=>YI,segment_util:()=>zd,shouldFuse:()=>ro,splitRealAndImagArrays:()=>BI,tupleValuesAreOne:()=>ct,upcastType:()=>Uo,validateInput:()=>$a,validateUpdateShape:()=>Mh,warn:()=>MI});function zI(e,t,n){if(t==="complex64"){if(e.dtype==="complex64")return e.clone();const o=Ce(e.shape),r=_(e,"float32"),i=n.complex(r,o);return o.dispose(),r.dispose(),i}if(!Dp(e.dtype,t))return g.makeTensorFromDataId(e.dataId,e.shape,t);if(e.dtype==="complex64"){const o=n.real(e),r=_(o,t);return o.dispose(),r}if(t==="int32")return n.int(e);if(t==="bool"){const o=C(0,e.dtype),r=n.notEqual(e,o);return o.dispose(),r}else throw new Error(`Error in Cast: failed to cast ${e.dtype} to ${t}`)}function YI(e,t){return g.makeTensorFromDataId(e.dataId,t,e.dtype)}function VI(e,t,n){const o=(t-e)/(n-1),r=Pt(n,"float32");r[0]=e;for(let i=1;i<r.length;i++)r[i]=r[i-1]+o;return ce(r,"float32")}function gf(e,t,n){const o=new Array(e.rank).fill(0),r=e.shape.slice();return t.map(i=>{const a=[...r];a[n]=i;const s=G(e,o,a);return o[n]+=i,s})}function bf(e,t){const n=new Array(e.rank);for(let r=0;r<n.length;r++)n[r]=e.shape[r]*t[r];const o=Be(n,e.dtype);for(let r=0;r<o.values.length;++r){const i=o.indexToLoc(r),a=new Array(e.rank);for(let c=0;c<a.length;c++)a[c]=i[c]%e.shape[c];const s=e.locToIndex(a);o.values[r]=e.values[s]}return o.toTensor()}function wf(e,t,n,o,r){const i=t[t.length-1],[a,s]=[e.length/i,i],c=Oo(n,a*o),p=Oo("int32",a*o);for(let h=0;h<a;h++){const d=h*s,b=e.subarray(d,d+s),x=[];for(let I=0;I<b.length;I++)x.push({value:b[I],index:I});x.sort((I,N)=>N.value-I.value);const w=h*o,L=c.subarray(w,w+o),S=p.subarray(w,w+o);for(let I=0;I<o;I++)L[I]=x[I].value,S[I]=x[I].index}const l=t.slice();return l[l.length-1]=o,[Ge(c,l,n),Ge(p,l,"int32")]}const xf={};Re(xf,{nonMaxSuppressionV3Impl:()=>za,nonMaxSuppressionV4Impl:()=>Ya,nonMaxSuppressionV5Impl:()=>Va,split:()=>gf,tile:()=>bf,topkImpl:()=>wf,whereImpl:()=>Ba});const KI=1e-7,JI=1e-4;class XI{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 ZI{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,o){return T("move")}memory(){return T("memory")}floatPrecision(){return T("floatPrecision")}epsilon(){return this.floatPrecision()===32?KI:JI}batchMatMul(e,t,n,o){return T("batchMatMul")}fusedBatchMatMul({a:e,b:t,transposeA:n,transposeB:o,bias:r,activation:i,preluActivationWeights:a}){return T("fusedBatchMatMul")}slice(e,t,n){return T("slice")}stridedSlice(e,t,n,o){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:o,activation:r,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:o,activation:r,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,o){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,o){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,o){return T("resizeBilinear")}resizeBilinearBackprop(e,t,n){return T("resizeBilinearBackprop")}resizeNearestNeighbor(e,t,n,o){return T("resizeNearestNeighbor")}resizeNearestNeighborBackprop(e,t,n){return T("resizeNearestNeighborBackprop")}batchNorm(e,t,n,o,r,i){return T("batchNorm")}localResponseNormalization4D(e,t,n,o,r){return T("localResponseNormalization4D")}LRNGrad(e,t,n,o,r,i,a){return T("LRNGrad")}multinomial(e,t,n,o){return T("multinomial")}oneHot(e,t,n,o){return T("oneHot")}cumsum(e,t,n,o){return T("cumsum")}nonMaxSuppression(e,t,n,o,r){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,o,r,i){return T("cropAndResize")}depthToSpace(e,t,n){return T("depthToSpace")}split(e,t,n){return T("split")}sparseToDense(e,t,n,o){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 yf={kernelName:yr,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(e,Dt(_(n,"float32"),-1))}}};const Lf={kernelName:Lr,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const o=H(_(n,"float32")),r=me(O(C(1),o));return ne(F(e,r))}}}};const vf={kernelName:vr,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const o=me(O(H(_(n,"float32")),1));return F(e,o)}}}};const Sf={kernelName:kn,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,o]=t,r=q(n.shape,o.shape),i=()=>{let s=e;const c=ae(n.shape,r);return c.length>0&&(s=U(s,c)),y(s,n.shape)},a=()=>{let s=e;const c=ae(o.shape,r);return c.length>0&&(s=U(s,c)),y(s,o.shape)};return{a:i,b:a}}};const If={kernelName:Sr,saveAllInputs:!0,gradFunc:(e,t)=>{const n={};return t.forEach((o,r)=>{n[r]=()=>e.clone()}),n}};const Tf={kernelName:Ir,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>W(n)}}};const Af={kernelName:Tr,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>W(n)}}};const Nf={kernelName:Ar,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>F(e,me(O(C(1),H(_(n,"float32")))))}}};const Rf={kernelName:Nr,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const o=me(R(C(1),H(_(n,"float32"))));return F(e,o)}}}};const _f={kernelName:Cr,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,o]=t,r=q(n.shape,o.shape),i=()=>{const s=R(H(n),H(o));let c=v(e,F(o,s));const p=ae(n.shape,r);return p.length>0&&(c=U(c,p)),y(c,n.shape)},a=()=>{const s=R(H(n),H(o));let c=ne(v(e,F(n,s)));const p=ae(o.shape,r);return p.length>0&&(c=U(c,p)),y(c,o.shape)};return{a:i,b:a}}};const Cf={kernelName:Rr,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>F(e,R(H(_(n,"float32")),1))}}};const Ef={kernelName:_r,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>F(e,O(C(1),H(_(n,"float32"))))}}};function QI(e,t,n,o,r=[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(o,r),()=>`Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides ${o} and dilations '${r}'`),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,o,r,i,a);return L.avgPool3dBackprop(p,l,S)},b={dy:p,input:l},x={filterSize:n,strides:o,dilations:r,pad:i,dimRoundingMode:a},w=g.runKernelFunc(d,b,null,Mc,x);return h?y(w,[w.shape[1],w.shape[2],w.shape[3],w.shape[4]]):w}const Of=m({avgPool3dBackprop_:QI});const kf={kernelName:Or,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[o]=t,{filterSize:r,strides:i,dilations:a,pad:s,dimRoundingMode:c}=n,p=a==null?[1,1,1]:a;return{x:()=>Of(e,o,r,i,p,s,c)}}};function eT(e,t,n,o,r){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,o,1,r);return x.avgPoolBackprop(c,s,w)},h={dy:c,input:s},d={filterSize:n,strides:o,pad:r},b=g.runKernelFunc(l,h,null,Fc,d);return p?y(b,[b.shape[1],b.shape[2],b.shape[3]]):b}const Df=m({avgPoolBackprop_:eT});const Ff={kernelName:Er,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[o]=t,{filterSize:r,strides:i,pad:a}=n;return{x:()=>Df(e,o,r,i,a)}}};const Mf={kernelName:kr,inputsToSave:["a","b"],gradFunc:(e,t,n)=>{const[o,r]=t,{transposeA:i,transposeB:a}=n;return!i&&!a?{a:()=>Y(e,r,!1,!0),b:()=>Y(o,e,!0,!1)}:!i&&a?{a:()=>Y(e,r,!1,!1),b:()=>Y(e,o,!0,!1)}:i&&!a?{a:()=>Y(r,e,!1,!0),b:()=>Y(o,e,!1,!1)}:{a:()=>Y(r,e,!0,!0),b:()=>Y(e,o,!0,!0)}}};const Uf={kernelName:Dr,gradFunc:(e,t,n)=>{const{blockShape:o,crops:r}=n;return{x:()=>Kn(e,o,r)}}};const Wf={kernelName:Fr,gradFunc:(e,t,n)=>{const o=n,r=o.inputShape,i=o.shape,a=Array.from(i);for(let c=r.length-1;c>=0;c--)if(r[c]===i[c])a[c]=1;else if(r[c]!==1)throw new Error(`broadcastTo(): [${r}] cannot be broadcast to [${i}].`);const s=[];for(let c=0;c<a.length;c++)a[c]>1&&s.push(c);return{x:()=>U(e,s,!0)}}};const Bf={kernelName:Dn,gradFunc:e=>({x:()=>e.clone()})};const $f={kernelName:Mr,gradFunc:e=>({x:()=>W(e)})};const jf={kernelName:Ur,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[o]=t,{clipValueMin:r,clipValueMax:i}=n;return{x:()=>Oe(Lt(ht(o,r),ut(o,i)),e,W(e))}}};const Gf={kernelName:Wr,saveAllInputs:!0,gradFunc:(e,t,n)=>{const o=t.map(c=>c.shape),{axis:r}=n,i=z(r,t[0].shape)[0],a=o.map(c=>c[i]),s=Yt(e,a,i);return s.map(c=>()=>c)}};const Pf={kernelName:Br,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[o,r]=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:()=>jo(o.shape,e,r,a,s,c),filter:()=>zo(o,e,r.shape,a,s,c)}}};const qf={kernelName:$r,inputsToSave:["dy","filter"],gradFunc:(e,t,n)=>{const[o,r]=t,{strides:i,pad:a,dataFormat:s,dimRoundingMode:c}=n;return{dy:()=>xe(e,r,i,a,s,1,c),filter:()=>zo(e,o,r.shape,i,a,s,c)}}};function tT(e,t,n,o,r){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,o,h,r);return l.conv3dDerFilter(i,a,d)},c={x:i,y:a},p={strides:o,pad:r};return g.runKernelFunc(s,c,null,Bc,p)}const Hf=m({conv3DBackpropFilter_:tT});const zf={kernelName:jr,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:o,strides:r,pad:i}=n;f(ct(o),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${o}'`);const[a,s]=t;return{x:()=>Da(a.shape,e,s,r,i),filter:()=>Hf(a,e,s.shape,r,i)}}};const Yf={kernelName:Gr,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(ne(Es(_(n,"float32"))),e)}}};const Vf={kernelName:Pr,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(Os(_(n,"float32")),e)}}};const Kf={kernelName:qr,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[o]=t,{axis:r,exclusive:i,reverse:a}=n;return{x:()=>{const s=ge([r],o.rank);let c=gs(e,r,i,!a);return s!=null&&(c=K(c,s)),c}}}};const Jf={kernelName:Hr,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:o,strides:r,pad:i,dimRoundingMode:a}=n,s=o==null?[1,1]:o;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(r,s),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${r} 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,r,s,i,a,!0);return{x:()=>Pa(c.shape,e,p,l),filter:()=>Ga(c,e,p.shape,l)}}};const Xf={kernelName:zr,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[o,r]=t,i={x:o,filter:r,dy:e},a={x:o,filter:r,dy:e};return{x:()=>g.runKernel(zc,i,n),filter:()=>g.runKernel(Yc,a,n)}}};const Zf={kernelName:Yr,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,o]=t,r=q(n.shape,o.shape),i=()=>{const s=F(e,_(o,"float32")),c=ae(n.shape,r);return c.length>0?y(U(s,c),n.shape):s},a=()=>{let s=v(e,_(n,"float32"));const c=ae(o.shape,r);c.length>0&&(s=y(U(s,c),o.shape));const p=H(o);return ne(F(s,_(p,"float32")))};return{a:i,b:a}}};const Qf={kernelName:Vr,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t,o=i=>i.eluDer(e,n),r={dy:e,y:n};return{x:()=>g.runKernelFunc(o,r,null,Vc)}}};const eg={kernelName:Kr,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,o=v(Se(ne(H(n))),2/Math.sqrt(Math.PI));return{x:()=>v(e,o)}}};const tg={kernelName:Jr,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(e,n)}}};const ng={kernelName:Xr,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(e,Se(n))}}};const og={kernelName:Zr,gradFunc:e=>({x:()=>W(e)})};const rg={kernelName:Qr,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,o]=t,r=q(n.shape,o.shape),i=()=>{const s=F(e,_(o,"float32")),c=ae(n.shape,r);return c.length>0?y(U(s,c),n.shape):s},a=()=>{let s=v(e,_(n,"float32"));const c=ae(o.shape,r);c.length>0&&(s=y(U(s,c),o.shape));const p=H(o);return ne(F(s,_(p,"float32")))};return{a:i,b:a}}};const ig={kernelName:ei,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{const{varianceEpsilon:o}=n,[r,i,a,s]=t,c=s==null?C(1):s,p=ae(i.shape,r.shape),l=[];if(i.rank===1){for(let A=0;A<r.shape.length-1;++A)l.push(r.shape[A]);l.push(1)}const h=O(r,i),d=v(e,c),b=Cs(R(a,C(o))),x=v(v(v(b,b),b),C(-.5)),w=()=>i.rank===1?y(v(v(e,Ot(y(b,[1,1,1,i.shape[0]]),l)),c),r.shape):y(v(v(e,b),c),r.shape),L=()=>{let A=v(v(b,C(-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 cg={kernelName:ti,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{const[o,r]=t,{axis:i}=n,a=z(i,o.shape)[0],s=()=>{const c=o.shape,p=r.size,l=c.slice(0,a),h=l.length,d=c.slice(i,c.length).slice(1),b=d.length,x=sg(0,h),w=sg(h+1,h+1+b),L=ag([l,[p],d]),S=y(e,L),I=y(r,[p]),N=ag([[h],x,w]),A=K(S,N);let E=Ds(A,I,o.shape[a]);const M=Un(N);return E=K(E,M),E};return{x:s,indices:()=>r}}};function sg(e,t){const n=[];for(let o=e;o<t;++o)n.push(o);return n}function ag(e){const t=[];for(let n=0;n<e.length;++n)for(let o=0;o<e[n].length;++o)t.push(e[n][o]);return t}const pg={kernelName:ni,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,o]=t;return{a:()=>W(n),b:()=>W(o)}}};const lg={kernelName:oi,gradFunc:e=>({x:()=>_(e,"float32")})};const hg={kernelName:ri,gradFunc:e=>({x:()=>W(e)})};const ug={kernelName:ii,gradFunc:e=>({x:()=>W(e)})};const dg={kernelName:si,gradFunc:e=>({x:()=>W(e)})};const mg={kernelName:ci,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>F(e,R(n,1))}}};const fg={kernelName:ai,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>F(e,_(n,"float32"))}}};const gg={kernelName:pi,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[o]=t,{axis:r}=n;return{logits:()=>{const i=!0,a=Se(o);return O(e,v(U(e,r,i),a))}}}};function nT(e,t,n,o=5,r=1,i=1,a=.5){const s=l=>l.LRNGrad(n,e,t,o,r,i,a),c={x:e,y:t,dy:n},p={depthRadius:o,bias:r,alpha:i,beta:a};return g.runKernelFunc(s,c,null,pp,p)}const bg=m({localResponseNormalizationBackprop_:nT});const wg={kernelName:li,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[o,r]=t,{depthRadius:i,bias:a,alpha:s,beta:c}=n;return{x:()=>bg(o,r,e,i,a,s,c)}}};function Za(e,t,n,o,r){return t.rank<n.rank&&(t=y(t,we(t.shape,o))),e.rank<n.rank&&(e=y(e,we(e.shape,o))),{x:()=>{const i=v(e,_(tn(n,t),e.dtype));return r==null?i:K(i,r)}}}const Xh={kernelName:hi,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const o=n,{reductionIndices:r}=o,[i,a]=t,s=z(r,i.shape),c=ge(s,i.rank),p=Za(e,a,i,s,c);return{x:()=>{let l=p.x();return c!=null&&(l=K(l)),l}}}};const xg={kernelName:ui,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,o]=t,r=()=>v(e,_(ht(n,o),"float32")),i=()=>v(e,_(Hn(n,o),"float32"));return{a:r,b:i}}};function oT(e,t,n,o,r,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(r,i),()=>`Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides ${r} 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,o,r,i,a,s);return N.maxPool3dBackprop(h,d,b,A)},L={dy:h,input:d,output:b},S={filterSize:o,strides:r,dilations:i,pad:a,dimRoundingMode:s},I=g.runKernelFunc(w,L,null,hp,S);return x?y(I,[I.shape[1],I.shape[2],I.shape[3],I.shape[4]]):I}const yg=m({maxPool3dBackprop_:oT});const Lg={kernelName:mi,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[o,r]=t,{filterSize:i,strides:a,dilations:s,pad:c,dimRoundingMode:p}=n,l=s==null?[1,1,1]:s;return{x:()=>yg(e,o,r,i,a,l,c,p)}}};function rT(e,t,n,o,r,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,o,r,1,i,a);return b.maxPoolBackprop(s,c,p,x)},h={dy:s,input:c,output:p},d={filterSize:o,strides:r,pad:i,dimRoundingMode:a};return g.runKernelFunc(l,h,null,lp,d)}const vg=m({maxPoolBackprop_:rT});const Sg={kernelName:di,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[o,r]=t,{filterSize:i,strides:a,pad:s}=n;return{x:()=>vg(e,o,r,i,a,s)}}};const Ig={kernelName:fi,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const o=n,{axis:r}=o,[i,a]=t,s=z(r,i.shape),c=ge(s,i.rank),p=Za(e,a,i,s,c);return{x:()=>{let l=p.x();return c!=null&&(l=K(l)),l}}}};const Tg={kernelName:gi,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,o]=t,r=()=>v(e,_(ut(n,o),"float32")),i=()=>v(e,_(tt(n,o),"float32"));return{a:r,b:i}}};const Ag={kernelName:bi,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,o]=t,r=q(n.shape,o.shape),i=()=>{const s=ae(n.shape,r);return s.length>0?y(U(e,s),n.shape):e},a=()=>{const s=v(e,ne(Pn(F(n,o)))),c=ae(o.shape,r);return c.length>0?y(U(s,c),o.shape):s};return{a:i,b:a}}};const Ng={kernelName:wi,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,o]=t,r=q(n.shape,o.shape),i=()=>{const s=v(e,_(o,"float32")),c=ae(n.shape,r);return c.length>0?y(U(s,c),n.shape):s},a=()=>{const s=v(e,_(n,"float32")),c=ae(o.shape,r);return c.length>0?y(U(s,c),o.shape):s};return{a:i,b:a}}};const Rg={kernelName:xi,gradFunc:e=>({x:()=>ne(e)})};const _g={kernelName:Li,inputsToSave:["indices"],gradFunc:(e,t)=>{const n=t[0];return{indices:()=>Ce(n.shape,"float32")}}};const Cg={kernelName:yi,gradFunc:e=>({x:()=>W(e)})};const Zh={kernelName:vi,inputsToSave:["x"],gradFunc:(e,t,n)=>{const o=t[0],{paddings:r}=n,i=r.map(a=>a[0]);return{x:()=>G(e,i,o.shape)}}};const Eg={kernelName:Si,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{const[n,o,r]=t,i=n,a=o,s=q(i.shape,a.shape),c=()=>{const l=_(a,"float32");let h=v(e,v(l,Je(i,O(l,C(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(r,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 Og={kernelName:Ii,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{const[n,o]=t,r=tt(n,0);return{x:()=>Oe(r,e,v(e,o)),alpha:()=>{let i=Oe(r,W(e),v(e,n));const a=ae(o.shape,e.shape);return a.length>0&&(i=U(i,a)),y(i,o.shape)}}}};const kg={kernelName:Ti,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>F(e,ne(H(n)))}}};const Dg={kernelName:Ci,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,o=v(ut(n,6),Dt(n));return{x:()=>v(e,_(o,"float32"))}}};const Fg={kernelName:Ai,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(e,_(Dt(n),"float32"))}}};const Mg={kernelName:Ni,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>y(e,n.shape)}}};const Ug={kernelName:_i,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[o]=t,r=s=>{const{alignCorners:c}=n;return s.resizeBilinearBackprop(e,o,c)},i={images:o},a=()=>g.runKernelFunc(r,i,null,Lp,n);return{images:a}}};const Wg={kernelName:Ri,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[o]=t,r=s=>{const{alignCorners:c}=n;return s.resizeNearestNeighborBackprop(e,o,c)},i={images:o},a=()=>g.runKernelFunc(r,i,null,yp,n);return{images:a}}};const Bg={kernelName:Ei,gradFunc:(e,t,n)=>{const{dims:o}=n,r=z(o,e.shape);return{x:()=>Ve(e,r)}}};const $g={kernelName:Oi,gradFunc:e=>({x:()=>W(e)})};const jg={kernelName:ki,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>ne(F(e,v(Je(n,1.5),2)))}}};const Gg={kernelName:Di,inputsToSave:["condition"],gradFunc:(e,t)=>{const[n]=t;return{condition:()=>_(W(n),"float32"),t:()=>v(e,_(n,e.dtype)),e:()=>v(e,_(zn(n),e.dtype))}}};const Pg={kernelName:Fi,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const o=tt(n,C(0)),r=C(Kh),i=C(Jh),a=v(e,i),s=v(v(e,r),Se(_(n,"float32")));return Oe(o,a,s)}}}};const qg={kernelName:$i,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(e,v(n,O(C(1),n)))}}};const Hg={kernelName:Bi,gradFunc:e=>({x:()=>W(e)})};const zg={kernelName:Ui,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(jn(_(n,"float32")),e)}}};const Yg={kernelName:Wi,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(fs(_(n,"float32")),e)}}};const Vg={kernelName:Mi,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[o]=t,{begin:r,size:i}=n,a=o.shape,[s,c]=ms(o,r,i),p=[];for(let l=0;l<e.rank;l++)p.push([s[l],a[l]-s[l]-c[l]]);return{x:()=>qe(e,p)}}};const Kg={kernelName:zi,outputsToSave:[!0],gradFunc:(e,t,n)=>{const[o]=t,{dim:r}=n,i=!0,a=v(e,o);return{logits:()=>O(a,v(U(a,[r],i),o))}}};const Jg={kernelName:ji,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(e,lt(n))}}};const Qh={kernelName:qi,gradFunc:(e,t,n)=>{const{blockShape:o,paddings:r}=n;return{x:()=>Bn(e,o,r)}}};const eu={kernelName:Hi,gradFunc:(e,t,n)=>{const{axis:o}=n;return{x:()=>Z(e,o)}}};const Xg={kernelName:Gi,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>F(e,v(me(_(n,"float32")),2))}}};const Zg={kernelName:Sp,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(e,v(_(n,"float32"),2))}}};const Qg={kernelName:Yi,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,o]=t,r=C(2),i=()=>v(e,v(r,O(n,o))),a=()=>v(e,v(r,O(o,n)));return{a:i,b:a}}};const eb={kernelName:ns,gradFunc:e=>({x:()=>W(e)})};const tb={kernelName:Vi,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,o]=t,r=q(n.shape,o.shape),i=()=>{let s=e;const c=ae(n.shape,r);return c.length>0&&(s=U(s,c)),y(s,n.shape)},a=()=>{let s=e;const c=ae(o.shape,r);return c.length>0&&(s=U(s,c)),y(ne(s),o.shape)};return{a:i,b:a}}};const nb={kernelName:Pi,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[o]=t,r=o.shape.slice(),{axis:i}=n,a=z(i,o.shape);a.forEach(p=>{r[p]=1});const s=y(e,r),c=v(s,vt(o.shape,"float32"));return{x:()=>c}}};const ob={kernelName:Ki,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>F(e,H(jn(n)))}}};const rb={kernelName:Ji,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(O(C(1),H(n)),e)}}};const ib={kernelName:Xi,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[o]=t,{reps:r}=n,i=()=>{let a=W(o);if(o.rank===1)for(let s=0;s<r[0];++s)a=R(a,G(e,[s*o.shape[0]],[o.shape[0]]));else if(o.rank===2)for(let s=0;s<r[0];++s)for(let c=0;c<r[1];++c)a=R(a,G(e,[s*o.shape[0],c*o.shape[1]],[o.shape[0],o.shape[1]]));else if(o.rank===3)for(let s=0;s<r[0];++s)for(let c=0;c<r[1];++c)for(let p=0;p<r[2];++p)a=R(a,G(e,[s*o.shape[0],c*o.shape[1],p*o.shape[2]],[o.shape[0],o.shape[1],o.shape[2]]));else if(o.rank===4)for(let s=0;s<r[0];++s)for(let c=0;c<r[1];++c)for(let p=0;p<r[2];++p)for(let l=0;l<r[3];++l)a=R(a,G(e,[s*o.shape[0],c*o.shape[1],p*o.shape[2],l*o.shape[3]],[o.shape[0],o.shape[1],o.shape[2],o.shape[3]]));else throw new Error(`Gradient for tile operation is not implemented for rank-${o.rank} tensors yet.`);return a};return{x:i}}};const sb={kernelName:Zi,gradFunc:(e,t,n)=>{const o=n,{perm:r}=o,i=Un(r);return{x:()=>K(e,i)}}};const ab={kernelName:Qi,gradFunc:(e,t,n)=>{const o=n,{axis:r}=o;return{value:()=>ke(e,r)}}};const cb={kernelName:es,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{const[n]=t,o=()=>iT(e,n);return{x:o}}};function iT(e,t){const n=kt(t,W(t)),o=qn(e,n);let r=ht(t,C(0,"int32"));const i=o.rank-r.rank;for(let s=0;s<i;++s)r=et(r,s+1);r=Lt(r,vt(o.shape,"bool"));const a=W(o);return Oe(r,o,a)}const pb={kernelName:ts,gradFunc:e=>({x:()=>W(e)})};const sT=[yf,Lf,vf,Sf,If,Tf,Af,Nf,Rf,_f,Cf,Ef,kf,Ff,Mf,Uf,Wf,Bf,$f,jf,Gf,qf,Pf,zf,Yf,Vf,Kf,Jf,Xf,Zf,Qf,eg,tg,ng,rg,og,ig,cg,pg,lg,hg,ug,dg,mg,fg,gg,wg,Xh,Xh,xg,Lg,Sg,Ig,Tg,Ag,Ng,Rg,_g,Cg,Zh,Zh,Eg,Og,kg,Dg,Fg,Mg,Ug,Wg,Bg,$g,jg,Gg,Pg,qg,Hg,zg,Yg,Vg,Kg,Jg,Qh,Qh,eu,eu,Xg,Qg,Zg,eb,tb,nb,ob,rb,ib,sb,ab,cb,pb];for(const e of sT)_p(e);const Ks={};Re(Ks,{Abs:()=>yr,Acos:()=>Lr,Acosh:()=>vr,AdadeltaOptimizer:()=>so,AdagradOptimizer:()=>ao,AdamOptimizer:()=>co,AdamaxOptimizer:()=>po,Add:()=>kn,AddN:()=>Sr,All:()=>kc,Any:()=>Dc,ArgMax:()=>Ir,ArgMin:()=>Tr,Asin:()=>Ar,Asinh:()=>Nr,Atan:()=>Rr,Atan2:()=>Cr,Atanh:()=>_r,AvgPool:()=>Er,AvgPool3D:()=>Or,AvgPool3DBackprop:()=>Mc,AvgPoolBackprop:()=>Fc,BatchMatMul:()=>kr,BatchToSpaceND:()=>Dr,BroadcastTo:()=>Fr,Cast:()=>Dn,Ceil:()=>Mr,ClipByValue:()=>Ur,Complex:()=>Uc,Concat:()=>Wr,Conv2D:()=>Br,Conv2DBackpropFilter:()=>Wc,Conv2DBackpropInput:()=>$r,Conv3D:()=>jr,Conv3DBackpropFilterV2:()=>Bc,Conv3DBackpropInputV2:()=>$c,Cos:()=>Gr,Cosh:()=>Pr,CropAndResize:()=>jc,Cumsum:()=>qr,DataStorage:()=>XI,DepthToSpace:()=>Gc,DepthwiseConv2dNative:()=>Hr,DepthwiseConv2dNativeBackpropFilter:()=>Pc,DepthwiseConv2dNativeBackpropInput:()=>qc,Diag:()=>Hc,Dilation2D:()=>zr,Dilation2DBackpropFilter:()=>Yc,Dilation2DBackpropInput:()=>zc,Div:()=>Yr,ENV:()=>lr,Elu:()=>Vr,EluGrad:()=>Vc,Environment:()=>_c,Equal:()=>Kc,Erf:()=>Kr,Exp:()=>Jr,Expm1:()=>Xr,FFT:()=>Jc,Fill:()=>Xc,FlipLeftRight:()=>Zc,Floor:()=>Zr,FloorDiv:()=>Qr,FromPixels:()=>Sa,FusedBatchNorm:()=>ei,FusedConv2D:()=>Ta,FusedDepthwiseConv2D:()=>Aa,GatherNd:()=>Qc,GatherV2:()=>ti,Greater:()=>ep,GreaterEqual:()=>ni,IFFT:()=>tp,Identity:()=>oi,Imag:()=>np,IsFinite:()=>ri,IsInf:()=>ii,IsNan:()=>si,KernelBackend:()=>ZI,LRN:()=>li,LRNBackprop:()=>pp,Less:()=>op,LessEqual:()=>rp,LinSpace:()=>ip,Log:()=>ai,Log1p:()=>ci,LogSoftmax:()=>pi,LogicalAnd:()=>sp,LogicalNot:()=>ap,LogicalOr:()=>cp,Max:()=>hi,MaxPool:()=>di,MaxPool3D:()=>mi,MaxPool3DBackprop:()=>hp,MaxPoolBackprop:()=>lp,MaxPoolWithArgmax:()=>up,Maximum:()=>ui,Mean:()=>hw,Min:()=>fi,Minimum:()=>gi,Mod:()=>bi,MomentumOptimizer:()=>lo,Multiply:()=>wi,Negate:()=>xi,NonMaxSuppressionV3:()=>mp,NonMaxSuppressionV4:()=>fp,NonMaxSuppressionV5:()=>gp,NotEqual:()=>dp,OneHot:()=>Li,OnesLike:()=>yi,Optimizer:()=>rt,PadV2:()=>vi,Pool:()=>uw,Pow:()=>Si,Prelu:()=>Ii,Prod:()=>bp,RMSPropOptimizer:()=>ho,Range:()=>wp,Rank:()=>Bp,Real:()=>xp,Reciprocal:()=>Ti,Reduction:()=>be,Relu:()=>Ai,Relu6:()=>Ci,Reshape:()=>Ni,ResizeBilinear:()=>_i,ResizeBilinearGrad:()=>Lp,ResizeNearestNeighbor:()=>Ri,ResizeNearestNeighborGrad:()=>yp,Reverse:()=>Ei,RotateWithOffset:()=>Np,Round:()=>Oi,Rsqrt:()=>ki,SGDOptimizer:()=>rn,ScatterNd:()=>vp,SelectV2:()=>Di,Selu:()=>Fi,Sigmoid:()=>$i,Sign:()=>Bi,Sin:()=>Ui,Sinh:()=>Wi,Slice:()=>Mi,Softmax:()=>zi,Softplus:()=>ji,SpaceToBatchND:()=>qi,SparseToDense:()=>Ip,SplitV:()=>Hi,Sqrt:()=>Gi,Square:()=>Sp,SquaredDifference:()=>Yi,Step:()=>ns,StridedSlice:()=>Tp,Sub:()=>Vi,Sum:()=>Pi,Tan:()=>Ki,Tanh:()=>Ji,Tensor:()=>ee,TensorBuffer:()=>Fo,Tile:()=>Xi,TopK:()=>Ap,Transpose:()=>Zi,Unpack:()=>Qi,UnsortedSegmentSum:()=>es,Variable:()=>Ht,ZerosLike:()=>ts,_FusedMatMul:()=>Ia,abs:()=>Ee,acos:()=>zp,acosh:()=>Yp,add:()=>R,addN:()=>Vp,addStrict:()=>rm,all:()=>Xp,any:()=>Zp,argMax:()=>Qp,argMin:()=>el,asin:()=>tl,asinh:()=>nl,atan:()=>ol,atan2:()=>rl,atanh:()=>il,avgPool:()=>pt,avgPool3d:()=>pl,backend:()=>Rx,backend_util:()=>ff,basicLSTMCell:()=>yl,batchNorm:()=>Ct,batchNorm2d:()=>Ll,batchNorm3d:()=>vl,batchNorm4d:()=>Sl,batchToSpaceND:()=>Bn,booleanMaskAsync:()=>Xd,broadcastTo:()=>$o,browser:()=>Jo,buffer:()=>Be,cast:()=>_,ceil:()=>Il,clipByValue:()=>$n,clone:()=>Et,complex:()=>Ye,concat:()=>Z,concat1d:()=>Tl,concat2d:()=>Al,concat3d:()=>Nl,concat4d:()=>Rl,conv1d:()=>_l,conv2d:()=>xe,conv2dTranspose:()=>Cl,conv3d:()=>El,conv3dTranspose:()=>Ol,cos:()=>jn,cosh:()=>fs,cosineWindow:()=>Ho,cumsum:()=>gs,customGrad:()=>Ke,deprecationWarn:()=>Le,depthToSpace:()=>kl,depthwiseConv2d:()=>en,device_util:()=>Wd,diag:()=>Dl,dilation2d:()=>Fl,disableDeprecationWarnings:()=>fx,dispose:()=>ve,disposeVariables:()=>gx,div:()=>F,divNoNan:()=>Ml,divStrict:()=>im,dot:()=>Ul,dropout:()=>vm,elu:()=>ws,enableDebugMode:()=>mx,enableProdMode:()=>dx,enclosingPowerOfTwo:()=>ja,engine:()=>bx,env:()=>pe,equal:()=>tn,equalStrict:()=>Zd,erf:()=>Wl,exp:()=>Se,expandDims:()=>et,expm1:()=>Bl,eye:()=>xs,fft:()=>Gn,fill:()=>Pe,findBackend:()=>Tx,findBackendFactory:()=>Ax,floor:()=>Pn,floorDiv:()=>bs,fused:()=>Uh,gather:()=>qn,gatherND:()=>ym,gather_util:()=>uf,getBackend:()=>Sx,getGradient:()=>Na,getKernel:()=>rs,getKernelsForBackend:()=>Ra,grad:()=>Zy,grads:()=>Qy,greater:()=>tt,greaterEqual:()=>ht,greaterEqualStrict:()=>Qd,greaterStrict:()=>em,ifft:()=>vn,imag:()=>nn,image:()=>Ka,inTopKAsync:()=>Sm,io:()=>Ko,irfft:()=>ys,isFinite:()=>jl,isInf:()=>Gl,isNaN:()=>Pl,keep:()=>cl,kernel_impls:()=>xf,leakyRelu:()=>ql,less:()=>Hn,lessEqual:()=>ut,lessEqualStrict:()=>tm,lessStrict:()=>nm,linalg:()=>Qm,linspace:()=>Hl,localResponseNormalization:()=>zl,log:()=>yt,log1p:()=>Ls,logSigmoid:()=>Vl,logSoftmax:()=>Kl,logSumExp:()=>Ss,logicalAnd:()=>Lt,logicalNot:()=>zn,logicalOr:()=>Is,logicalXor:()=>Jl,losses:()=>ef,matMul:()=>Y,math:()=>hf,max:()=>dt,maxPool:()=>Ae,maxPool3d:()=>Xl,maxPoolWithArgmax:()=>Zl,maximum:()=>kt,maximumStrict:()=>sm,mean:()=>Sn,memory:()=>wx,min:()=>In,minimum:()=>Yn,minimumStrict:()=>am,mod:()=>Ts,modStrict:()=>cm,moments:()=>Ql,movingAverage:()=>mm,mul:()=>v,mulStrict:()=>pm,multiRNNCell:()=>eh,multinomial:()=>th,neg:()=>ne,nextFrame:()=>SI,norm:()=>qo,notEqual:()=>Vn,notEqualStrict:()=>om,oneHot:()=>Go,ones:()=>vt,onesLike:()=>Ua,op:()=>m,outerProduct:()=>nh,pad:()=>qe,pad1d:()=>oh,pad2d:()=>rh,pad3d:()=>ih,pad4d:()=>sh,pool:()=>ah,pow:()=>Je,powStrict:()=>lm,prelu:()=>As,print:()=>ch,prod:()=>ph,profile:()=>xx,rand:()=>lh,randomGamma:()=>mh,randomNormal:()=>fh,randomUniform:()=>Rs,range:()=>Po,ready:()=>vx,real:()=>zt,reciprocal:()=>gh,registerBackend:()=>Nx,registerGradient:()=>_p,registerKernel:()=>dw,relu:()=>ie,relu6:()=>_s,removeBackend:()=>Ix,reshape:()=>y,reverse:()=>Ve,reverse1d:()=>bh,reverse2d:()=>wh,reverse3d:()=>xh,reverse4d:()=>yh,rfft:()=>Jn,round:()=>vh,rsqrt:()=>Cs,scalar:()=>C,scatterND:()=>bm,scatter_util:()=>fm,selu:()=>Sh,separableConv2d:()=>Xn,serialization:()=>mf,setBackend:()=>Lx,setPlatform:()=>_x,setdiff1dAsync:()=>Ih,sigmoid:()=>lt,sign:()=>Th,signal:()=>Zm,sin:()=>Es,sinh:()=>Os,slice:()=>G,slice1d:()=>Ah,slice2d:()=>Nh,slice3d:()=>ks,slice4d:()=>Rh,slice_util:()=>Gd,softmax:()=>on,softplus:()=>vs,spaceToBatchND:()=>Kn,sparseToDense:()=>xm,spectral:()=>Xm,split:()=>Yt,sqrt:()=>me,square:()=>H,squaredDifference:()=>Zn,squaredDifferenceStrict:()=>hm,squeeze:()=>Qn,stack:()=>ke,step:()=>Dt,stridedSlice:()=>_h,sub:()=>O,subStrict:()=>um,sum:()=>U,sumOutType:()=>Fw,tan:()=>Ch,tanh:()=>Bo,tensor:()=>Ge,tensor1d:()=>ce,tensor2d:()=>mt,tensor3d:()=>eo,tensor4d:()=>ft,tensor5d:()=>Eh,tensor6d:()=>Oh,tensor_util:()=>Fd,test_util:()=>Yd,tidy:()=>k,tile:()=>Ot,time:()=>yx,topk:()=>kh,train:()=>LI,transpose:()=>K,truncatedNormal:()=>Dh,unregisterGradient:()=>fw,unregisterKernel:()=>mw,unsortedSegmentSum:()=>Ds,unstack:()=>Ie,upcastType:()=>Uo,util:()=>yd,valueAndGrad:()=>eL,valueAndGrads:()=>tL,variable:()=>Fh,variableGrads:()=>Yl,version_core:()=>Lc,where:()=>Oe,whereAsync:()=>Fs,zeros:()=>Ce,zerosLike:()=>W});function sn(e,t,n=!1){if(e.beginPath(),t.slice(1).forEach(({x:o,y:r},i)=>{const a=t[i];e.moveTo(a.x,a.y),e.lineTo(o,r)}),n){const o=t[t.length-1],r=t[0];if(!o||!r)return;e.moveTo(o.x,o.y),e.lineTo(r.x,r.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 Xs={};Re(Xs,{computeReshapedDimensions:()=>ou,getCenterPoint:()=>fo,isDimensions:()=>ec,isEven:()=>Qa,isFloat:()=>nu,isTensor:()=>uo,isTensor1D:()=>aT,isTensor2D:()=>tu,isTensor3D:()=>an,isTensor4D:()=>gt,isValidNumber:()=>Mt,isValidProbablitiy:()=>Zo,range:()=>Vt,round:()=>mo});function uo(e,t){return e instanceof ee&&e.shape.length===t}function aT(e){return uo(e,1)}function tu(e){return uo(e,2)}function an(e){return uo(e,3)}function gt(e){return uo(e,4)}function nu(e){return e%1!==0}function Qa(e){return e%2===0}function mo(e,t=2){const n=Math.pow(10,t);return Math.floor(e*n)/n}function ec(e){return e&&e.width&&e.height}function ou({width:e,height:t},n){const o=n/Math.max(t,e);return new Qe(Math.round(e*o),Math.round(t*o))}function fo(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((o,r)=>t+r*n)}function Mt(e){return!!e&&e!==Infinity&&e!==-Infinity&&!isNaN(e)||e===0}function Zo(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||{},o=[n.left,n.top,n.right,n.bottom].every(Mt),r=[n.x,n.y,n.width,n.height].every(Mt);if(!r&&!o)throw new Error(`Box.constructor - expected box to be IBoundingBox | IRect, instead have ${JSON.stringify(n)}`);const[i,a,s,c]=r?[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,o]=[this.x,this.y,this.width,this.height].map(r=>Math.round(r));return new de({x:e,y:t,width:n,height:o})}floor(){const[e,t,n,o]=[this.x,this.y,this.width,this.height].map(r=>Math.floor(r));return new de({x:e,y:t,width:n,height:o})}toSquare(){let{x:e,y:t,width:n,height:o}=this;const r=Math.abs(n-o);return n<o&&(e-=r/2,n+=r),o<n&&(t-=r/2,o+=r),new de({x:e,y:t,width:n,height:o})}rescale(e){const t=ec(e)?e.width:e,n=ec(e)?e.height:e;return new de({x:this.x*t,y:this.y*n,width:this.width*t,height:this.height*n})}pad(e,t){let[n,o,r,i]=[this.x-e/2,this.y-t/2,this.width+e,this.height+t];return new de({x:n,y:o,width:r,height:i})}clipAtImageBorders(e,t){const{x:n,y:o,right:r,bottom:i}=this,a=Math.max(n,0),s=Math.max(o,0),c=r-a,p=i-s,l=Math.min(c,e-a),h=Math.min(p,t-s);return new de({x:a,y:s,width:l,height:h}).floor()}shift(e,t){const{width:n,height:o}=this,r=this.x+e,i=this.y+t;return new de({x:r,y:i,width:n,height:o})}padAtBorders(e,t){const n=this.width+1,o=this.height+1;let r=1,i=1,a=n,s=o,c=this.left,p=this.top,l=this.right,h=this.bottom;return l>t&&(a=-l+t+n,l=t),h>e&&(s=-h+e+o,h=e),c<1&&(s=2-c,c=1),p<1&&(s=2-p,p=1),{dy:i,edy:s,dx:r,edx:a,y:p,ey:h,x:c,ex:l,w:n,h:o}}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 _o extends de{constructor(e,t,n,o,r=!1){super({left:e,top:t,right:n,bottom:o},r)}}class On{constructor(e,t,n,o,r){this._imageDims=new Qe(r.width,r.height),this._score=e,this._classScore=t,this._className=n,this._box=new de(o).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:o,imageDims:r}=super.forSize(e,t);return new fe(n,o,r)}}function ra(e,t,n=!0){const o=Math.max(0,Math.min(e.right,t.right)-Math.max(e.left,t.left)),r=Math.max(0,Math.min(e.bottom,t.bottom)-Math.max(e.top,t.top)),i=o*r;return n?i/(e.area+t.area-i):i/Math.min(e.area,t.area)}function oa(e){const t=e.map(s=>s.x),n=e.map(s=>s.y),o=t.reduce((s,c)=>c<s?c:s,Infinity),r=n.reduce((s,c)=>c<s?c:s,Infinity),i=t.reduce((s,c)=>s<c?c:s,0),a=n.reduce((s,c)=>s<c?c:s,0);return new _o(o,r,i,a)}function na(e,t,n,o=!0){let r=t.map((a,s)=>({score:a,boxIndex:s})).sort((a,s)=>a.score-s.score).map(a=>a.boxIndex);const i=[];for(;r.length>0;){const a=r.pop();i.push(a);const s=r,c=[];for(let p=0;p<s.length;p++){const l=s[p],h=e[a],d=e[l];c.push(ra(h,d,o))}r=r.filter((p,l)=>c[l]<=n)}return i}function wt(e,t){return k(()=>{const[n,o,r]=t,i=Pe([...e.shape.slice(0,3),1],n),a=Pe([...e.shape.slice(0,3),1],o),s=Pe([...e.shape.slice(0,3),1],r),c=Z([i,a,s],3);return O(e,c)})}function ta(e,t=!1){return k(()=>{const[n,o]=e.shape.slice(1);if(n===o)return e;const r=Math.abs(n-o),i=Math.round(r*(t?.5:1)),a=n>o?2:1,s=d=>{const b=e.shape.slice();return b[a]=d,Pe(b,0)},c=s(i),p=r-c.shape[a],l=t&&p?s(p):null,h=[l,e,c].filter(d=>!!d).map(d=>_(d,"float32"));return Z(h,a)})}function ju(e){const t=e.slice();for(let n=t.length-1;n>0;n--){const o=Math.floor(Math.random()*(n+1)),r=t[n];t[n]=t[o],t[o]=r}return t}function vo(e){return 1/(1+Math.exp(-e))}function Gu(e){return Math.log(e/(1-e))}class No extends de{constructor(e,t,n,o,r=!1){super({x:e,y:t,width:n,height:o},r)}}const cT=.5,pT=.43,lT=.45;class st{constructor(e,t,n=new J(0,0)){const{width:o,height:r}=t;this._imgDims=new Qe(o,r),this._shift=n,this._positions=e.map(i=>i.mul(new J(o,r)).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 r=e instanceof fe?e.box.floor():new de(e);return this.shiftBy(r.x,r.y).align(null,t)}const{useDlibAlignment:n,minBoxPadding:o}=Object.assign({},{useDlibAlignment:!1,minBoxPadding:.2},t);return n?this.alignDlib():this.alignMinBbox(o)}alignDlib(){const e=this.getRefPointsForAlignment(),[t,n,o]=e,r=l=>o.sub(l).magnitude(),i=(r(t)+r(n))/2,a=Math.floor(i/lT),s=fo(e),c=Math.floor(Math.max(0,s.x-cT*a)),p=Math.floor(Math.max(0,s.y-pT*a));return new No(c,p,Math.min(a,this.imageWidth+c),Math.min(a,this.imageHeight+p))}alignMinBbox(e){const t=oa(this.positions);return t.pad(t.width*e,t.height*e)}getRefPointsForAlignment(){throw new Error("getRefPointsForAlignment not implemented by base class")}}class gd extends st{getRefPointsForAlignment(){const e=this.positions;return[e[0],e[1],fo([e[3],e[4]])]}}class Ro 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(fo)}}class xr{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?` (${mo(this.distance)})`:""}`}}class wr 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 fd extends wr{constructor(e,t,n,o){super(e,t);this._score=n,this._classScore=o}static assertIsValidPredictedBox(e,t){if(wr.assertIsValidLabeledBox(e,t),!Zo(e.score)||!Zo(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 tc(e){let t="";if(!e)try{e=require("fs")}catch(o){t=o.toString()}const n=e?function(o){return new Promise((r,i)=>{e.readFile(o,function(a,s){return a?i(a):r(s)})})}:function(){throw new Error(`readFile - failed to require fs in nodejs environment with error: ${t}`)};return{readFile:n}}function iu(){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")},o=function(){if(t)return new t;throw new Error("createImageElement - missing Image implementation for nodejs environment")},r=global.fetch||function(){throw new Error("fetch - missing fetch implementation for nodejs environment")},i=tc();return Ys({Canvas:e||class{},CanvasRenderingContext2D:global.CanvasRenderingContext2D||class{},Image:t||class{},ImageData:global.ImageData||class{},Video:global.HTMLVideoElement||class{},createCanvasElement:n,createImageElement:o,fetch:r},i)}function su(){return typeof window=="object"&&typeof document!="undefined"&&typeof HTMLImageElement!="undefined"&&typeof HTMLCanvasElement!="undefined"&&typeof HTMLVideoElement!="undefined"&&typeof ImageData!="undefined"&&typeof CanvasRenderingContext2D!="undefined"}const au=gu(Du());let Fe;function hT(){if(!Fe)throw new Error("getEnv - environment is not defined, check isNodejs() and isBrowser()");return Fe}function cu(e){Fe=e}function pu(){if(su())return cu(ru());if(au.isNodejs())return cu(iu())}function uT(e){if(Fe||pu(),!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:hT,setEnv:cu,initialize:pu,createBrowserEnv:ru,createFileSystem:tc,createNodejsEnv:iu,monkeyPatch:uT,isBrowser:su,isNodejs:au.isNodejs};pu();function gn(e){return!se.isNodejs()&&typeof e=="string"?document.getElementById(e):e}function He(e){const{Canvas:t,CanvasRenderingContext2D:n}=se.getEnv();if(e instanceof n)return e;const o=gn(e);if(!(o instanceof t))throw new Error("resolveContext2d - expected canvas to be of instance of Canvas");const r=o.getContext("2d");if(!r)throw new Error("resolveContext2d - canvas 2d context is null");return r}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 nc{constructor(e={}){const{anchorPosition:t,backgroundColor:n,fontColor:o,fontSize:r,fontStyle:i,padding:a}=e;this.anchorPosition=t||Kt.TOP_LEFT,this.backgroundColor=n||"rgba(0, 0, 0, 0.5)",this.fontColor=o||"rgba(255, 255, 255, 1)",this.fontSize=r||14,this.fontStyle=i||"Georgia",this.padding=a||4}}class Qo{constructor(e,t,n={}){this.text=typeof e=="string"?[e]:e instanceof Qo?e.text:e,this.anchor=t,this.options=new nc(n)}measureWidth(e){const{padding:t}=this.options;return this.text.map(n=>e.measureText(n).width).reduce((n,o)=>n<o?o:n,0)+2*t}measureHeight(){const{fontSize:e,padding:t}=this.options;return this.text.length*e+2*t}getUpperLeft(e,t){const{anchorPosition:n}=this.options,o=n===Kt.BOTTOM_RIGHT||n===Kt.TOP_RIGHT,r=n===Kt.BOTTOM_LEFT||n===Kt.BOTTOM_RIGHT,i=this.measureWidth(e),a=this.measureHeight(),s=o?this.anchor.x-i:this.anchor.x,c=r?this.anchor.y-a:this.anchor.y;if(t){const{width:p,height:l}=t,h=Math.max(Math.min(s,p-i),0),d=Math.max(Math.min(c,l-a),0);return{x:h,y:d}}return{x:s,y:c}}draw(e){const t=gn(e),n=He(t),{backgroundColor:o,fontColor:r,fontSize:i,fontStyle:a,padding:s}=this.options;n.font=`${i}px ${a}`;const c=this.measureWidth(n),p=this.measureHeight();n.fillStyle=o;const l=this.getUpperLeft(n,t);n.fillRect(l.x,l.y,c,p),n.fillStyle=r,this.text.forEach((h,d)=>{const b=s+l.x,x=s+l.y+(d+1)*i;n.fillText(h,b,x)})}}class lb{constructor(e={}){const{boxColor:t,lineWidth:n,label:o,drawLabelOptions:r}=e;this.boxColor=t||"rgba(0, 0, 255, 1)",this.lineWidth=n||2,this.label=o;const i={anchorPosition:Kt.BOTTOM_LEFT,backgroundColor:this.boxColor};this.drawLabelOptions=new nc(Object.assign({},i,r))}}class lu{constructor(e,t={}){this.box=new de(e),this.options=new lb(t)}draw(e){const t=He(e),{boxColor:n,lineWidth:o}=this.options,{x:r,y:i,width:a,height:s}=this.box;t.strokeStyle=n,t.lineWidth=o,t.strokeRect(r,i,a,s);const{label:c}=this.options;c&&new Qo([c],{x:r-o/2,y:i},this.options.drawLabelOptions).draw(e)}}function dT(e,t){const n=Array.isArray(t)?t:[t];n.forEach(o=>{const r=o instanceof fe?o.score:Nt(o)?o.detection.score:void 0,i=o instanceof fe?o.box:Nt(o)?o.detection.box:new de(o),a=r?`${mo(r)}`:void 0;new lu(i,{label:a}).draw(e)})}function To(e){const{Image:t,Video:n}=se.getEnv();return e instanceof t&&e.complete||e instanceof n&&e.readyState>=3}function La(e){return new Promise((t,n)=>{if(e instanceof se.getEnv().Canvas||To(e))return t(null);function o(i){if(!i.currentTarget)return;i.currentTarget.removeEventListener("load",o),i.currentTarget.removeEventListener("error",r),t(i)}function r(i){if(!i.currentTarget)return;i.currentTarget.removeEventListener("load",o),i.currentTarget.removeEventListener("error",r),n(i)}e.addEventListener("load",o),e.addEventListener("error",r)})}function ya(e){return new Promise((t,n)=>{if(!(e instanceof Blob))return n("bufferToImage - expected buf to be of type: Blob");const o=new FileReader;o.onload=()=>{if(typeof o.result!="string")return n("bufferToImage - expected reader.result to be a string, in onload");const r=se.getEnv().createImageElement();r.onload=()=>t(r),r.onerror=n,r.src=o.result},o.onerror=n,o.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(),o=n();return o.width=e,o.height=t,o}function Ao(e,t){const{ImageData:n}=se.getEnv();if(!(e instanceof n)&&!To(e))throw new Error("createCanvasFromMedia - media has not finished loading yet");const{width:o,height:r}=t||bn(e),i=En({width:o,height:r});return e instanceof n?He(i).putImageData(e,0,0):He(i).drawImage(e,0,0,o,r),i}async function wa(e,t){const n=t||se.getEnv().createCanvasElement(),[o,r,i]=e.shape.slice(gt(e)?1:0),a=k(()=>e.as3D(o,r,i).toInt());return await Jo.toPixels(a,n),a.dispose(),n}function br(e){const{Image:t,Canvas:n,Video:o}=se.getEnv();return e instanceof t||e instanceof n||e instanceof o}function ba(e,t,n=!1){const{Image:o,Canvas:r}=se.getEnv();if(!(e instanceof o||e instanceof r))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 r?e:Ao(e),h=Math.abs(s-c)/2,d=n&&s<c?h:0,b=n&&c<s?h:0;return He(p).drawImage(l,d,b,s,c),p}class Jt{constructor(e,t=!1){if(this._imageTensors=[],this._canvases=[],this._treatAsBatchInput=!1,this._inputDimensions=[],!Array.isArray(e))throw new Error(`NetInput.constructor - expected inputs to be an Array of TResolvedNetInput or to be instanceof tf.Tensor4D, instead have ${e}`);this._treatAsBatchInput=t,this._batchSize=e.length,e.forEach((n,o)=>{if(an(n)){this._imageTensors[o]=n,this._inputDimensions[o]=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[o]=n,this._inputDimensions[o]=n.shape.slice(1);return}const r=n instanceof se.getEnv().Canvas?n:Ao(n);this._canvases[o]=r,this._inputDimensions[o]=[r.height,r.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 ou({width:t,height:n},this.inputSize)}toBatchTensor(e,t=!0){return this._inputSize=e,k(()=>{const n=Vt(this.batchSize,0,1).map(r=>{const i=this.getInput(r);if(i instanceof ee){let a=gt(i)?i:i.expandDims();return a=ta(a,t),(a.shape[1]!==e||a.shape[2]!==e)&&(a=Ka.resizeBilinear(a,[e,e])),a.as3D(e,e,3)}if(i instanceof se.getEnv().Canvas)return Jo.fromPixels(ba(i,e,t));throw new Error(`toBatchTensor - at batchIdx ${r}, expected input to be instanceof tf.Tensor or instanceof HTMLCanvasElement, instead have ${i}`)}),o=ke(n.map(r=>_(r,"float32"))).as4D(this.batchSize,e,e,3);return o})}}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=r=>Array.isArray(e)?` at input index ${r}:`:"",o=t.map(gn);return o.forEach((r,i)=>{if(!br(r)&&!an(r)&&!gt(r))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(r)){const a=r.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(o.map(r=>br(r)&&La(r))),new Jt(o,Array.isArray(e))}async function _n(e,t){const{Canvas:n}=se.getEnv();let o=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);o=s instanceof n?s:await wa(s)}const r=He(o),i=t.map(a=>a instanceof fe?a.forSize(o.width,o.height).box.floor():a).map(a=>a.clipAtImageBorders(o.width,o.height));return i.map(({x:a,y:s,width:c,height:p})=>{const l=En({width:c,height:p});return He(l).putImageData(r.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,o,r]=e.shape.slice(gt(e)?1:0),i=t.map(s=>s instanceof fe?s.forSize(o,n).box:s).map(s=>s.clipAtImageBorders(o,n)),a=i.map(({x:s,y:c,width:p,height:l})=>ks(e.as3D(n,o,r),[c,s,0],[l,p,r]));return a})}async function wn(e,t){const n=se.getEnv().fetch,o=await n(e,t);if(!(o.status<400))throw new Error(`failed to fetch: (${o.status}) ${o.statusText}, from url: ${o.url}`);return o}async function md(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 ya(n)}async function xa(e){return(await wn(e)).json()}async function dd(e){return new Float32Array(await(await wn(e)).arrayBuffer())}function oc(e,t){const n=`${t}-weights_manifest.json`;if(!e)return{modelBaseUri:"",manifestUri:n};if(e==="/")return{modelBaseUri:"/",manifestUri:`/${n}`};const o=e.startsWith("http://")?"http://":e.startsWith("https://")?"https://":"";e=e.replace(o,"");const r=e.split("/").filter(s=>s),i=e.endsWith(".json")?r[r.length-1]:n;let a=o+(e.endsWith(".json")?r.slice(0,r.length-1):r).join("/");return a=e.startsWith("/")?`/${a}`:a,{modelBaseUri:a,manifestUri:a==="/"?`/${i}`:`${a}/${i}`}}async function ga(e,t){const{manifestUri:n,modelBaseUri:o}=oc(e,t);let r=await xa(n);return Ko.loadWeights(r,o)}function ud(e,t,n=!1){const{width:o,height:r}=n?bn(t):t;return e.width=o,e.height=r,{width:o,height:r}}class Ue{constructor(e){this._name=e,this._params=void 0,this._paramMappings=[];try{const t=Ge([0]);t.toFloat()}catch(t){throw new Error(`module not loaded: load '@tensorflow/tfjs' or '@tensorflow/tfjs-core' with appropriate backend explicitly: ${t}`)}}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:o}=this.traversePropertyPath(e);n[o].dispose(),n[o]=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=Ge(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 ga(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:o}=oc(e,this.getDefaultModelName()),r=c=>Promise.all(c.map(p=>t(p).then(l=>l.buffer))),i=Ko.weightsLoaderFactory(r),a=JSON.parse((await t(n)).toString()),s=await i(a,o);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((r,i)=>{if(!r.nextObj.hasOwnProperty(i))throw new Error(`traversePropertyPath - object does not have property ${i}, for path ${e}`);return{obj:r.nextObj,objProp:i,nextObj:r.nextObj[i]}},{nextObj:this.params}),{obj:n,objProp:o}=t;if(!n||!o||!(n[o]instanceof ee))throw new Error(`traversePropertyPath - parameter is not a tensor, for path ${e}`);return{obj:n,objProp:o}}}function ot(e,t,n){return k(()=>{let o=Xn(e,t.depthwise_filter,t.pointwise_filter,n,"same");return o=R(o,t.bias),o})}function rc(e,t,n=!1){return k(()=>{const o=ie(n?R(xe(e,t.conv0.filters,[2,2],"same"),t.conv0.bias):ot(e,t.conv0,[2,2])),r=ot(o,t.conv1,[1,1]),i=ie(R(o,r)),a=ot(i,t.conv2,[1,1]);return ie(R(o,R(r,a)))})}function Bs(e,t,n=!1,o=!0){return k(()=>{const r=ie(n?R(xe(e,t.conv0.filters,o?[2,2]:[1,1],"same"),t.conv0.bias):ot(e,t.conv0,o?[2,2]:[1,1])),i=ot(r,t.conv1,[1,1]),a=ie(R(r,i)),s=ot(a,t.conv2,[1,1]),c=ie(R(r,R(i,s))),p=ot(c,t.conv3,[1,1]);return ie(R(r,R(i,R(s,p))))})}function go(e,t,n="same",o=!1){return k(()=>{const r=R(xe(e,t.filters,[1,1],n),t.bias);return o?ie(r):r})}function Xe(e,t){Object.keys(e).forEach(n=>{t.some(o=>o.originalPath===n)||e[n].dispose()})}function er(e,t){return function(n,o,r,i){const a=ft(e(n*o*r*r),[r,r,n,o]),s=ce(e(o));return t.push({paramPath:`${i}/filters`},{paramPath:`${i}/bias`}),{filters:a,bias:s}}}function ic(e,t){return function(n,o,r){const i=mt(e(n*o),[n,o]),a=ce(e(o));return t.push({paramPath:`${r}/weights`},{paramPath:`${r}/bias`}),{weights:i,bias:a}}}class hu{constructor(e,t,n){this.depthwise_filter=e,this.pointwise_filter=t,this.bias=n}}function tr(e,t){return function(n,o,r){const i=ft(e(3*3*n),[3,3,n,1]),a=ft(e(n*o),[1,1,n,o]),s=ce(e(o));return t.push({paramPath:`${r}/depthwise_filter`},{paramPath:`${r}/pointwise_filter`},{paramPath:`${r}/bias`}),new hu(i,a,s)}}function nr(e){return function(t){const n=e(`${t}/depthwise_filter`,4),o=e(`${t}/pointwise_filter`,4),r=e(`${t}/bias`,1);return new hu(n,o,r)}}function it(e,t){return function(n,o,r){const i=e[n];if(!uo(i,o))throw new Error(`expected weightMap[${n}] to be a Tensor${o}D, instead have ${i}`);return t.push({originalPath:n,paramPath:r||n}),i}}function Ze(e){let t=e;function n(r){const i=t.slice(0,r);return t=t.slice(r),i}function o(){return t}return{extractWeights:n,getRemainingWeights:o}}function sc(e,t){const n=er(e,t),o=tr(e,t);function r(a,s,c,p=!1){const l=p?n(a,s,3,`${c}/conv0`):o(a,s,`${c}/conv0`),h=o(s,s,`${c}/conv1`),d=o(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}=r(a,s,c,p),b=o(s,s,`${c}/conv3`);return{conv0:l,conv1:h,conv2:d,conv3:b}}return{extractDenseBlock3Params:r,extractDenseBlock4Params:i}}function hb(e){const t=[],{extractWeights:n,getRemainingWeights:o}=Ze(e),{extractDenseBlock4Params:r}=sc(n,t),i=r(3,32,"dense0",!0),a=r(32,64,"dense1"),s=r(64,128,"dense2"),c=r(128,256,"dense3");if(o().length!==0)throw new Error(`weights remaing after extract: ${o().length}`);return{paramMappings:t,params:{dense0:i,dense1:a,dense2:s,dense3:c}}}function ac(e){return function(t){const n=e(`${t}/filters`,4),o=e(`${t}/bias`,1);return{filters:n,bias:o}}}function cc(e,t){const n=it(e,t),o=ac(n),r=nr(n);function i(s,c=!1){const p=c?o(`${s}/conv0`):r(`${s}/conv0`),l=r(`${s}/conv1`),h=r(`${s}/conv2`);return{conv0:p,conv1:l,conv2:h}}function a(s,c=!1){const p=c?o(`${s}/conv0`):r(`${s}/conv0`),l=r(`${s}/conv1`),h=r(`${s}/conv2`),d=r(`${s}/conv3`);return{conv0:p,conv1:l,conv2:h,conv3:d}}return{extractDenseBlock3Params:i,extractDenseBlock4Params:a}}function ub(e){const t=[],{extractDenseBlock4Params:n}=cc(e,t),o={dense0:n("dense0",!0),dense1:n("dense1"),dense2:n("dense2"),dense3:n("dense3")};return Xe(e,t),{params:o,paramMappings:t}}class pc 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),o=[122.782,117.001,104.298],r=wt(n,o).div(C(255));let i=Bs(r,t.dense0,!0);return i=Bs(i,t.dense1),i=Bs(i,t.dense2),i=Bs(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 ub(e)}extractParams(e){return hb(e)}}function $s(e,t){return k(()=>R(Y(e,t.weights),t.bias))}function db(e,t,n){const o=[],{extractWeights:r,getRemainingWeights:i}=Ze(e),a=ic(r,o),s=a(t,n,"fc");if(i().length!==0)throw new Error(`weights remaing after extract: ${i().length}`);return{paramMappings:o,params:{fc:s}}}function mb(e){const t=[],n=it(e,t);function o(i){const a=n(`${i}/weights`,2),s=n(`${i}/bias`,1);return{weights:a,bias:s}}const r={fc:o("fc")};return Xe(e,t),{params:r,paramMappings:t}}function lc(e){const t={},n={};return Object.keys(e).forEach(o=>{const r=o.startsWith("fc")?n:t;r[o]=e[o]}),{featureExtractorMap:t,classifierMap:n}}class hc 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 $s(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 db(e,this.getClassifierChannelsIn(),this.getClassifierChannelsOut())}extractParamsFromWeigthMap(e){const{featureExtractorMap:t,classifierMap:n}=lc(e);return this.faceFeatureExtractor.loadFromWeightMap(t),mb(n)}extractParams(e){const t=this.getClassifierChannelsIn(),n=this.getClassifierChannelsOut(),o=n*t+n,r=e.slice(0,e.length-o),i=e.slice(e.length-o);return this.faceFeatureExtractor.extractWeights(r),this.extractClassifierParams(i)}}const da=["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}`);da.forEach((t,n)=>{this[t]=e[n]})}asSortedArray(){return da.map(e=>({expression:e,probability:this[e]})).sort((e,t)=>t.probability-e.probability)}}class ma extends hc{constructor(e=new pc){super("FaceExpressionNet",e)}forwardInput(e){return k(()=>on(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),o=await Promise.all(Ie(n).map(async i=>{const a=await i.data();return i.dispose(),a}));n.dispose();const r=o.map(i=>new fn(i));return t.isBatchInput?r:r[0]}getDefaultModelName(){return"face_expression_model"}getClassifierChannelsIn(){return 256}getClassifierChannelsOut(){return 7}}function ha(e){return e.expressions instanceof fn}function mr(e,t){const n={expressions:t};return Object.assign({},e,n)}function mT(e,t,n=.1,o){const r=Array.isArray(t)?t:[t];r.forEach(i=>{const a=i instanceof fn?i:ha(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:o||new J(0,0),l=new Qo(c.map(h=>`${h.expression} (${mo(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,o=t.shiftBy(n.x,n.y),r=o.align(),{imageDims:i}=e.detection,a=new fe(e.detection.score,r.rescale(i.reverse()),i),s={landmarks:o,unshiftedLandmarks:t,alignedRect:a};return Object.assign({},e,s)}class fb{constructor(e={}){const{drawLines:t=!0,drawPoints:n=!0,lineWidth:o,lineColor:r,pointSize:i,pointColor:a}=e;this.drawLines=t,this.drawPoints=n,this.lineWidth=o||1,this.pointSize=i||2,this.lineColor=r||"rgba(0, 255, 255, 1)",this.pointColor=a||"rgba(255, 0, 255, 1)"}}class gb{constructor(e,t={}){this.faceLandmarks=e,this.options=new fb(t)}draw(e){const t=He(e),{drawLines:n,drawPoints:o,lineWidth:r,lineColor:i,pointSize:a,pointColor:s}=this.options;if(n&&this.faceLandmarks instanceof Ro&&(t.strokeStyle=i,t.lineWidth=r,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)),o){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 fT(e,t){const n=Array.isArray(t)?t:[t];n.forEach(o=>{const r=o instanceof st?o:dn(o)?o.landmarks:void 0;if(!r)throw new Error("drawFaceLandmarks - expected faceExpressions to be FaceLandmarks | WithFaceLandmarks<WithFaceDetection<{}>> or array thereof");new gb(r).draw(e)})}const Js={};Re(Js,{AnchorPosition:()=>Kt,DrawBox:()=>lu,DrawBoxOptions:()=>lb,DrawFaceLandmarks:()=>gb,DrawFaceLandmarksOptions:()=>fb,DrawTextField:()=>Qo,DrawTextFieldOptions:()=>nc,drawContour:()=>sn,drawDetections:()=>dT,drawFaceExpressions:()=>mT,drawFaceLandmarks:()=>fT});function gT(e,t){const n=er(e,t),o=tr(e,t);function r(a,s,c){const p=o(a,s,`${c}/separable_conv0`),l=o(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=o(a,a,`${s}/separable_conv0`),p=o(a,a,`${s}/separable_conv1`),l=o(a,a,`${s}/separable_conv2`);return{separable_conv0:c,separable_conv1:p,separable_conv2:l}}return{extractConvParams:n,extractSeparableConvParams:o,extractReductionBlockParams:r,extractMainBlockParams:i}}function bb(e,t){const n=[],{extractWeights:o,getRemainingWeights:r}=Ze(e),{extractConvParams:i,extractSeparableConvParams:a,extractReductionBlockParams:s,extractMainBlockParams:c}=gT(o,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(r().length!==0)throw new Error(`weights remaing after extract: ${r().length}`);return{paramMappings:n,params:{entry_flow:d,middle_flow:b,exit_flow:L}}}function bT(e,t){const n=it(e,t),o=ac(n),r=nr(n);function i(s){const c=r(`${s}/separable_conv0`),p=r(`${s}/separable_conv1`),l=o(`${s}/expansion_conv`);return{separable_conv0:c,separable_conv1:p,expansion_conv:l}}function a(s){const c=r(`${s}/separable_conv0`),p=r(`${s}/separable_conv1`),l=r(`${s}/separable_conv2`);return{separable_conv0:c,separable_conv1:p,separable_conv2:l}}return{extractConvParams:o,extractSeparableConvParams:r,extractReductionBlockParams:i,extractMainBlockParams:a}}function wb(e,t){const n=[],{extractConvParams:o,extractSeparableConvParams:r,extractReductionBlockParams:i,extractMainBlockParams:a}=bT(e,n),s=o("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=r("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 xb(e,t,n){return R(xe(e,t.filters,n,"same"),t.bias)}function uu(e,t,n=!0){let o=n?ie(e):e;return o=ot(o,t.separable_conv0,[1,1]),o=ot(ie(o),t.separable_conv1,[1,1]),o=Ae(o,[3,3],[2,2],"same"),o=R(o,xb(e,t.expansion_conv,[2,2])),o}function wT(e,t){let n=ot(ie(e),t.separable_conv0,[1,1]);return n=ot(ie(n),t.separable_conv1,[1,1]),n=ot(ie(n),t.separable_conv2,[1,1]),n=R(n,e),n}class yb 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),o=[122.782,117.001,104.298],r=wt(n,o).div(C(256));let i=ie(xb(r,t.entry_flow.conv_in,[2,2]));return i=uu(i,t.entry_flow.reduction_block_0,!1),i=uu(i,t.entry_flow.reduction_block_1),Vt(this._numMainBlocks,0,1).forEach(a=>{i=wT(i,t.middle_flow[`main_block_${a}`])}),i=uu(i,t.exit_flow.reduction_block),i=ie(ot(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 wb(e,this._numMainBlocks)}extractParams(e){return bb(e,this._numMainBlocks)}}function Lb(e){const t=[],{extractWeights:n,getRemainingWeights:o}=Ze(e),r=ic(n,t),i=r(512,1,"fc/age"),a=r(512,2,"fc/gender");if(o().length!==0)throw new Error(`weights remaing after extract: ${o().length}`);return{paramMappings:t,params:{fc:{age:i,gender:a}}}}function vb(e){const t=[],n=it(e,t);function o(i){const a=n(`${i}/weights`,2),s=n(`${i}/bias`,1);return{weights:a,bias:s}}const r={fc:{age:o("fc/age"),gender:o("fc/gender")}};return Xe(e,t),{params:r,paramMappings:t}}var Bt;(function(e){e.FEMALE="female",e.MALE="male"})(Bt||(Bt={}));class va extends Ue{constructor(e=new yb(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,o=pt(n,[7,7],[2,2],"valid").as2D(n.shape[0],-1),r=$s(o,t.fc.age).as1D(),i=$s(o,t.fc.gender);return{age:r,gender:i}})}forwardInput(e){return k(()=>{const{age:t,gender:n}=this.runNet(e);return{age:t,gender:on(n)}})}async forward(e){return this.forwardInput(await ue(e))}async predictAgeAndGender(e){const t=await ue(e),n=await this.forwardInput(t),o=Ie(n.age),r=Ie(n.gender),i=o.map((s,c)=>({ageTensor:s,genderTensor:r[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 Lb(e)}extractParamsFromWeigthMap(e){const{featureExtractorMap:t,classifierMap:n}=lc(e);return this.faceFeatureExtractor.loadFromWeightMap(t),vb(n)}extractParams(e){const t=512*1+1+(512*2+2),n=e.slice(0,e.length-t),o=e.slice(e.length-t);return this.faceFeatureExtractor.extractWeights(n),this.extractClassifierParams(o)}}class uc extends hc{postProcess(e,t,n){const o=n.map(({width:i,height:a})=>{const s=t/Math.max(a,i);return{width:i*s,height:a*s}}),r=o.length;return k(()=>{const i=(l,h)=>ke([Pe([68],l),Pe([68],h)],1).as2D(1,136).as1D(),a=(l,h)=>{const{width:d,height:b}=o[l];return h(d,b)?Math.abs(d-b)/2:0},s=l=>a(l,(h,d)=>h<d),c=l=>a(l,(h,d)=>d<h),p=e.mul(Pe([r,136],t)).sub(ke(Array.from(Array(r),(l,h)=>i(s(h),c(h))))).div(ke(Array.from(Array(r),(l,h)=>i(o[h].width,o[h].height))));return p})}forwardInput(e){return k(()=>{const t=this.runNet(e);return this.postProcess(t,e.inputSize,e.inputDimensions.map(([n,o])=>({height:n,width:o})))})}async forward(e){return this.forwardInput(await ue(e))}async detectLandmarks(e){const t=await ue(e),n=k(()=>Ie(this.forwardInput(t))),o=await Promise.all(n.map(async(r,i)=>{const a=Array.from(await r.data()),s=a.filter((p,l)=>Qa(l)),c=a.filter((p,l)=>!Qa(l));return new Ro(Array(68).fill(0).map((p,l)=>new J(s[l],c[l])),{height:t.getInputHeight(i),width:t.getInputWidth(i)})}));return n.forEach(r=>r.dispose()),t.isBatchInput?o:o[0]}getClassifierChannelsOut(){return 136}}class Io extends uc{constructor(e=new pc){super("FaceLandmark68Net",e)}getDefaultModelName(){return"face_landmark_68_model"}getClassifierChannelsIn(){return 256}}function Sb(e){const t=[],{extractDenseBlock3Params:n}=cc(e,t),o={dense0:n("dense0",!0),dense1:n("dense1"),dense2:n("dense2")};return Xe(e,t),{params:o,paramMappings:t}}function Ib(e){const t=[],{extractWeights:n,getRemainingWeights:o}=Ze(e),{extractDenseBlock3Params:r}=sc(n,t),i=r(3,32,"dense0",!0),a=r(32,64,"dense1"),s=r(64,128,"dense2");if(o().length!==0)throw new Error(`weights remaing after extract: ${o().length}`);return{paramMappings:t,params:{dense0:i,dense1:a,dense2:s}}}class Tb 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),o=[122.782,117.001,104.298],r=wt(n,o).div(C(255));let i=rc(r,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 Sb(e)}extractParams(e){return Ib(e)}}class ua extends uc{constructor(e=new Tb){super("FaceLandmark68TinyNet",e)}getDefaultModelName(){return"face_landmark_68_tiny_model"}getClassifierChannelsIn(){return 128}}class hd extends Io{}function Ab(e,t){return R(v(e,t.weights),t.biases)}function du(e,t,n,o,r="same"){const{filters:i,bias:a}=t.conv;let s=xe(e,i,n,r);return s=R(s,a),s=Ab(s,t.scale),o?ie(s):s}function Nb(e,t){return du(e,t,[1,1],!0)}function mu(e,t){return du(e,t,[1,1],!1)}function dc(e,t){return du(e,t,[2,2],!0,"valid")}function xT(e,t){function n(s,c,p){const l=e(s),h=l.length/(c*p*p);if(nu(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 o(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 r(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=o(s,c,p,`${l}/conv`),d=r(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 Rb(e){const{extractWeights:t,getRemainingWeights:n}=Ze(e),o=[],{extractConvLayerParams:r,extractResidualLayerParams:i}=xT(t,o),a=r(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(o.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:o}}function yT(e,t){const n=it(e,t);function o(a){const s=n(`${a}/scale/weights`,1),c=n(`${a}/scale/biases`,1);return{weights:s,biases:c}}function r(a){const s=n(`${a}/conv/filters`,4),c=n(`${a}/conv/bias`,1),p=o(a);return{conv:{filters:s,bias:c},scale:p}}function i(a){return{conv1:r(`${a}/conv1`),conv2:r(`${a}/conv2`)}}return{extractConvLayerParams:r,extractResidualLayerParams:i}}function _b(e){const t=[],{extractConvLayerParams:n,extractResidualLayerParams:o}=yT(e,t),r=n("conv32_down"),i=o("conv32_1"),a=o("conv32_2"),s=o("conv32_3"),c=o("conv64_down"),p=o("conv64_1"),l=o("conv64_2"),h=o("conv64_3"),d=o("conv128_down"),b=o("conv128_1"),x=o("conv128_2"),w=o("conv256_down"),L=o("conv256_1"),S=o("conv256_2"),I=o("conv256_down_out"),N=e.fc;if(t.push({originalPath:"fc",paramPath:"fc"}),!tu(N))throw new Error(`expected weightMap[fc] to be a Tensor2D, instead have ${N}`);const A={conv32_down:r,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=Nb(e,t.conv1);return n=mu(n,t.conv2),n=R(n,e),n=ie(n),n}function js(e,t){let n=dc(e,t.conv1);n=mu(n,t.conv2);let o=pt(e,2,2,"valid");const r=Ce(o.shape),i=o.shape[3]!==n.shape[3],a=o.shape[1]!==n.shape[1]||o.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 o=i?Z([o,r],3):o,n=R(o,n),n=ie(n),n}class So 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),"float32"),o=[122.782,117.001,104.298],r=wt(n,o).div(C(256));let i=dc(r,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=js(i,t.conv64_down),i=Ut(i,t.conv64_1),i=Ut(i,t.conv64_2),i=Ut(i,t.conv64_3),i=js(i,t.conv128_down),i=Ut(i,t.conv128_1),i=Ut(i,t.conv128_2),i=js(i,t.conv256_down),i=Ut(i,t.conv256_1),i=Ut(i,t.conv256_2),i=js(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))),o=await Promise.all(n.map(r=>r.data()));return n.forEach(r=>r.dispose()),t.isBatchInput?o:o[0]}getDefaultModelName(){return"face_recognition_model"}extractParamsFromWeigthMap(e){return _b(e)}extractParams(e){return Rb(e)}}function ld(e){const t=new So;return t.extractWeights(e),t}function fr(e,t){const n={descriptor:t};return Object.assign({},e,n)}function pd(e){return typeof e.age=="number"}function gr(e,t){const n={age:t};return Object.assign({},e,n)}function cd(e){return(e.gender===Bt.MALE||e.gender===Bt.FEMALE)&&Zo(e.genderProbability)}function dr(e,t,n){const o={gender:t,genderProbability:n};return Object.assign({},e,o)}function LT(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 o(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 r(c,p,l,h){const{filters:d,bias:b}=o(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=r(c,p,1,`${l}/pointwise_conv`);return{depthwise_conv:h,pointwise_conv:d}}function a(){const c=r(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=r(1024,256,1,"prediction_layer/conv_0"),p=r(256,512,3,"prediction_layer/conv_1"),l=r(512,128,1,"prediction_layer/conv_2"),h=r(128,256,3,"prediction_layer/conv_3"),d=r(256,128,1,"prediction_layer/conv_4"),b=r(128,256,3,"prediction_layer/conv_5"),x=r(256,64,1,"prediction_layer/conv_6"),w=r(64,128,3,"prediction_layer/conv_7"),L=o(512,12,1,"prediction_layer/box_predictor_0/box_encoding_predictor"),S=o(512,9,1,"prediction_layer/box_predictor_0/class_predictor"),I=o(1024,24,1,"prediction_layer/box_predictor_1/box_encoding_predictor"),N=o(1024,18,1,"prediction_layer/box_predictor_1/class_predictor"),A=o(512,24,1,"prediction_layer/box_predictor_2/box_encoding_predictor"),E=o(512,18,1,"prediction_layer/box_predictor_2/class_predictor"),M=o(256,24,1,"prediction_layer/box_predictor_3/box_encoding_predictor"),D=o(256,18,1,"prediction_layer/box_predictor_3/class_predictor"),$=o(256,24,1,"prediction_layer/box_predictor_4/box_encoding_predictor"),B=o(256,18,1,"prediction_layer/box_predictor_4/class_predictor"),j=o(128,24,1,"prediction_layer/box_predictor_5/box_encoding_predictor"),te=o(128,18,1,"prediction_layer/box_predictor_5/class_predictor"),oe={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:oe,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 Cb(e){const t=[],{extractWeights:n,getRemainingWeights:o}=Ze(e),{extractMobilenetV1Params:r,extractPredictionLayerParams:i}=LT(n,t),a=r(),s=i(),c=eo(n(5118*4),[1,5118,4]),p={extra_dim:c};if(t.push({paramPath:"output_layer/extra_dim"}),o().length!==0)throw new Error(`weights remaing after extract: ${o().length}`);return{params:{mobilenetv1:a,prediction_layer:s,output_layer:p},paramMappings:t}}function vT(e,t){const n=it(e,t);function o(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 r(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:o("MobilenetV1",p,b)}}function i(){return{conv_0:o("MobilenetV1",0,"mobilenetv1/conv_0"),conv_1:r(1),conv_2:r(2),conv_3:r(3),conv_4:r(4),conv_5:r(5),conv_6:r(6),conv_7:r(7),conv_8:r(8),conv_9:r(9),conv_10:r(10),conv_11:r(11),conv_12:r(12),conv_13:r(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:o("Prediction",0,"prediction_layer/conv_0"),conv_1:o("Prediction",1,"prediction_layer/conv_1"),conv_2:o("Prediction",2,"prediction_layer/conv_2"),conv_3:o("Prediction",3,"prediction_layer/conv_3"),conv_4:o("Prediction",4,"prediction_layer/conv_4"),conv_5:o("Prediction",5,"prediction_layer/conv_5"),conv_6:o("Prediction",6,"prediction_layer/conv_6"),conv_7:o("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 Eb(e){const t=[],{extractMobilenetV1Params:n,extractPredictionLayerParams:o}=vT(e,t),r=e["Output/extra_dim"];if(t.push({originalPath:"Output/extra_dim",paramPath:"output_layer/extra_dim"}),!an(r))throw new Error(`expected weightMap['Output/extra_dim'] to be a Tensor3D, instead have ${r}`);const i={mobilenetv1:n(),prediction_layer:o(),output_layer:{extra_dim:r}};return Xe(e,t),{params:i,paramMappings:t}}function It(e,t,n){return k(()=>{let o=xe(e,t.filters,n,"same");return o=R(o,t.batch_norm_offset),$n(o,0,6)})}const ST=.0010000000474974513;function IT(e,t,n){return k(()=>{let o=en(e,t.filters,n,"same");return o=Ct(o,t.batch_norm_mean,t.batch_norm_variance,t.batch_norm_offset,t.batch_norm_scale,ST),$n(o,0,6)})}function TT(e){return[2,4,6,12].some(t=>t===e)?[2,2]:[1,1]}function Ob(e,t){return k(()=>{let n=null,o=It(e,t.conv_0,[2,2]);const r=[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(r.forEach((i,a)=>{const s=a+1,c=TT(s);o=IT(o,i.depthwise_conv,c),o=It(o,i.pointwise_conv,[1,1]),s===11&&(n=o)}),n===null)throw new Error("mobileNetV1 - output of conv layer 11 is null");return{out:o,conv11:n}})}function kb(e,t,n,o,r){const i=e.shape[0],a=Math.min(n,i),s=t.map((l,h)=>({score:l,boxIndex:h})).filter(l=>l.score>r).sort((l,h)=>h.score-l.score),c=l=>l<=o?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=AT(e,l.boxIndex,p[d]);if(b===0)continue;if(l.score*=c(b),l.score<=r)break}h===l.score&&p.push(l.boxIndex)}),p}function AT(e,t,n){const o=e.arraySync(),r=Math.min(o[t][0],o[t][2]),i=Math.min(o[t][1],o[t][3]),a=Math.max(o[t][0],o[t][2]),s=Math.max(o[t][1],o[t][3]),c=Math.min(o[n][0],o[n][2]),p=Math.min(o[n][1],o[n][3]),l=Math.max(o[n][0],o[n][2]),h=Math.max(o[n][1],o[n][3]),d=(a-r)*(s-i),b=(l-c)*(h-p);if(d<=0||b<=0)return 0;const x=Math.max(r,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 NT(e){const t=Ie(K(e,[1,0])),n=[O(t[2],t[0]),O(t[3],t[1])],o=[R(t[0],F(n[0],C(2))),R(t[1],F(n[1],C(2)))];return{sizes:n,centers:o}}function RT(e,t){const{sizes:n,centers:o}=NT(e),r=Ie(K(t,[1,0])),i=F(v(Se(F(r[2],C(5))),n[0]),C(2)),a=R(v(F(r[0],C(10)),n[0]),o[0]),s=F(v(Se(F(r[3],C(5))),n[1]),C(2)),c=R(v(F(r[1],C(10)),n[1]),o[1]);return K(ke([O(a,i),O(c,s),R(a,i),R(c,s)]),[1,0])}function Db(e,t,n){return k(()=>{const o=e.shape[0];let r=RT(y(Ot(n.extra_dim,[o,1,1]),[-1,4]),y(e,[-1,4]));r=y(r,[o,r.shape[0]/o,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,[o,a.shape[1]]);const s=Ie(r),c=Ie(a);return{boxes:s,scores:c}})}function bo(e,t){return k(()=>{const n=e.shape[0],o=y(go(e,t.box_encoding_predictor),[n,-1,1,4]),r=y(go(e,t.class_predictor),[n,-1,3]);return{boxPredictionEncoding:o,classPrediction:r}})}function Fb(e,t,n){return k(()=>{const o=It(e,n.conv_0,[1,1]),r=It(o,n.conv_1,[2,2]),i=It(r,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=bo(t,n.box_predictor_0),d=bo(e,n.box_predictor_1),b=bo(r,n.box_predictor_2),x=bo(a,n.box_predictor_3),w=bo(c,n.box_predictor_4),L=bo(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),"float32"),o=O(v(n,C(.007843137718737125)),C(1)),r=Ob(o,t.mobilenetv1),{boxPredictions:i,classPredictions:a}=Fb(r.out,r.conv11,t.prediction_layer);return Db(i,a,t.output_layer)})}async forward(e){return this.forwardInput(await ue(e))}async locateFaces(e,t={}){const{maxResults:n,minConfidence:o}=new bt(t),r=await ue(e),{boxes:i,scores:a}=this.forwardInput(r),s=i[0],c=a[0];for(let I=1;I<i.length;I++)i[I].dispose(),a[I].dispose();const p=Array.from(await c.data()),l=.5,h=kb(s,p,n,l,o),d=r.getReshapedInputDimensions(0),b=r.inputSize,x=b/d.width,w=b/d.height,L=s.arraySync(),S=h.map(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 No(E,N,M-E,A-N),{height:r.getInputHeight(0),width:r.getInputWidth(0)})});return s.dispose(),c.dispose(),S}getDefaultModelName(){return"ssd_mobilenetv1_model"}extractParamsFromWeigthMap(e){return Eb(e)}extractParams(e){return Cb(e)}}function vc(e){const t=new Nn;return t.extractWeights(e),t}function Bu(e){return vc(e)}class $u extends Nn{}const Mb=.4,Ub=[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)],Wb=[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)],Bb=[117.001,114.697,97.404],$b="tiny_yolov2_model",jb="tiny_yolov2_separable_conv_model";const mc=e=>typeof e=="number";function Zs(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(!mc(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=>mc(t.x)&&mc(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(mc)))throw new Error(`config.meanRgb has to be an array of shape [number, number, number], have: ${JSON.stringify(e.meanRgb)}`)}function or(e){return k(()=>{const t=v(e,C(.10000000149011612));return R(ie(O(e,t)),t)})}function cn(e,t){return k(()=>{let n=qe(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),or(n)})}function pn(e,t){return k(()=>{let n=qe(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),or(n)})}function _T(e,t){const n=er(e,t);function o(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 r(a,s,c){const p=n(a,s,3,`${c}/conv`),l=o(s,`${c}/bn`);return{conv:p,bn:l}}const i=tr(e,t);return{extractConvParams:n,extractConvWithBatchNormParams:r,extractSeparableConvParams:i}}function Gb(e,t,n,o){const{extractWeights:r,getRemainingWeights:i}=Ze(e),a=[],{extractConvParams:s,extractConvWithBatchNormParams:c,extractSeparableConvParams:p}=_T(r,a);let l;if(t.withSeparableConvs){const[h,d,b,x,w,L,S,I,N]=o,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,oe=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:oe}}else{const[h,d,b,x,w,L,S,I,N]=o,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"),oe=s(N,5*n,1,"conv8");l={conv0:A,conv1:E,conv2:M,conv3:D,conv4:$,conv5:B,conv6:j,conv7:te,conv8:oe}}if(i().length!==0)throw new Error(`weights remaing after extract: ${i().length}`);return{params:l,paramMappings:a}}function CT(e,t){const n=it(e,t);function o(s){const c=n(`${s}/sub`,1),p=n(`${s}/truediv`,1);return{sub:c,truediv:p}}function r(s){const c=n(`${s}/filters`,4),p=n(`${s}/bias`,1);return{filters:c,bias:p}}function i(s){const c=r(`${s}/conv`),p=o(`${s}/bn`);return{conv:c,bn:p}}const a=nr(n);return{extractConvParams:r,extractConvWithBatchNormParams:i,extractSeparableConvParams:a}}function Pb(e,t){const n=[],{extractConvParams:o,extractConvWithBatchNormParams:r,extractSeparableConvParams:i}=CT(e,n);let a;if(t.withSeparableConvs){const s=t.filterSizes&&t.filterSizes.length||9;a={conv0:t.isFirstLayerConv2d?o("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:o("conv8")}}else a={conv0:r("conv0"),conv1:r("conv1"),conv2:r("conv2"),conv3:r("conv3"),conv4:r("conv4"),conv5:r("conv5"),conv6:r("conv6"),conv7:r("conv7"),conv8:o("conv8")};return Xe(e,n),{params:a,paramMappings:n}}var Qs;(function(e){e[e.XS=224]="XS",e[e.SM=320]="SM",e[e.MD=416]="MD",e[e.LG=608]="LG"})(Qs||(Qs={}));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 rr extends Ue{constructor(e){super("TinyYolov2");Zs(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),go(n,t.conv8,"valid",!1)}runMobilenet(e,t){let n=this.config.isFirstLayerConv2d?or(go(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,go(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 o=_(e.toBatchTensor(t,!1),"float32");return o=this.config.meanRgb?wt(o,this.config.meanRgb):o,o=o.div(C(256)),this.config.withSeparableConvs?this.runMobilenet(o,n):this.runTinyYolov2(o,n)})}async forward(e,t){return await this.forwardInput(await ue(e),t)}async detect(e,t={}){const{inputSize:n,scoreThreshold:o}=new Wt(t),r=await ue(e),i=await this.forwardInput(r,n),a=k(()=>Ie(i)[0].expandDims()),s={width:r.getInputWidth(0),height:r.getInputHeight(0)},c=await this.extractBoxes(a,r.getReshapedInputDimensions(0),o);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=na(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 Pb(e,this.config)}extractParams(e){const t=this.config.filterSizes||rr.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 Gb(e,this.config,this.boxEncodingSize,t)}async extractBoxes(e,t,n){const{width:o,height:r}=t,i=Math.max(o,r),a=i/o,s=i/r,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?on(L.slice([0,0,0,5],[c,c,p,this.config.classes.length]),3):C(0);return[S,I,N]}),b=[],x=await h.array(),w=await l.array();for(let L=0;L<c;L++)for(let S=0;S<c;S++)for(let I=0;I<p;I++){const N=vo(x[L][S][I][0]);if(!n||N>n){const A=(S+vo(w[L][S][I][0]))/c*a,E=(L+vo(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:oe}=this.withClassScores?await this.extractPredictedClass(d,j):{classScore:1,label:0};b.push(Ys({box:new _o($,B,$+M,B+D),score:N,classScore:N*te,label:oe},j))}}return l.dispose(),h.dispose(),d.dispose(),b}async extractPredictedClass(e,t){const{row:n,col:o,anchor:r}=t,i=await e.array();return Array(this.config.classes.length).fill(0).map((a,s)=>i[n][o][r][s]).map((a,s)=>({classScore:a,label:s})).reduce((a,s)=>a.classScore>s.classScore?a:s)}}rr.DEFAULT_FILTER_SIZES=[3,16,32,64,128,256,512,1024,1024];class yo extends rr{constructor(e=!0){const t=Object.assign({},{withSeparableConvs:e,iouThreshold:Mb,classes:["face"]},e?{anchors:Wb,meanRgb:Bb}:{anchors:Ub,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(o=>new fe(o.score,o.relativeBox,{width:o.imageWidth,height:o.imageHeight}))}getDefaultModelName(){return this.withSeparableConvs?jb:$b}extractParamsFromWeigthMap(e){return super.extractParamsFromWeigthMap(e)}}function Uu(e,t=!0){const n=new yo(t);return n.extractWeights(e),n}class ea 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 wo(e,t,n,o,r=({alignedRect:i})=>i){const i=e.map(c=>dn(c)?r(c):c.detection),a=o||(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 ir(e,t,n,o,r){return wo([e],t,async i=>n(i[0]),o,r)}const qb=.4,Hb=[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)],zb=[117.001,114.697,97.404];class Lo extends rr{constructor(){const e={withSeparableConvs:!0,iouThreshold:qb,classes:["face"],anchors:Hb,meanRgb:zb,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(o=>new fe(o.score,o.relativeBox,{width:o.imageWidth,height:o.imageHeight}))}getDefaultModelName(){return"tiny_face_detector_model"}extractParamsFromWeigthMap(e){return super.extractParamsFromWeigthMap(e)}}const re={ssdMobilenetv1:new Nn,tinyFaceDetector:new Lo,tinyYolov2:new yo,faceLandmark68Net:new Io,faceLandmark68TinyNet:new ua,faceRecognitionNet:new So,faceExpressionNet:new ma,ageGenderNet:new va},Ic=(e,t)=>re.ssdMobilenetv1.locateFaces(e,t),Pu=(e,t)=>re.tinyFaceDetector.locateFaces(e,t),qu=(e,t)=>re.tinyYolov2.locateFaces(e,t),Tc=e=>re.faceLandmark68Net.detectLandmarks(e),Hu=e=>re.faceLandmark68TinyNet.detectLandmarks(e),zu=e=>re.faceRecognitionNet.computeFaceDescriptor(e),Yu=e=>re.faceExpressionNet.predictExpressions(e),Vu=e=>re.ageGenderNet.predictAgeAndGender(e),Ac=e=>re.ssdMobilenetv1.load(e),Ku=e=>re.tinyFaceDetector.load(e),Ju=e=>re.tinyYolov2.load(e),Xu=e=>re.faceLandmark68Net.load(e),Zu=e=>re.faceLandmark68TinyNet.load(e),Qu=e=>re.faceRecognitionNet.load(e),ed=e=>re.faceExpressionNet.load(e),td=e=>re.ageGenderNet.load(e),nd=Ac,od=Ic,rd=Tc;class Yb extends xt{constructor(e,t,n){super();this.parentTask=e,this.input=t,this.extractedFaces=n}}class qs extends Yb{async run(){const e=await this.parentTask,t=await wo(e,this.input,async n=>await Promise.all(n.map(o=>re.faceExpressionNet.predictExpressions(o))),this.extractedFaces);return e.map((n,o)=>mr(n,t[o]))}withAgeAndGender(){return new Gs(this,this.input)}}class Hs extends Yb{async run(){const e=await this.parentTask;if(!e)return;const t=await ir(e,this.input,n=>re.faceExpressionNet.predictExpressions(n),this.extractedFaces);return mr(e,t)}withAgeAndGender(){return new Ps(this,this.input)}}class cr extends qs{withAgeAndGender(){return new sr(this,this.input)}withFaceDescriptors(){return new hn(this,this.input)}}class pr extends Hs{withAgeAndGender(){return new ar(this,this.input)}withFaceDescriptor(){return new un(this,this.input)}}class Vb extends xt{constructor(e,t,n){super();this.parentTask=e,this.input=t,this.extractedFaces=n}}class Gs extends Vb{async run(){const e=await this.parentTask,t=await wo(e,this.input,async n=>await Promise.all(n.map(o=>re.ageGenderNet.predictAgeAndGender(o))),this.extractedFaces);return e.map((n,o)=>{const{age:r,gender:i,genderProbability:a}=t[o];return gr(dr(n,i,a),r)})}withFaceExpressions(){return new qs(this,this.input)}}class Ps extends Vb{async run(){const e=await this.parentTask;if(!e)return;const{age:t,gender:n,genderProbability:o}=await ir(e,this.input,r=>re.ageGenderNet.predictAgeAndGender(r),this.extractedFaces);return gr(dr(e,n,o),t)}withFaceExpressions(){return new Hs(this,this.input)}}class sr extends Gs{withFaceExpressions(){return new cr(this,this.input)}withFaceDescriptors(){return new hn(this,this.input)}}class ar extends Ps{withFaceExpressions(){return new pr(this,this.input)}withFaceDescriptor(){return new un(this,this.input)}}class la extends xt{constructor(e,t){super();this.parentTask=e,this.input=t}}class hn extends la{async run(){const e=await this.parentTask,t=await wo(e,this.input,n=>Promise.all(n.map(o=>re.faceRecognitionNet.computeFaceDescriptor(o))),null,n=>n.landmarks.align(null,{useDlibAlignment:!0}));return t.map((n,o)=>fr(e[o],n))}withFaceExpressions(){return new cr(this,this.input)}withAgeAndGender(){return new sr(this,this.input)}}class un extends la{async run(){const e=await this.parentTask;if(!e)return;const t=await ir(e,this.input,n=>re.faceRecognitionNet.computeFaceDescriptor(n),null,n=>n.landmarks.align(null,{useDlibAlignment:!0}));return fr(e,t)}withFaceExpressions(){return new pr(this,this.input)}withAgeAndGender(){return new ar(this,this.input)}}class aa extends xt{constructor(e,t,n){super();this.parentTask=e,this.input=t,this.useTinyLandmarkNet=n}get landmarkNet(){return this.useTinyLandmarkNet?re.faceLandmark68TinyNet:re.faceLandmark68Net}}class ca extends aa{async run(){const e=await this.parentTask,t=e.map(r=>r.detection),n=this.input instanceof ee?await Cn(this.input,t):await _n(this.input,t),o=await Promise.all(n.map(r=>this.landmarkNet.detectLandmarks(r)));return n.forEach(r=>r instanceof ee&&r.dispose()),e.map((r,i)=>Rn(r,o[i]))}withFaceExpressions(){return new cr(this,this.input)}withAgeAndGender(){return new sr(this,this.input)}withFaceDescriptors(){return new hn(this,this.input)}}class pa extends aa{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]),o=await this.landmarkNet.detectLandmarks(n[0]);return n.forEach(r=>r instanceof ee&&r.dispose()),Rn(e,o)}withFaceExpressions(){return new pr(this,this.input)}withAgeAndGender(){return new ar(this,this.input)}withFaceDescriptor(){return new un(this,this.input)}}class ia extends xt{constructor(e,t=new bt){super();this.input=e,this.options=t}}class ur extends ia{async run(){const{input:e,options:t}=this,n=t instanceof ea?o=>re.tinyFaceDetector.locateFaces(o,t):t instanceof bt?o=>re.ssdMobilenetv1.locateFaces(o,t):t instanceof Wt?o=>re.tinyYolov2.locateFaces(o,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 ca(this.runAndExtendWithFaceDetections(),this.input,e)}withFaceExpressions(){return new qs(this.runAndExtendWithFaceDetections(),this.input)}withAgeAndGender(){return new Gs(this.runAndExtendWithFaceDetections(),this.input)}}class sa extends ia{async run(){const e=await new ur(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 pa(this.runAndExtendWithFaceDetection(),this.input,e)}withFaceExpressions(){return new Hs(this.runAndExtendWithFaceDetection(),this.input)}withAgeAndGender(){return new Ps(this.runAndExtendWithFaceDetection(),this.input)}}function id(e,t=new bt){return new sa(e,t)}function hr(e,t=new bt){return new ur(e,t)}async function Nc(e,t){return console.warn("allFacesSsdMobilenetv1 is deprecated and will be removed soon, use the high level api instead"),await hr(e,new bt(t?{minConfidence:t}:{})).withFaceLandmarks().withFaceDescriptors()}async function sd(e,t={}){return console.warn("allFacesTinyYolov2 is deprecated and will be removed soon, use the high level api instead"),await hr(e,new Wt(t)).withFaceLandmarks().withFaceDescriptors()}const ad=Nc;function fa(e,t){if(e.length!==t.length)throw new Error("euclideanDistance: arr1.length !== arr2.length");const n=Array.from(e),o=Array.from(t);return Math.sqrt(n.map((r,i)=>r-o[i]).reduce((r,i)=>r+Math.pow(i,2),0))}class Rc{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 o=1;const r=()=>`person ${o++}`;this._labeledDescriptors=n.map(i=>{if(i instanceof xn)return i;if(i instanceof Float32Array)return new xn(r(),[i]);if(i.descriptor&&i.descriptor instanceof Float32Array)return new xn(r(),[i.descriptor]);throw new Error("FaceRecognizer.constructor - expected inputs to be of type LabeledFaceDescriptors | WithFaceDescriptor<any> | Float32Array | Array<LabeledFaceDescriptors | WithFaceDescriptor<any> | Float32Array>")})}get labeledDescriptors(){return this._labeledDescriptors}get distanceThreshold(){return this._distanceThreshold}computeMeanDistance(e,t){return t.map(n=>fa(n,e)).reduce((n,o)=>n+o,0)/(t.length||1)}matchDescriptor(e){return this.labeledDescriptors.map(({descriptors:t,label:n})=>new xr(n,this.computeMeanDistance(e,t))).reduce((t,n)=>t.distance<n.distance?t:n)}findBestMatch(e){const t=this.matchDescriptor(e);return t.distance<this.distanceThreshold?t:new xr("unknown",t.distance)}toJSON(){return{distanceThreshold:this.distanceThreshold,labeledDescriptors:this.labeledDescriptors.map(e=>e.toJSON())}}static fromJSON(e){const t=e.labeledDescriptors.map(n=>xn.fromJSON(n));return new Rc(t,e.distanceThreshold)}}function Wu(e){const t=new Lo;return t.extractWeights(e),t}function Sc(e,t){const{width:n,height:o}=new Qe(t.width,t.height);if(n<=0||o<=0)throw new Error(`resizeResults - invalid dimensions: ${JSON.stringify({width:n,height:o})}`);if(Array.isArray(e))return e.map(r=>Sc(r,{width:n,height:o}));if(dn(e)){const r=e.detection.forSize(n,o),i=e.unshiftedLandmarks.forSize(r.box.width,r.box.height);return Rn(mn(e,r),i)}return Nt(e)?mn(e,e.detection.forSize(n,o)):e instanceof st||e instanceof fe?e.forSize(n,o):e}var Fu="0.4.6";return bd();})();
/**
* @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