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

100 lines
318 KiB
JavaScript

var faceapi=(()=>{var Ts=Object.defineProperty,Nb=Object.prototype.hasOwnProperty,As=Object.assign,St=(e,t)=>()=>(t||(t={exports:{}},e(t.exports,t)),t.exports),ql=e=>Ts(e,"__esModule",{value:!0}),_e=(e,t)=>{ql(e);for(var n in t)Ts(e,n,{get:t[n],enumerable:!0})},Rb=(e,t)=>{if(ql(e),typeof t=="object"||typeof t=="function")for(let n in t)!Nb.call(e,n)&&n!=="default"&&Ts(e,n,{get:()=>t[n],enumerable:!0});return e},zl=e=>e&&e.__esModule?e:Rb(Ts({},"default",{value:e,enumerable:!0}),e);var Yl=St((Hl,uc)=>{(function(e,t,n){function r(s){var c=this,p=a();c.next=function(){var l=2091639*c.s0+c.c*23283064365386963e-26;return c.s0=c.s1,c.s1=c.s2,c.s2=l-(c.c=l|0)},c.c=1,c.s0=p(" "),c.s1=p(" "),c.s2=p(" "),c.s0-=p(s),c.s0<0&&(c.s0+=1),c.s1-=p(s),c.s1<0&&(c.s1+=1),c.s2-=p(s),c.s2<0&&(c.s2+=1),p=null}function o(s,c){return c.c=s.c,c.s0=s.s0,c.s1=s.s1,c.s2=s.s2,c}function i(s,c){var p=new r(s),l=c&&c.state,h=p.next;return h.int32=function(){return p.next()*4294967296|0},h.double=function(){return h()+(h()*2097152|0)*11102230246251565e-32},h.quick=h,l&&(typeof l=="object"&&o(l,p),h.state=function(){return o(p,{})}),h}function a(){var s=4022871197,c=function(p){p=p.toString();for(var l=0;l<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})(Hl,typeof uc=="object"&&uc,typeof define=="function"&&define)});var Kl=St((Vl,dc)=>{(function(e,t,n){function r(a){var s=this,c="";s.x=0,s.y=0,s.z=0,s.w=0,s.next=function(){var l=s.x^s.x<<11;return s.x=s.y,s.y=s.z,s.z=s.w,s.w^=s.w>>>19^l^l>>>8},a===(a|0)?s.x=a:c+=a;for(var p=0;p<c.length+64;p++)s.x^=c.charCodeAt(p)|0,s.next()}function o(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 r(a),p=s&&s.state,l=function(){return(c.next()>>>0)/4294967296};return l.double=function(){do var h=c.next()>>>11,d=(c.next()>>>0)/4294967296,g=(h+d)/(1<<21);while(g===0);return g},l.int32=c.next,l.quick=l,p&&(typeof p=="object"&&o(p,c),l.state=function(){return o(c,{})}),l}t&&t.exports?t.exports=i:n&&n.amd?n(function(){return i}):this.xor128=i})(Vl,typeof dc=="object"&&dc,typeof define=="function"&&define)});var Xl=St((Jl,mc)=>{(function(e,t,n){function r(a){var s=this,c="";s.next=function(){var l=s.x^s.x>>>2;return s.x=s.y,s.y=s.z,s.z=s.w,s.w=s.v,(s.d=s.d+362437|0)+(s.v=s.v^s.v<<4^(l^l<<1))|0},s.x=0,s.y=0,s.z=0,s.w=0,s.v=0,a===(a|0)?s.x=a:c+=a;for(var p=0;p<c.length+64;p++)s.x^=c.charCodeAt(p)|0,p==c.length&&(s.d=s.x<<10^s.x>>>4),s.next()}function o(a,s){return s.x=a.x,s.y=a.y,s.z=a.z,s.w=a.w,s.v=a.v,s.d=a.d,s}function i(a,s){var c=new r(a),p=s&&s.state,l=function(){return(c.next()>>>0)/4294967296};return l.double=function(){do var h=c.next()>>>11,d=(c.next()>>>0)/4294967296,g=(h+d)/(1<<21);while(g===0);return g},l.int32=c.next,l.quick=l,p&&(typeof p=="object"&&o(p,c),l.state=function(){return o(c,{})}),l}t&&t.exports?t.exports=i:n&&n.amd?n(function(){return i}):this.xorwow=i})(Jl,typeof mc=="object"&&mc,typeof define=="function"&&define)});var Ql=St((Zl,fc)=>{(function(e,t,n){function r(a){var s=this;s.next=function(){var p=s.x,l=s.i,h,d,g;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,g=[];if(l===(l|0))d=g[0]=l;else for(l=""+l,h=0;h<l.length;++h)g[h&7]=g[h&7]<<15^l.charCodeAt(h)+g[h+1&7]<<13;for(;g.length<8;)g.push(0);for(h=0;h<8&&g[h]===0;++h);for(h==8?d=g[7]=-1:d=g[h],p.x=g,p.i=0,h=256;h>0;--h)p.next()}c(s,a)}function o(a,s){return s.x=a.x.slice(),s.i=a.i,s}function i(a,s){a==null&&(a=+new Date);var c=new r(a),p=s&&s.state,l=function(){return(c.next()>>>0)/4294967296};return l.double=function(){do var h=c.next()>>>11,d=(c.next()>>>0)/4294967296,g=(h+d)/(1<<21);while(g===0);return g},l.int32=c.next,l.quick=l,p&&(p.x&&o(p,c),l.state=function(){return o(c,{})}),l}t&&t.exports?t.exports=i:n&&n.amd?n(function(){return i}):this.xorshift7=i})(Zl,typeof fc=="object"&&fc,typeof define=="function"&&define)});var th=St((eh,gc)=>{(function(e,t,n){function r(a){var s=this;s.next=function(){var p=s.w,l=s.X,h=s.i,d,g;return s.w=p=p+1640531527|0,g=l[h+34&127],d=l[h=h+1&127],g^=g<<13,d^=d<<17,g^=g>>>15,d^=d>>>12,g=l[h]=g^d,s.i=h,g+(p^p>>>16)|0};function c(p,l){var h,d,g,x,w,L=[],S=128;for(l===(l|0)?(d=l,l=null):(l=l+"\0",d=0,S=Math.max(S,l.length)),g=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,g=h==0?g+1:0);for(g>=128&&(L[(l&&l.length||0)&127]=-1),g=127,x=4*128;x>0;--x)d=L[g+34&127],h=L[g=g+1&127],d^=d<<13,h^=h<<17,d^=d>>>15,h^=h>>>12,L[g]=d^h;p.w=w,p.X=L,p.i=g}c(s,a)}function o(a,s){return s.i=a.i,s.w=a.w,s.X=a.X.slice(),s}function i(a,s){a==null&&(a=+new Date);var c=new r(a),p=s&&s.state,l=function(){return(c.next()>>>0)/4294967296};return l.double=function(){do var h=c.next()>>>11,d=(c.next()>>>0)/4294967296,g=(h+d)/(1<<21);while(g===0);return g},l.int32=c.next,l.quick=l,p&&(p.X&&o(p,c),l.state=function(){return o(c,{})}),l}t&&t.exports?t.exports=i:n&&n.amd?n(function(){return i}):this.xor4096=i})(eh,typeof gc=="object"&&gc,typeof define=="function"&&define)});var rh=St((nh,bc)=>{(function(e,t,n){function r(a){var s=this,c="";s.next=function(){var l=s.b,h=s.c,d=s.d,g=s.a;return l=l<<25^l>>>7^h,h=h-d|0,d=d<<24^d>>>8^g,g=g-l|0,s.b=l=l<<20^l>>>12^h,s.c=h=h-d|0,s.d=d<<16^h>>>16^g,s.a=g-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 o(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 r(a),p=s&&s.state,l=function(){return(c.next()>>>0)/4294967296};return l.double=function(){do var h=c.next()>>>11,d=(c.next()>>>0)/4294967296,g=(h+d)/(1<<21);while(g===0);return g},l.int32=c.next,l.quick=l,p&&(typeof p=="object"&&o(p,c),l.state=function(){return o(c,{})}),l}t&&t.exports?t.exports=i:n&&n.amd?n(function(){return i}):this.tychei=i})(nh,typeof bc=="object"&&bc,typeof define=="function"&&define)});var oh=St(()=>{});var ih=St((WT,Ns)=>{(function(e,t){var n=this,r=256,o=6,i=52,a="random",s=t.pow(r,o),c=t.pow(2,i),p=c*2,l=r-1,h;function d(R,A,E){var F=[];A=A==!0?{entropy:!0}:A||{};var M=L(w(A.entropy?[R,I(e)]:R==null?S():R,3),F),j=new g(F),$=function(){for(var U=j.g(o),Q=s,ne=0;U<c;)U=(U+ne)*r,Q*=r,ne=j.g(1);for(;U>=p;)U/=2,Q/=2,ne>>>=1;return(U+ne)/Q};return $.int32=function(){return j.g(4)|0},$.quick=function(){return j.g(4)/4294967296},$.double=$,L(I(j.S),e),(A.pass||E||function(U,Q,ne,he){return he&&(he.S&&x(he,j),U.state=function(){return x(j,{})}),ne?(t[a]=U,Q):U})($,M,"global"in A?A.global:this==t,A.state)}t["seed"+a]=d;function g(R){var A,E=R.length,F=this,M=0,j=F.i=F.j=0,$=F.S=[];for(E||(R=[E++]);M<r;)$[M]=M++;for(M=0;M<r;M++)$[M]=$[j=l&j+R[M%E]+(A=$[M])],$[j]=A;(F.g=function(U){for(var Q,ne=0,he=F.i,xe=F.j,Ue=F.S;U--;)Q=Ue[he=l&he+1],ne=ne*r+Ue[l&(Ue[he]=Ue[xe=l&xe+Q])+(Ue[xe]=Q)];return F.i=he,F.j=xe,ne})(r)}function x(R,A){return A.i=R.i,A.j=R.j,A.S=R.S.slice(),A}function w(R,A){var E=[],F=typeof R,M;if(A&&F=="object")for(M in R)try{E.push(w(R[M],A-1))}catch(j){}return E.length?E:F=="string"?R:R+"\0"}function L(R,A){for(var E=R+"",F,M=0;M<E.length;)A[l&M]=l&(F^=A[l&M]*19)+E.charCodeAt(M++);return I(A)}function S(){try{var R;return h&&(R=h.randomBytes)?R=R(r):(R=new Uint8Array(r),(n.crypto||n.msCrypto).getRandomValues(R)),I(R)}catch(F){var A=n.navigator,E=A&&A.plugins;return[+new Date,n,E,n.screen,I(e)]}}function I(R){return String.fromCharCode.apply(0,R)}if(L(t.random(),e),typeof Ns=="object"&&Ns.exports){Ns.exports=d;try{h=oh()}catch(R){}}else typeof define=="function"&&define.amd&&define(function(){return d})})([],Math)});var ah=St((BT,sh)=>{var _b=Yl(),Cb=Kl(),Eb=Xl(),Ob=Ql(),kb=th(),Db=rh(),Sn=ih();Sn.alea=_b;Sn.xor128=Cb;Sn.xorwow=Eb;Sn.xorshift7=Ob;Sn.xor4096=kb;Sn.tychei=Db;sh.exports=Sn});var ph=St((Fb,ch)=>{_e(Fb,{isNodejs:()=>Mb});function Mb(){return typeof global=="object"&&!0&&typeof ch!="undefined"&&typeof process!="undefined"&&!!process.version}});var Hh=St(Ub=>{_e(Ub,{AgeGenderNet:()=>ta,BoundingBox:()=>hr,Box:()=>de,ComposableTask:()=>ut,ComputeAllFaceDescriptorsTask:()=>an,ComputeFaceDescriptorsTaskBase:()=>Ps,ComputeSingleFaceDescriptorTask:()=>cn,DetectAllFaceLandmarksTask:()=>js,DetectAllFacesTask:()=>ro,DetectFaceLandmarksTaskBase:()=>$s,DetectFacesTaskBase:()=>Ws,DetectSingleFaceLandmarksTask:()=>Gs,DetectSingleFaceTask:()=>Bs,Dimensions:()=>Ke,FACE_EXPRESSION_LABELS:()=>Hs,FaceDetection:()=>me,FaceDetectionNet:()=>fh,FaceExpressionNet:()=>Ys,FaceExpressions:()=>hn,FaceLandmark68Net:()=>sr,FaceLandmark68TinyNet:()=>zs,FaceLandmarkNet:()=>$h,FaceLandmarks:()=>st,FaceLandmarks5:()=>zh,FaceLandmarks68:()=>lr,FaceMatch:()=>lo,FaceMatcher:()=>Ac,FaceRecognitionNet:()=>ir,Gender:()=>Dt,LabeledBox:()=>po,LabeledFaceDescriptors:()=>fn,NetInput:()=>Vt,NeuralNetwork:()=>We,ObjectDetection:()=>_n,Point:()=>J,PredictedBox:()=>qh,Rect:()=>pr,SsdMobilenetv1:()=>In,SsdMobilenetv1Options:()=>lt,TinyFaceDetector:()=>rr,TinyFaceDetectorOptions:()=>ks,TinyYolov2:()=>nr,TinyYolov2Options:()=>kt,TinyYolov2SizeType:()=>Os,allFaces:()=>Mh,allFacesSsdMobilenetv1:()=>Tc,allFacesTinyYolov2:()=>Fh,awaitMediaLoaded:()=>ea,bufferToImage:()=>Qs,computeFaceDescriptor:()=>Lh,createCanvas:()=>Rn,createCanvasFromMedia:()=>cr,createFaceDetectionNet:()=>mh,createFaceRecognitionNet:()=>Bh,createSsdMobilenetv1:()=>yc,createTinyFaceDetector:()=>dh,createTinyYolov2:()=>uh,detectAllFaces:()=>no,detectFaceLandmarks:()=>Sc,detectFaceLandmarksTiny:()=>yh,detectLandmarks:()=>kh,detectSingleFace:()=>Dh,draw:()=>_s,env:()=>se,euclideanDistance:()=>Vs,extendWithAge:()=>ao,extendWithFaceDescriptor:()=>so,extendWithFaceDetection:()=>ln,extendWithFaceExpressions:()=>io,extendWithFaceLandmarks:()=>Tn,extendWithGender:()=>oo,extractFaceTensors:()=>Nn,extractFaces:()=>An,fetchImage:()=>Ph,fetchJson:()=>Zs,fetchNetWeights:()=>Gh,fetchOrThrow:()=>mn,getContext2dOrThrow:()=>Ge,getMediaDimensions:()=>dn,imageTensorToCanvas:()=>Xs,imageToSquare:()=>Js,inverseSigmoid:()=>bh,iou:()=>Us,isMediaElement:()=>co,isMediaLoaded:()=>ar,isWithAge:()=>Wh,isWithFaceDetection:()=>It,isWithFaceExpressions:()=>qs,isWithFaceLandmarks:()=>pn,isWithGender:()=>Uh,loadAgeGenderModel:()=>Ch,loadFaceDetectionModel:()=>Eh,loadFaceExpressionModel:()=>_h,loadFaceLandmarkModel:()=>Ah,loadFaceLandmarkTinyModel:()=>Nh,loadFaceRecognitionModel:()=>Rh,loadSsdMobilenetv1Model:()=>Ic,loadTinyFaceDetectorModel:()=>Ih,loadTinyYolov2Model:()=>Th,loadWeightMap:()=>Ks,locateFaces:()=>Oh,matchDimensions:()=>jh,minBbox:()=>Ms,nets:()=>oe,nonMaxSuppression:()=>Fs,normalize:()=>ht,padToSquare:()=>Ds,predictAgeAndGender:()=>Sh,recognizeFaceExpressions:()=>vh,resizeResults:()=>Lc,resolveInput:()=>un,shuffleArray:()=>gh,sigmoid:()=>or,ssdMobilenetv1:()=>vc,tf:()=>Rs,tinyFaceDetector:()=>wh,tinyYolov2:()=>xh,toNetInput:()=>ue,utils:()=>Cs,validateConfig:()=>Es,version:()=>hh});const Wb=typeof process!="undefined"?process.version:!1,Bb=typeof navigator!="undefined"?navigator.userAgent:!1,hh={faceapi:lh,node:Wb,browser:Bb,tfjs:xc,backend:wc()}});const Yh="tfjsflags";class Nc{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.populateURLFlags()}setPlatform(e,t){this.platform!=null&&console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${t}.`),this.platformName=e,this.platform=t}registerFlag(e,t,n){if(this.flagRegistry[e]={evaluationFn:t,setHook:n},this.urlFlags[e]!=null){const r=this.urlFlags[e];console.warn(`Setting feature override from URL ${e}: ${r}.`),this.set(e,r)}}async getAsync(e){return e in this.flags?this.flags[e]:(this.flags[e]=await this.evaluateFlag(e),this.flags[e])}get(e){if(e in this.flags)return this.flags[e];const t=this.evaluateFlag(e);if(t instanceof Promise)throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[e]=t,this.flags[e]}getNumber(e){return this.get(e)}getBool(e){return this.get(e)}getFlags(){return this.flags}get features(){return this.flags}set(e,t){if(this.flagRegistry[e]==null)throw new Error(`Cannot set flag ${e} as it has not been registered.`);this.flags[e]=t,this.flagRegistry[e].setHook!=null&&this.flagRegistry[e].setHook(t)}evaluateFlag(e){if(this.flagRegistry[e]==null)throw new Error(`Cannot evaluate flag '${e}': no evaluation function found.`);return this.flagRegistry[e].evaluationFn()}setFlags(e){this.flags=Object.assign({},e)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if(typeof this.global=="undefined"||typeof this.global.location=="undefined"||typeof this.global.location.search=="undefined")return;const e=$b(this.global.location.search);if(Yh in e){const t=e[Yh].split(",");t.forEach(n=>{const[r,o]=n.split(":");this.urlFlags[r]=jb(r,o)})}}}function $b(e){const t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(n,...r)=>(Gb(t,r[0],r[1]),r.join("="))),t}function Gb(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}function jb(e,t){if(t=t.toLowerCase(),t==="true"||t==="false")return t==="true";if(`${+t}`===t)return+t;throw new Error(`Could not parse value flag value ${t} for flag ${e}.`)}function pe(){return Rc}let Rc=null;function Vh(e){Rc=e}let _c;function Cc(){if(_c==null){let e;if(typeof window!="undefined")e=window;else if(typeof global!="undefined")e=global;else if(typeof process!="undefined")e=process;else if(typeof self!="undefined")e=self;else throw new Error("Could not find a global object");_c=e}return _c}function Pb(){const e=Cc();return e._tfGlobals==null&&(e._tfGlobals=new Map),e._tfGlobals}function Ec(e,t){const n=Pb();if(n.has(e))return n.get(e);{const r=t();return n.set(e,r),n.get(e)}}const ho="Abs",uo="Acos",mo="Acosh",Cn="Add",fo="AddN",Oc="All",kc="Any",go="ArgMax",bo="ArgMin",wo="Asin",xo="Asinh",yo="Atan",Lo="Atanh",vo="Atan2",So="AvgPool",Dc="AvgPoolBackprop",Io="AvgPool3D",Fc="AvgPool3DBackprop",To="BatchMatMul",Ao="BatchToSpaceND",No="BroadcastTo",En="Cast",Ro="Ceil",_o="ClipByValue",Mc="Complex",Co="Concat",Eo="Conv2D",Uc="Conv2DBackpropFilter",Oo="Conv2DBackpropInput",ko="Conv3D",Wc="Conv3DBackpropFilterV2",Bc="Conv3DBackpropInputV2",Do="Cos",Fo="Cosh",Mo="Cumsum",$c="CropAndResize",jc="DepthToSpace",Uo="DepthwiseConv2dNative",Gc="DepthwiseConv2dNativeBackpropFilter",Pc="DepthwiseConv2dNativeBackpropInput",qc="Diag",Wo="Dilation2D",zc="Dilation2DBackpropInput",Hc="Dilation2DBackpropFilter",Bo="Div",$o="Elu",Yc="EluGrad",jo="Erf",Vc="Equal",Go="Exp",Po="Expm1",Kc="FFT",Jc="Fill",Xc="FlipLeftRight",qo="Floor",zo="FloorDiv",Ho="FusedBatchNorm",Yo="GatherV2",Zc="GatherNd",Qc="Greater",Vo="GreaterEqual",Ko="Identity",ep="IFFT",tp="Imag",Jo="IsFinite",Xo="IsInf",Zo="IsNan",np="Less",rp="LessEqual",op="LinSpace",Qo="Log",ei="Log1p",ip="LogicalAnd",sp="LogicalNot",ap="LogicalOr",ti="LogSoftmax",ni="LRN",cp="LRNBackprop",ri="Max",oi="Maximum",ii="MaxPool",pp="MaxPoolBackprop",si="MaxPool3D",lp="MaxPool3DBackprop",hp="MaxPoolWithArgmax",qb="Mean",ai="Min",ci="Minimum",pi="Mod",li="Multiply",hi="Negate",up="NotEqual",dp="NonMaxSuppressionV3",mp="NonMaxSuppressionV4",fp="NonMaxSuppressionV5",ui="OnesLike",di="OneHot",mi="PadV2",zb="Pool",fi="Pow",gi="Prelu",gp="Prod",bp="Range",wp="Real",bi="Reciprocal",wi="Relu",xi="Reshape",yi="ResizeNearestNeighbor",xp="ResizeNearestNeighborGrad",Li="ResizeBilinear",yp="ResizeBilinearGrad",vi="Relu6",Si="Reverse",Ii="Round",Ti="Rsqrt",Lp="ScatterNd",Ai="SelectV2",Ni="Selu",Ri="Slice",_i="Sin",Ci="Sinh",Ei="Sign",Oi="Sigmoid",ki="Softplus",Di="Sqrt",Fi="Sum",Mi="SpaceToBatchND",Ui="SplitV",Wi="Softmax",Bi="SquaredDifference",vp="Square",$i="Sub",Sp="SparseToDense",Ip="StridedSlice",ji="Tan",Gi="Tanh",Pi="Tile",Tp="TopK",qi="Transpose",zi="Unpack",Hi="UnsortedSegmentSum",Yi="ZerosLike",Vi="Step",na="FromPixels",Ap="RotateWithOffset",ra="_FusedMatMul",oa="FusedConv2D",ia="FusedDepthwiseConv2D";const ur=Ec("kernelRegistry",()=>new Map),Ki=Ec("gradRegistry",()=>new Map);function Ji(e,t){const n=Np(e,t);return ur.get(n)}function sa(e){return Ki.get(e)}function aa(e){const t=ur.entries(),n=[];for(;;){const{done:r,value:o}=t.next();if(r)break;const[i,a]=o,[s]=i.split("_");s===e&&n.push(a)}return n}function Hb(e){const{kernelName:t,backendName:n}=e,r=Np(t,n);ur.has(r)&&console.warn(`The kernel '${t}' for backend '${n}' is already registered`),ur.set(r,e)}function Rp(e){const{kernelName:t}=e;Ki.has(t)&&(pe().getBool("DEBUG")&&console.warn(`Overriding the gradient for '${t}'`)),Ki.set(t,e)}function Yb(e,t){const n=Np(e,t);if(!ur.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);ur.delete(n)}function Vb(e){if(!Ki.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);Ki.delete(e)}function Np(e,t){return`${t}_${e}`}const Kh={};_e(Kh,{arraysEqual:()=>Se,assert:()=>f,assertNonNegativeIntegerDimensions:()=>Qi,assertNonNull:()=>at,assertShapesMatch:()=>G,bytesFromStringArray:()=>Fp,bytesPerElement:()=>Dp,checkConversionForErrors:()=>Xh,clamp:()=>dr,computeStrides:()=>Ut,createShuffledIndices:()=>nw,decodeString:()=>pa,distSquared:()=>Zb,encodeString:()=>Mp,fetch:()=>sw,flatten:()=>Ft,getArrayFromDType:()=>Ep,getTypedArrayFromDType:()=>mr,hasEncodingLoss:()=>kp,indexToLoc:()=>cw,inferDtype:()=>fr,inferFromImplicitShape:()=>_p,isBoolean:()=>Zh,isFunction:()=>Mt,isInt:()=>X,isNumber:()=>Qh,isScalarShape:()=>Qb,isString:()=>Tt,isTypedArray:()=>Ne,isValidDtype:()=>Op,locToIndex:()=>aw,makeOnesTypedArray:()=>Zi,makeZerosNestedTypedArray:()=>iw,makeZerosTypedArray:()=>Wt,nearestDivisor:()=>gr,nearestLargerEven:()=>Kb,now:()=>ca,parseAxisParam:()=>H,randUniform:()=>Xb,repeatedTry:()=>rw,rightPad:()=>On,shuffle:()=>Jh,sizeFromShape:()=>ee,sizeToSquarishShape:()=>tw,squeezeShape:()=>Cp,sum:()=>Jb,tanh:()=>ew,toNestedArray:()=>kn,toTypedArray:()=>Xi});function Jh(e){let t=e.length,n=0,r=0;for(;t>0;)r=Math.random()*t|0,t--,n=e[t],e[t]=e[r],e[r]=n}function dr(e,t,n){return Math.max(e,Math.min(t,n))}function Kb(e){return e%2===0?e:e+1}function Jb(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t}function Xb(e,t){const n=Math.random();return t*n+(1-n)*e}function Zb(e,t){let n=0;for(let r=0;r<e.length;r++){const o=Number(e[r])-Number(t[r]);n+=o*o}return n}function f(e,t){if(!e)throw new Error(typeof t=="string"?t:t())}function G(e,t,n=""){f(Se(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 Ft(e,t=[],n=!1){if(t==null&&(t=[]),Array.isArray(e)||Ne(e)&&!n)for(let r=0;r<e.length;++r)Ft(e[r],t,n);else t.push(e);return t}function ee(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 Qb(e){return e.length===0}function Se(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 ew(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 tw(e){const t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function nw(e){const t=new Uint32Array(e);for(let n=0;n<e;++n)t[n]=n;return Jh(t),t}function On(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function rw(e,t=r=>0,n){return new Promise((r,o)=>{let i=0;const a=()=>{if(e()){r();return}i++;const s=t(i);if(n!=null&&i>=n){o();return}setTimeout(a,s)};a()})}function _p(e,t){let n=1,r=-1;for(let i=0;i<e.length;++i)if(e[i]>=0)n*=e[i];else if(e[i]===-1){if(r!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${r} and dim ${i}`);r=i}else if(e[i]<0)throw Error(`Shapes can not be < 0. Found ${e[i]} at dim ${i}`);if(r===-1){if(t>0&&t!==n)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(n===0)throw Error(`Cannot infer the missing size in [${e}] when there are 0 elements`);if(t%n!==0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${n}`);const o=e.slice();return o[r]=t/n,o}function H(e,t){const n=t.length;return e=e==null?t.map((r,o)=>o):[].concat(e),f(e.every(r=>r>=-n&&r<n),()=>`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`),f(e.every(r=>X(r)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(r=>r<0?n+r:r)}function Cp(e,t){const n=[],r=[],o=t!=null&&Array.isArray(t)&&t.length===0,i=t==null||o?null:H(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]),r.push(s)),i[a]<=s&&a++}e[s]!==1&&(n.push(e[s]),r.push(s))}return{newShape:n,keptDims:r}}function mr(e,t){let n=null;if(e==null||e==="float32")n=new Float32Array(t);else if(e==="int32")n=new Int32Array(t);else if(e==="bool")n=new Uint8Array(t);else throw new Error(`Unknown data type ${e}`);return n}function Ep(e,t){let n=null;if(e==null||e==="float32")n=new Float32Array(t);else if(e==="int32")n=new Int32Array(t);else if(e==="bool")n=new Uint8Array(t);else if(e==="string")n=new Array(t);else throw new Error(`Unknown data type ${e}`);return n}function Xh(e,t){for(let n=0;n<e.length;n++){const r=e[n];if(isNaN(r)||!isFinite(r))throw Error(`A tensor of type ${t} being uploaded contains ${r}.`)}}function Op(e){return e==="bool"||e==="complex64"||e==="float32"||e==="int32"||e==="string"}function kp(e,t){return t==="complex64"||(t==="float32"&&e!=="complex64"||t==="int32"&&e!=="float32"&&e!=="complex64")?!1:!(t==="bool"&&e==="bool")}function Ne(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array}function Dp(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 Fp(e){if(e==null)return 0;let t=0;return e.forEach(n=>t+=n.length),t}function Tt(e){return typeof e=="string"||e instanceof String}function Zh(e){return typeof e=="boolean"}function Qh(e){return typeof e=="number"}function fr(e){return Array.isArray(e)?fr(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array?"int32":Qh(e)?"float32":Tt(e)?"string":Zh(e)?"bool":"float32"}function Mt(e){return!!(e&&e.constructor&&e.call&&e.apply)}function gr(e,t){for(let n=t;n<e;++n)if(e%n===0)return n;return e}function Ut(e){const t=e.length;if(t<2)return[];const n=new Array(t-1);n[t-2]=e[t-1];for(let r=t-3;r>=0;--r)n[r]=n[r+1]*e[r+1];return n}function Xi(e,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=Ft(e)),pe().getBool("DEBUG")&&Xh(e,t),ow(e,t))return e;if(t==null||t==="float32"||t==="complex64")return new Float32Array(e);if(t==="int32")return new Int32Array(e);if(t==="bool"){const n=new Uint8Array(e.length);for(let r=0;r<n.length;++r)Math.round(e[r])!==0&&(n[r]=1);return n}else throw new Error(`Unknown data type ${t}`)}function eu(e,t,n){const r=new Array;if(t.length===1){const o=t[0];for(let i=0;i<o;i++)r[i]=n[e+i]}else{const o=t[0],i=t.slice(1),a=i.reduce((s,c)=>s*c);for(let s=0;s<o;s++)r[s]=eu(e+s*a,i,n)}return r}function kn(e,t){if(e.length===0)return t[0];const n=e.reduce((r,o)=>r*o);if(n===0)return[];if(n!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}.`);return eu(0,e,t)}function ow(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function Zi(e,t){const n=Wt(e,t);for(let r=0;r<n.length;r++)n[r]=1;return n}function Wt(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 iw(e,t){const n=e.reduce((r,o)=>r*o,1);if(t==null||t==="float32")return kn(e,new Float32Array(n));if(t==="int32")return kn(e,new Int32Array(n));if(t==="bool")return kn(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function ca(){return pe().platform.now()}function Qi(e){e.forEach(t=>{f(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function sw(e,t){return pe().platform.fetch(e,t)}function Mp(e,t="utf-8"){return t=t||"utf-8",pe().platform.encode(e,t)}function pa(e,t="utf-8"){return t=t||"utf-8",pe().platform.decode(e,t)}function aw(e,t,n){if(t===0)return 0;if(t===1)return e[0];let r=e[e.length-1];for(let o=0;o<e.length-1;++o)r+=n[o]*e[o];return r}function cw(e,t,n){if(t===0)return[];if(t===1)return[e];const r=new Array(t);for(let o=0;o<r.length-1;++o)r[o]=Math.floor(e/n[o]),e-=r[o]*n[o];return r[r.length-1]=e,r}class tu{constructor(e,t){this.backendTimer=e,this.logger=t,t==null&&(this.logger=new lw)}profileKernel(e,t,n){let r;const o=()=>{r=n()},i=this.backendTimer.time(o);for(let s=0;s<r.length;s++){const c=r[s];c.data().then(p=>{pw(p,c.dtype,e)})}const a={kernelName:e,outputs:r,inputs:t,timeMs:i.then(s=>s.kernelMs),extraInfo:i.then(s=>s.getExtraProfileInfo!=null?s.getExtraProfileInfo():"")};return a}logKernelProfile(e){const{kernelName:t,outputs:n,timeMs:r,inputs:o,extraInfo:i}=e;n.forEach(a=>{Promise.all([a.data(),r,i]).then(s=>{this.logger.logKernelProfile(t,a,s[0],s[1],o,s[2])})})}}function pw(e,t,n){if(t!=="float32")return!1;for(let r=0;r<e.length;r++){const o=e[r];if(isNaN(o)||!isFinite(o))return console.warn(`Found ${o} in the result of '${n}'`),!0}return!1}class lw{logKernelProfile(e,t,n,r,o,i){const a=typeof r=="number"?On(`${r}ms`,9):r.error,s=On(e,25),c=t.rank,p=t.size,l=On(t.shape.toString(),14);let h="";for(const d in o){const g=o[d];if(g!=null){const x=g.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 nu(e,t,n){const r={},o={};for(let c=0;c<t.length;c++)r[t[c].id]=!0;for(let c=0;c<e.length;c++){const p=e[c],l=p.inputs;for(const h in l){const d=l[h];let g=!1;for(let x=0;x<t.length;x++)if(r[d.id]){p.outputs.forEach(w=>r[w.id]=!0),g=!0,o[p.id]=!0;break}if(g)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(o[p.id]&&a[p.id]){const l={};for(const d in p.inputs){const g=p.inputs[d];r[g.id]&&(l[d]=g)}const h=Object.assign({},p);h.inputs=l,h.outputs=p.outputs,s.push(h)}}return s}function ru(e,t,n,r){for(let o=t.length-1;o>=0;o--){const i=t[o],a=[];if(i.outputs.forEach(c=>{const p=e[c.id];p!=null?a.push(p):a.push(null)}),i.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${i.kernelName}.`);const s=i.gradient(a);for(const c in i.inputs){if(!(c in s))throw new Error(`Cannot backprop through input ${c}. Available gradients found: ${Object.keys(s)}.`);const p=n(()=>s[c]());if(p.dtype!=="float32")throw new Error(`Error in gradient for op ${i.kernelName}. The gradient of input ${c} must have 'float32' dtype, but has '${p.dtype}'`);const l=i.inputs[c];if(!Se(p.shape,l.shape))throw new Error(`Error in gradient for op ${i.kernelName}. The gradient of input '${c}' has shape '${p.shape}', which does not match the shape of the input '${l.shape}'`);if(e[l.id]==null)e[l.id]=p;else{const h=e[l.id];e[l.id]=r(h,p),h.dispose()}}}}const ou=20,es=3,Up=7;function iu(e,t,n,r){const o=Ut(t),i=hw(e,t,n,o),a=t.length,s=la(e,t,n,o,i),c=["Tensor"];return r&&(c.push(` dtype: ${n}`),c.push(` rank: ${a}`),c.push(` shape: [${t}]`),c.push(" values:")),c.push(s.map(p=>" "+p).join(`
`)),c.join(`
`)}function hw(e,t,n,r){const o=ee(t),i=r[r.length-1],a=new Array(i).fill(0),s=t.length,c=n==="complex64"?ns(e):e;if(s>1)for(let p=0;p<o/i;p++){const l=p*i;for(let h=0;h<i;h++)a[h]=Math.max(a[h],ts(c[l+h],0,n).length)}return a}function ts(e,t,n){let r;return Array.isArray(e)?r=`${parseFloat(e[0].toFixed(Up))} + ${parseFloat(e[1].toFixed(Up))}j`:Tt(e)?r=`'${e}'`:n==="bool"?r=su(e):r=parseFloat(e.toFixed(Up)).toString(),On(r,t)}function su(e){return e===0?"false":"true"}function la(e,t,n,r,o,i=!0){const a=n==="complex64"?2:1,s=t[0],c=t.length;if(c===0){if(n==="complex64"){const w=ns(e);return[ts(w[0],0,n)]}return n==="bool"?[su(e[0])]:[e[0].toString()]}if(c===1){if(s>ou){const L=es*a;let S=Array.from(e.slice(0,L)),I=Array.from(e.slice((s-es)*a,s*a));return n==="complex64"&&(S=ns(S),I=ns(I)),["["+S.map((R,A)=>ts(R,o[A],n)).join(", ")+", ..., "+I.map((R,A)=>ts(R,o[s-es+A],n)).join(", ")+"]"]}const w=n==="complex64"?ns(e):Array.from(e);return["["+w.map((L,S)=>ts(L,o[S],n)).join(", ")+"]"]}const p=t.slice(1),l=r.slice(1),h=r[0]*a,d=[];if(s>ou){for(let w=0;w<es;w++){const L=w*h,S=L+h;d.push(...la(e.slice(L,S),p,n,l,o,!1))}d.push("...");for(let w=s-es;w<s;w++){const L=w*h,S=L+h;d.push(...la(e.slice(L,S),p,n,l,o,w===s-1))}}else for(let w=0;w<s;w++){const L=w*h,S=L+h;d.push(...la(e.slice(L,S),p,n,l,o,w===s-1))}const g=c===2?",":"";d[0]="["+d[0]+g;for(let w=1;w<d.length-1;w++)d[w]=" "+d[w]+g;let x=`,
`;for(let w=2;w<c;w++)x+=`
`;return d[d.length-1]=" "+d[d.length-1]+"]"+(i?"":x),d}function ns(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}class br{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=ee(e),n!=null){const r=n.length;f(r===this.size,()=>`Length of values '${r}' does not match the size inferred by the shape '${this.size}'.`)}if(t==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||Ep(t,this.size),this.strides=Ut(e)}set(e,...t){t.length===0&&(t=[0]),f(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);const n=this.locToIndex(t);this.values[n]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(const r of e){if(r<0||r>=this.shape[t]){const o=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(o)}t++}let n=e[e.length-1];for(let r=0;r<e.length-1;++r)n+=this.strides[r]*e[r];return this.values[n]}locToIndex(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];let t=e[e.length-1];for(let n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t}indexToLoc(e){if(this.rank===0)return[];if(this.rank===1)return[e];const t=new Array(this.shape.length);for(let n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return Bt().makeTensor(this.values,this.shape,this.dtype)}}let Bt=null,wr=null,uw=null;function au(e){Bt=e}function cu(e){wr=e}function pu(e){uw=e}class te{constructor(e,t,n,r){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=ee(e),this.strides=Ut(e),this.dataId=n,this.id=r,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){const e=await this.data();return wr.buffer(this.shape,this.dtype,e)}bufferSync(){return wr.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return kn(this.shape,e)}arraySync(){return kn(this.shape,this.dataSync())}async data(){this.throwIfDisposed();const e=Bt().read(this.dataId);if(this.dtype==="string"){const t=await e;try{return t.map(n=>pa(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=Bt().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>pa(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 Bt().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){if(this.isDisposed)return;Bt().disposeTensor(this),this.isDisposedInternal=!0}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return wr.print(this,e)}clone(){return this.throwIfDisposed(),wr.clone(this)}toString(e=!1){const t=this.dataSync();return iu(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),wr.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Bt().makeVariable(this,e,t,n)}}Object.defineProperty(te,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});class $t extends te{constructor(e,t,n,r){super(e.shape,e.dtype,e.dataId,r);this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!Se(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Bt().disposeTensor(this),this.dataId=e.dataId,Bt().incRef(this,null)}dispose(){Bt().disposeVariable(this),this.isDisposedInternal=!0}}Object.defineProperty($t,Symbol.hasInstance,{value:e=>e instanceof te&&e.assign!=null&&e.assign instanceof Function});var Wp;(function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"})(Wp||(Wp={}));var Bp;(function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"})(Bp||(Bp={}));var $p;(function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"})($p||($p={}));var jp;(function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"})(jp||(jp={}));var Gp;(function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"})(Gp||(Gp={}));const dw={float32:jp,int32:Bp,bool:$p,complex64:Gp};function xr(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 mw(e){return xr(e,"int32")}const lu={};_e(lu,{assertTypesMatch:()=>Pp,getTensorsInContainer:()=>rs,isTensorInList:()=>fw,makeTypesMatch:()=>Y});function Y(e,t){if(e.dtype===t.dtype)return[e,t];const n=xr(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function Pp(e,t){f(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function fw(e,t){return t.some(n=>n.id===e.id)}function rs(e){const t=[],n=new Set;return hu(e,t,n),t}function hu(e,t,n){if(e==null)return;if(e instanceof te){t.push(e);return}if(!gw(e))return;const r=e;for(const o in r){const i=r[o];n.has(i)||(n.add(i),hu(i,t,n))}}function gw(e){return Array.isArray(e)||typeof e=="object"}class uu{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 os{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new uu}async ready(){if(this.pendingBackendInit!=null)return this.pendingBackendInit.then(()=>{});if(this.backendInstance!=null)return;const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t],r=await this.initializeBackend(n).success;if(r){await this.setBackend(n);return}}throw new Error("Could not initialize any backends, all backend initializations failed.")}get backend(){if(this.pendingBackendInit!=null)throw new Error(`Backend '${this.backendName}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);if(this.backendInstance==null){const{name:e,asyncInit:t}=this.initializeBackendsAndReturnBest();if(t)throw new Error(`The highest priority backend '${e}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(e)}return this.backendInstance}backendNames(){return Object.keys(this.registryFactory)}findBackend(e){if(!(e in this.registry))if(e in this.registryFactory){const{asyncInit:t}=this.initializeBackend(e);if(t)return null}else return null;return this.registry[e]}findBackendFactory(e){return e in this.registryFactory?this.registryFactory[e].factory:null}registerBackend(e,t,n=1){return e in this.registryFactory?(console.warn(`${e} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[e]={factory:t,priority:n},!0)}async setBackend(e){if(this.registryFactory[e]==null)throw new Error(`Backend name '${e}' not found in registry`);if(this.backendName=e,this.registry[e]==null){this.backendInstance=null;const{success:t,asyncInit:n}=this.initializeBackend(e),r=n?await t:t;if(!r)return!1}return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new tu(this.backendInstance),!0}setupRegisteredKernels(){const e=aa(this.backendName);e.forEach(t=>{t.setupFunc!=null&&t.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){const t=aa(e);t.forEach(n=>{n.disposeFunc!=null&&n.disposeFunc(this.registry[e])})}initializeBackend(e){const t=this.registryFactory[e];if(t==null)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{const n=t.factory();if(Promise.resolve(n)===n){const r=++this.pendingBackendInitId,o=n.then(i=>r<this.pendingBackendInitId?!1:(this.registry[e]=i,this.pendingBackendInit=null,!0)).catch(i=>(r<this.pendingBackendInitId||(this.pendingBackendInit=null,console.warn(`Initialization of backend ${e} failed`),console.warn(i.stack||i.message)),!1));return this.pendingBackendInit=o,{success:o,asyncInit:!0}}else return this.registry[e]=n,{success:!0,asyncInit:!1}}catch(n){return console.warn(`Initialization of backend ${e} failed`),console.warn(n.stack||n.message),{success:!1,asyncInit:!1}}}removeBackend(e){if(!(e in this.registryFactory))throw new Error(`${e} backend not found in registry`);this.backendName===e&&this.pendingBackendInit!=null&&this.pendingBackendInitId++,e in this.registry&&(this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e]),delete this.registryFactory[e],this.backendName===e&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)}getSortedBackends(){if(Object.keys(this.registryFactory).length===0)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort((e,t)=>this.registryFactory[t].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t],{success:r,asyncInit:o}=this.initializeBackend(n);if(o||r)return{name:n,asyncInit:o}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){const n=this.state.tensorInfo.get(t),r=n.backend,o=this.readSync(t);r.disposeData(t),n.backend=e,e.move(t,o,n.shape,n.dtype),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(e,t){let n=null;if(t==null){if(typeof e!="function")throw new Error("Please provide a function to tidy()");t=e}else{if(typeof e!="string"&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if(typeof t!="function")throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");n=e}let r;return this.scopedRun(()=>this.startScope(n),()=>this.endScope(r),()=>(r=t(),r instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),r))}scopedRun(e,t,n){e();try{const r=n();return t(),r}catch(r){throw t(),r}}nextTensorId(){return os.nextTensorId++}nextVariableId(){return os.nextVariableId++}clone(e){const t=this.makeTensorFromDataId(e.dataId,e.shape,e.dtype),n={x:e},r=i=>({x:()=>{const a="float32",s={x:i},c={dtype:a};return b.runKernelFunc(p=>p.cast(i,a),s,null,En,c)}}),o=[];return this.addTapeNode(this.state.activeScope.name,n,[t],r,o,{}),t}runKernel(e,t,n,r,o){const i=null,a=null;return this.runKernelFunc(i,t,a,e,n,r,o)}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){const r=this.backend.numDataIds();let o=0;n.forEach(s=>{o+=s.dtype==="complex64"?3:1});const i=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],a=r-t-o-i;if(a>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${a} data ids) after running '${e}'`)}runKernelFunc(e,t,n,r,o,i,a){let s,c=[];const p=this.isTapeOn();r==null&&(r=this.state.activeScope!=null?this.state.activeScope.name:"");const l=this.state.numBytes,h=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let d;const g=Ji(r,this.backendName);let x;if(g!=null)d=()=>{const L=this.backend.numDataIds();x=g.kernelFunc({inputs:t,attrs:o,backend:this.backend});const S=Array.isArray(x)?x:[x];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(r,L,S);const I=S.map(({dataId:R,shape:A,dtype:E})=>this.makeTensorFromDataId(R,A,E));if(p){let R=this.getTensorsForGradient(r,t,I);if(R==null){a==null&&(a=[]);const A=I.filter((E,F)=>a[F]);R=(i||[]).slice().concat(A)}c=this.saveTensorsForBackwardMode(R)}return I};else{const L=S=>{if(!p)return;c=S.map(I=>this.keep(this.clone(I)))};d=()=>{const S=this.backend.numDataIds();x=this.tidy(()=>e(this.backend,L));const I=Array.isArray(x)?x:[x];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(r,S,I),I}}let w;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?s=d():(w=this.profiler.profileKernel(r,t,()=>d()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(w),s=w.outputs)}),p&&this.addTapeNode(r,t,s,n,c,o),this.state.profiling&&this.state.activeProfile.kernels.push({name:r,bytesAdded:this.state.numBytes-l,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-h,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(t).map(L=>t[L]!=null?t[L].shape:null),outputShapes:s.map(L=>L.shape),kernelTimeMs:w.timeMs,extraInfo:w.extraInfo}),Array.isArray(x)?s:s[0]}saveTensorsForBackwardMode(e){const t=e.map(n=>this.keep(this.clone(n)));return t}getTensorsForGradient(e,t,n){const r=sa(e);if(r!=null){const o=r.inputsToSave||[],i=r.outputsToSave||[];let a;r.saveAllInputs?(f(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),a=Object.keys(t).map(c=>t[c])):a=o.map(c=>t[c]);const s=n.filter((c,p)=>i[p]);return a.concat(s)}return null}makeTensor(e,t,n,r){if(e==null)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",r=r||this.backend;let o=e;n==="string"&&Tt(e[0])&&(o=e.map(s=>Mp(s)));const i=r.write(o,t,n),a=new te(t,n,i,this.nextTensorId());if(this.incRef(a,r),n==="string"){const s=this.state.tensorInfo.get(i),c=Fp(o);this.state.numBytes+=c-s.bytes,s.bytes=c}return a}makeTensorFromDataId(e,t,n,r){n=n||"float32";const o=new te(t,n,e,this.nextTensorId());return this.incRef(o,r),o}makeVariable(e,t=!0,n,r){n=n||this.nextVariableId().toString(),r!=null&&r!==e.dtype&&(e=e.cast(r));const o=new $t(e,t,n,this.nextTensorId());if(this.state.registeredVariables[o.name]!=null)throw new Error(`Variable with name ${o.name} was already registered`);return this.state.registeredVariables[o.name]=o,this.incRef(o,this.backend),o}incRef(e,t){const n=this.state.tensorInfo.has(e.dataId)?this.state.tensorInfo.get(e.dataId).refCount:0;if(this.state.numTensors++,e.dtype==="string"&&this.state.numStringTensors++,n===0){this.state.numDataBuffers++;let r=0;e.dtype!=="complex64"&&e.dtype!=="string"&&(r=e.size*Dp(e.dtype)),this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:r,refCount:0}),this.state.numBytes+=r}this.state.tensorInfo.get(e.dataId).refCount++,e instanceof $t||this.track(e)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;this.state.numTensors--,e.dtype==="string"&&this.state.numStringTensors--;const t=this.state.tensorInfo.get(e.dataId),n=t.refCount;n<=1?(e.dtype!=="complex64"&&(this.state.numBytes-=t.bytes),this.state.numDataBuffers--,t.backend.disposeData(e.dataId),this.state.tensorInfo.delete(e.dataId)):this.state.tensorInfo.get(e.dataId).refCount--}disposeVariables(){for(const e in this.state.registeredVariables){const t=this.state.registeredVariables[e];this.disposeVariable(t)}}disposeVariable(e){this.disposeTensor(e),this.state.registeredVariables[e.name]!=null&&delete this.state.registeredVariables[e.name]}memory(){const e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,e.reasons==null&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e}async profile(e){this.state.profiling=!0;const t=this.state.numBytes,n=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map(r=>r.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(const r of this.state.activeProfile.kernels)r.kernelTimeMs=await r.kernelTimeMs,r.extraInfo=await r.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(e,t,n,r,o,i){const a={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:o},s=sa(e);s!=null&&(r=s.gradFunc),r!=null&&(a.gradient=c=>(c=c.map((p,l)=>{if(p==null){const h=n[l],d=Wt(h.size,h.dtype);return this.makeTensor(d,h.shape,h.dtype)}return p}),r(c.length>1?c:c[0],o,i))),this.state.activeTape.push(a)}keep(e){return e.kept=!0,e}startTape(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){const t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){const t=rs(e),n=new Set(t.map(o=>o.id));for(let o=0;o<this.state.activeScope.track.length;o++){const i=this.state.activeScope.track[o];!i.kept&&!n.has(i.id)&&i.dispose()}const r=this.state.scopeStack.pop();this.state.activeScope=this.state.scopeStack.length===0?null:this.state.scopeStack[this.state.scopeStack.length-1],t.forEach(o=>{!o.kept&&o.scopeId===r.id&&this.track(o)})}gradients(e,t,n,r=!1){if(f(t.length>0,()=>"gradients() received an empty list of xs."),n!=null&&n.dtype!=="float32")throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`);const o=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));f(o instanceof te,()=>"The result y returned by f() must be a tensor.");const i=nu(this.state.activeTape,t,o);if(!r&&i.length===0&&t.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",()=>{const a={};a[o.id]=n==null?bw(o.shape):n,ru(a,i,c=>this.tidy(c),ww);const s=t.map(c=>a[c.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(c=>{for(const p of c.saved)p.dispose()}),this.state.activeTape=null),{value:o,grads:s}})}customGrad(e){return f(Mt(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{f(t.every(o=>o instanceof te),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let n;const r={};return t.forEach((o,i)=>{r[i]=o}),this.runKernelFunc((o,i)=>(n=e(...t,i),f(n.value instanceof te,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),f(Mt(n.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),n.value),r,(o,i)=>{const a=n.gradFunc(o,i),s=Array.isArray(a)?a:[a];f(s.length===t.length,()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."),f(s.every(p=>p instanceof te),()=>"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=ca(),n=await this.backend.time(e);return n.wallMs=ca()-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 uu;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}}os.nextTensorId=0;os.nextVariableId=0;function bw(e){const t=Zi(ee(e),"float32");return b.makeTensor(t,e,"float32")}function qp(){const e=Cc();if(e._tfengine==null){const t=new Nc(e);e._tfengine=new os(t)}return Vh(e._tfengine.ENV),au(()=>e._tfengine),e._tfengine}const b=qp();function ww(e,t){const n={a:e,b:t};return b.runKernelFunc((r,o)=>{const i=r.add(e,t);return o([e,t]),i},n,null,Cn)}const du={};_e(du,{isBrowser:()=>zp,isMobile:()=>yw});function xw(){return typeof navigator!="undefined"&&navigator!=null}function yw(){if(xw()){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 zp(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}const Kt=pe();Kt.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.")});Kt.registerFlag("IS_BROWSER",()=>zp());Kt.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");Kt.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));Kt.registerFlag("PROD",()=>!1);Kt.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Kt.getBool("DEBUG"));Kt.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);Kt.registerFlag("IS_TEST",()=>!1);function Be(e,t){let n=e;if(Ne(e))return t==="string"?[]:[e.length];if(!Array.isArray(e))return[];const r=[];for(;Array.isArray(n)||Ne(n)&&t!=="string";)r.push(n.length),n=n[0];return Array.isArray(e)&&pe().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&mu(e,r,[]),r}function mu(e,t,n){if(n=n||[],!Array.isArray(e)&&!Ne(e)){f(t.length===0,()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}f(t.length>0,()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`),f(e.length===t[0],()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`);const r=t.slice(1);for(let o=0;o<e.length;++o)mu(e[o],r,n.concat(o))}function fu(e,t,n,r){if(e==null)return;if(e!=="numeric"&&e!==t||e==="numeric"&&t==="string")throw new Error(`Argument '${n}' passed to '${r}' must be ${e} tensor, but got ${t} tensor`)}function u(e,t,n,r="numeric"){if(e instanceof te)return fu(r,e.dtype,t,n),e;let o=fr(e);if(o!=="string"&&["bool","int32","float32"].indexOf(r)>=0&&(o=r),fu(r,o,t,n),e==null||!Ne(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=Be(e,o);!Ne(e)&&!Array.isArray(e)&&(e=[e]);const a=!0,s=o!=="string"?Xi(e,o):Ft(e,[],a);return b.makeTensor(s,i,o)}function Jt(e,t,n,r="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);const o=e;return o.map((i,a)=>u(i,`${t}[${a}]`,n),r)}const Hp="__op";function m(e){const t=Object.keys(e);if(t.length!==1)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${t.length} keys.`);let n=t[0];const r=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1)),n=n+Hp;const o=(...i)=>{b.startScope(n);try{const a=r(...i);return a instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),b.endScope(a),a}catch(a){throw b.endScope(null),a}};return Object.defineProperty(o,"name",{value:n,configurable:!0}),o}function Lw(e,t){const n=u(e,"real","complex"),r=u(t,"imag","complex");G(n.shape,r.shape,`real and imag shapes, ${n.shape} and ${r.shape}, must match in call to tf.complex().`);const o=a=>a.complex(n,r),i={real:n,imag:r};return b.runKernelFunc(o,i,null,Mc)}const Je=m({complex_:Lw});function Pe(e,t,n,r){if(r==null&&(r=fr(e)),r==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!Ne(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){Qi(t);const o=ee(t),i=ee(n);f(o===i,()=>`Based on the provided shape, [${t}], the tensor should have ${o} values but has ${i}`);for(let a=0;a<n.length;++a){const s=n[a],c=a===n.length-1?s!==ee(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!Ne(e)&&!Array.isArray(e)&&(e=[e]),t=t||n,e=r!=="string"?Xi(e,r):Ft(e,[],!0),b.makeTensor(e,t,r)}function Xe(e,t,n){const r=Be(e,n);return Pe(e,t,r,n)}const is={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};const ha=4;async function Sw(e,t){const n=[],r=[],o=Array.isArray(e)?e.map(a=>a.name):Object.keys(e);for(let a=0;a<o.length;++a){const s=o[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(),g=d.reduce((L,S)=>L+S.length,0)+ha*d.length,x=new Uint8Array(g);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+=ha,x.set(S,w),w+=S.length}h(x)});r.push(l)}else r.push(c.data());t!=null&&(p.group=t),n.push(p)}const i=await Promise.all(r);return{data:vw(i),specs:n}}function Yp(e,t){const n={};let r,o=0;for(const i of t){const a=i.name,s=i.dtype,c=i.shape,p=ee(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=is[h.dtype],g=e.slice(o,o+p*d),x=h.dtype==="uint8"?new Uint8Array(g):new Uint16Array(g);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")r===void 0&&(r=Iw()),l=r(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}`);o+=p*d}else if(s==="string"){const h=ee(i.shape);l=[];for(let d=0;d<h;d++){const g=new Uint32Array(e.slice(o,o+ha))[0];o+=ha;const x=new Uint8Array(e.slice(o,o+g));l.push(x),o+=g}}else{const h=is[s],d=e.slice(o,o+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 g=new Float32Array(l.length/2),x=new Float32Array(l.length/2);for(let S=0;S<g.length;S++)g[S]=l[S*2],x[S]=l[S*2+1];const w=Xe(g,c,"float32"),L=Xe(x,c,"float32");n[a]=Je(w,L)}else throw new Error(`Unsupported dtype in weight '${a}': ${s}`);o+=p*h}s!=="complex64"&&(n[a]=Xe(l,c,s))}return n}function vw(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 r=new Uint8Array(t);let o=0;return n.forEach(i=>{r.set(new Uint8Array(i.buffer),o),o+=i.byteLength}),r.buffer}const Tw=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function gu(e){return Tw?Buffer.byteLength(e):new Blob([e]).size}function ss(e){if(e.length===1)return e[0];let t=0;e.forEach(o=>{t+=o.byteLength});const n=new Uint8Array(t);let r=0;return e.forEach(o=>{n.set(new Uint8Array(o),r),r+=o.byteLength}),n.buffer}function Vp(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 as(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:gu(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:gu(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:e.weightData.byteLength}}function Aw(){const e=n=>{let r=n<<13,o=0;for(;(r&8388608)===0;)o-=8388608,r<<=1;return r&=~8388608,o+=947912704,r|o},t=new Uint32Array(2048);t[0]=0;for(let n=1;n<1024;n++)t[n]=e(n);for(let n=1024;n<2048;n++)t[n]=939524096+(n-1024<<13);return t}function Nw(){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 Rw(){const e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function Iw(){const e=Aw(),t=Nw(),n=Rw();return r=>{const o=new ArrayBuffer(4*r.length),i=new Uint32Array(o);for(let a=0;a<r.length;a++){const s=r[a],c=e[n[s>>10]+(s&1023)]+t[s>>10];i[a]=c}return new Float32Array(o)}}class Ie{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return Ie.instance==null&&(Ie.instance=new Ie),Ie.instance}static registerSaveRouter(e){Ie.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Ie.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Ie.getHandlers(e,"save")}static getLoadHandlers(e,t){return Ie.getHandlers(e,"load",t)}static getHandlers(e,t,n){const r=[],o=t==="load"?Ie.getInstance().loadRouters:Ie.getInstance().saveRouters;return o.forEach(i=>{const a=i(e,n);a!==null&&r.push(a)}),r}}const _w=e=>Ie.registerSaveRouter(e),Cw=e=>Ie.registerLoadRouter(e),Ew=e=>Ie.getSaveHandlers(e),Ow=(e,t)=>Ie.getLoadHandlers(e,t);const yr="://";class At{constructor(){this.managers={}}static getInstance(){return At.instance==null&&(At.instance=new At),At.instance}static registerManager(e,t){f(e!=null,()=>"scheme must not be undefined or null."),e.endsWith(yr)&&(e=e.slice(0,e.indexOf(yr))),f(e.length>0,()=>"scheme must not be an empty string.");const n=At.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 ua(e){if(e.indexOf(yr)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${At.getSchemes().join(",")}`);return{scheme:e.split(yr)[0],path:e.split(yr)[1]}}async function bu(e,t,n=!1){f(e!==t,()=>`Old path and new path are the same: '${e}'`);const r=Ie.getLoadHandlers(e);f(r.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),f(r.length<2,()=>`Copying failed because more than one (${r.length}) load handlers for source URL ${e}.`);const o=r[0],i=Ie.getSaveHandlers(t);f(i.length>0,()=>`Copying failed because no save handler is found for destination URL ${t}.`),f(i.length<2,()=>`Copying failed because more than one (${r.length}) save handlers for destination URL ${t}.`);const a=i[0],s=ua(e).scheme,c=ua(e).path,p=s===ua(e).scheme,l=await o.load();n&&p&&await At.getManager(s).removeModel(c);const h=await a.save(l);return n&&!p&&await At.getManager(s).removeModel(c),h.modelArtifactsInfo}async function wu(){const e=At.getSchemes(),t={};for(const n of e){const r=await At.getManager(n).listModels();for(const o in r){const i=n+yr+o;t[i]=r[o]}}return t}async function xu(e){const t=ua(e),n=At.getManager(t.scheme);return n.removeModel(t.path)}async function yu(e,t){const n=!1;return bu(e,t,n)}async function Lu(e,t){const n=!0;return bu(e,t,n)}function Ee(e,t="float32",n){return t=t||"float32",Qi(e),new br(e,t,n)}function kw(e,t){const n=u(e,"x","cast");if(!Op(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if(t==="string"&&n.dtype!=="string"||t!=="string"&&n.dtype==="string")throw new Error("Only strings can be casted to strings");const r={x:n},o={dtype:t};return b.runKernelFunc(i=>i.cast(n,t),r,null,En,o)}const _=m({cast_:kw});function Dw(e){const t=u(e,"x","clone",null),n=()=>b.makeTensorFromDataId(t.dataId,t.shape,t.dtype),r={x:t};return b.runKernelFunc(n,r,null,Ko)}const dt=m({clone_:Dw});function da(e,t=!1){console.log(e.toString(t))}qp();const Fw={buffer:Ee,cast:_,clone:dt,print:da};cu(Fw);const Mw="model",Uw=".json",Ww=".weights.bin";function vu(e){return new Promise(t=>setTimeout(t)).then(e)}class Lr{constructor(e){if(!pe().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(Lr.URL_SCHEME)&&(e=e.slice(Lr.URL_SCHEME.length)),(e==null||e.length===0)&&(e=Mw),this.modelTopologyFileName=e+Uw,this.weightDataFileName=e+Ww}async save(e){if(typeof document=="undefined")throw new Error("Browser downloads are not supported in this environment since `document` is not present");const t=window.URL.createObjectURL(new Blob([e.weightData],{type:"application/octet-stream"}));if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");{const n=[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}],r={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:n},o=window.URL.createObjectURL(new Blob([JSON.stringify(r)],{type:"application/json"})),i=this.jsonAnchor==null?document.createElement("a"):this.jsonAnchor;if(i.download=this.modelTopologyFileName,i.href=o,await vu(()=>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 vu(()=>a.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:as(e)}}}}Lr.URL_SCHEME="downloads://";class Bw{constructor(e){if(e==null||e.length<1)throw new Error(`When calling browserFiles, at least 1 file is required, but received ${e}`);this.files=e}async load(){const e=this.files[0],t=this.files.slice(1);return new Promise((n,r)=>{const o=new FileReader;o.onload=i=>{const a=JSON.parse(i.target.result),s=a.modelTopology;if(s==null){r(new Error(`modelTopology field is missing from file ${e.name}`));return}t.length===0&&n({modelTopology:s});const c=a.weightsManifest;if(c==null){r(new Error(`weightManifest field is missing from file ${e.name}`));return}let p;try{p=this.checkManifestAndWeightFiles(c,t)}catch(g){r(g);return}const l=[],h=[],d=[];c.forEach(g=>{g.paths.forEach(x=>{h.push(x),d.push(null)}),l.push(...g.weights)}),c.forEach(g=>{g.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:ss(d),format:a.format,generatedBy:a.generatedBy,convertedBy:a.convertedBy,userDefinedMetadata:a.userDefinedMetadata})},w.onerror=L=>r(`Failed to weights data from file of path '${x}'.`),w.readAsArrayBuffer(p[x])})})},o.onerror=i=>r(`Failed to read model topology and weights manifest JSON from file '${e.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),o.readAsText(e)})}checkManifestAndWeightFiles(e,t){const n=[],r=t.map(i=>Vp(i.name)),o={};for(const i of e)i.paths.forEach(a=>{const s=Vp(a);if(n.indexOf(s)!==-1)throw new Error(`Duplicate file basename found in weights manifest: '${s}'`);if(n.push(s),r.indexOf(s)===-1)throw new Error(`Weight file with basename '${s}' is not provided.`);o[a]=t[r.indexOf(s)]});if(n.length!==t.length)throw new Error(`Mismatch in the number of files in weights manifest (${n.length}) and the number of weight files provided (${t.length}).`);return o}}const jw=e=>pe().getBool("IS_BROWSER")&&(!Array.isArray(e)&&e.startsWith(Lr.URL_SCHEME))?$w(e.slice(Lr.URL_SCHEME.length)):null;Ie.registerSaveRouter(jw);function $w(e="model"){return new Lr(e)}function Gw(e){return new Bw(e)}function Kp(e,t,n,r){a(e),n=n==null?0:n,r=r==null?1:r,s(n,r);let o=0;const i=c=>(c.then(p=>{const l=n+ ++o/e.length*(r-n);return t(l),p}),c);function a(c){f(c!=null&&Array.isArray(c)&&c.length>0,()=>"promises must be a none empty array")}function s(c,p){f(c>=0&&c<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${c}`),f(p>=0&&p<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${p}`),f(p>=c,()=>`startFraction must be no more than endFraction, but got startFraction ${c} and endFraction ${p}`)}return Promise.all(e.map(i))}async function Jp(e,t){t==null&&(t={});const n=t.fetchFunc==null?pe().platform.fetch:t.fetchFunc,r=e.map(h=>n(h,t.requestInit,{isBinary:!0})),o=0,i=.5,a=t.onProgress==null?await Promise.all(r):await Kp(r,t.onProgress,o,i),s=a.map(h=>h.arrayBuffer()),c=.5,p=1,l=t.onProgress==null?await Promise.all(s):await Kp(s,t.onProgress,c,p);return l}async function Pw(e,t="",n,r){const o=a=>Jp(a,{requestInit:r}),i=Su(o);return i(e,t,n)}function Su(e){return async(t,n="",r)=>{const o=t.map(()=>!1),i={},a=r!=null?r.map(()=>!1):[],s=[];if(t.forEach((g,x)=>{let w=0;g.weights.forEach(L=>{const S="quantization"in L?L.quantization.dtype:L.dtype,I=is[S]*ee(L.shape),R=()=>{o[x]=!0,i[x]==null&&(i[x]=[]),i[x].push({manifestEntry:L,groupOffset:w,sizeBytes:I})};r!=null?r.forEach((A,E)=>{A===L.name&&(R(),a[E]=!0)}):R(),s.push(L.name),w+=I})}),!a.every(g=>g)){const g=r.filter((x,w)=>!a[w]);throw new Error(`Could not find weights in manifest with names: ${g.join(", ")}.
Manifest JSON has weights with names: ${s.join(", ")}.`)}const c=o.reduce((g,x,w)=>(x&&g.push(w),g),[]),p=[];c.forEach(g=>{t[g].paths.forEach(x=>{const w=n+(n.endsWith("/")?"":"/")+x;p.push(w)})});const l=await e(p),h={};let d=0;return c.forEach(g=>{const x=t[g].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 R=i[g];R.forEach(A=>{const E=L.slice(A.groupOffset,A.groupOffset+A.sizeBytes),F=Yp(E,[A.manifestEntry]);for(const M in F)h[M]=F[M]}),d+=x}),h}}const qw="application/octet-stream",zw="application/json";class Xp{constructor(e,t){if(this.DEFAULT_METHOD="POST",t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,this.weightUrlConverter=t.weightUrlConverter,t.fetchFunc!=null?(f(typeof t.fetchFunc=="function",()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"),this.fetch=t.fetchFunc):this.fetch=pe().platform.fetch,f(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&f(e.length===2,()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`),this.path=e,t.requestInit!=null&&t.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");const t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;const n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],r={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,userDefinedMetadata:e.userDefinedMetadata,weightsManifest:n};t.body.append("model.json",new Blob([JSON.stringify(r)],{type:zw}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:qw}),"model.weights.bin");const o=await this.fetch(this.path,t);if(o.ok)return{modelArtifactsInfo:as(e),responses:[o]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${o.status}.`)}async load(){const e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new Error(`Request to ${this.path} failed with status code ${e.status}. Please verify this URL points to the model JSON of the model to load.`);let t;try{t=await e.json()}catch(l){let h=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?h+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":h+=" Please make sure the server is serving valid JSON for this request.",new Error(h)}const n=t.modelTopology,r=t.weightsManifest,o=t.generatedBy,i=t.convertedBy,a=t.format,s=t.userDefinedMetadata;if(n==null&&r==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);let c,p;if(r!=null){const l=await this.loadWeights(r);[c,p]=l}return{modelTopology:n,weightSpecs:c,weightData:p,userDefinedMetadata:s,generatedBy:o,convertedBy:i,format:a}}async loadWeights(e){const t=Array.isArray(this.path)?this.path[1]:this.path,[n,r]=Hw(t),o=this.weightPathPrefix||n,i=[];for(const p of e)i.push(...p.weights);const a=[],s=[];for(const p of e)for(const l of p.paths)this.weightUrlConverter!=null?s.push(this.weightUrlConverter(l)):a.push(o+l+r);this.weightUrlConverter&&a.push(...await Promise.all(s));const c=await Jp(a,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[i,ss(c)]}}Xp.URL_SCHEME_REGEX=/^https?:\/\//;function Hw(e){const t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),r=e.substring(0,t),o=n>t?e.substring(n):"";return[r+"/",o]}function Zp(e){return e.match(Xp.URL_SCHEME_REGEX)!=null}const Iu=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let n=!0;if(Array.isArray(e)?n=e.every(r=>Zp(r)):n=Zp(e),n)return Qp(e,t)}return null};Ie.registerSaveRouter(Iu);Ie.registerLoadRouter(Iu);function Qp(e,t){return new Xp(e,t)}function Yw(e,t){return Qp(e,t)}class el{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}}class Vw{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}}function Kw(e,t,n,r){if(arguments.length===1){const o=e.modelTopology!=null||e.weightSpecs!=null;return o?new el(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 el({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 el({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:r})}function Jw(e){return new Vw(e)}const vr={};_e(vr,{browserFiles:()=>Gw,browserHTTPRequest:()=>Yw,concatenateArrayBuffers:()=>ss,copyModel:()=>yu,decodeWeights:()=>Yp,encodeWeights:()=>Sw,fromMemory:()=>Kw,getLoadHandlers:()=>Ow,getModelArtifactsInfoForJSON:()=>as,getSaveHandlers:()=>Ew,http:()=>Qp,isHTTPScheme:()=>Zp,listModels:()=>wu,loadWeights:()=>Pw,moveModel:()=>Lu,registerLoadRouter:()=>Cw,registerSaveRouter:()=>_w,removeModel:()=>xu,weightsLoaderFactory:()=>Su,withSaveHandler:()=>Jw});function Xw(e,t){const n=u(e,"x","reshape",null);t=_p(t,n.size),f(n.size===ee(t),()=>"new shape and old shape must have the same number of elements.");const r={x:n},o={shape:t},i=(a,s)=>(s([n]),a.reshape(n,t));return b.runKernelFunc(i,r,null,xi,o)}const y=m({reshape_:Xw});function Zw(e,t,n=!1,r=!1){let o=u(e,"a","matMul"),i=u(t,"b","matMul");[o,i]=Y(o,i),f(o.rank>=2&&i.rank>=2&&o.rank===i.rank,()=>`Error in matMul: inputs must have the same rank of at least 2, got ranks ${o.rank} and ${i.rank}.`);const a=n?o.shape[o.rank-2]:o.shape[o.rank-1],s=r?i.shape[i.rank-1]:i.shape[i.rank-2],c=n?o.shape[o.rank-1]:o.shape[o.rank-2],p=r?i.shape[i.rank-2]:i.shape[i.rank-1],l=o.shape.slice(0,-2),h=i.shape.slice(0,-2),d=ee(l),g=ee(h);f(Se(l,h),()=>`Error in matMul: outer dimensions (${l}) and (${h}) of Tensors with shapes ${o.shape} and ${i.shape} must match.`),f(a===s,()=>`Error in matMul: inner shapes (${a}) and (${s}) of Tensors with shapes ${o.shape} and ${i.shape} and transposeA=${n} and transposeB=${r} must match.`);const x=o.shape.slice(0,-2).concat([c,p]),w=n?y(o,[d,a,c]):y(o,[d,c,a]),L=r?y(i,[g,p,s]):y(i,[g,s,p]),S=(E,F)=>(F([w,L]),E.batchMatMul(w,L,n,r)),I={a:w,b:L},R={transposeA:n,transposeB:r},A=b.runKernelFunc(S,I,null,To,R);return y(A,x)}const V=m({matMul_:Zw});function Qw(e,t,n=1,r=0){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);const o=u(e,"indices","oneHot","int32"),i=[...o.shape,t],a=(p,l)=>(l([o]),y(p.oneHot(y(o,[o.size]),t,n,r),i)),s={indices:o},c={depth:t,onValue:n,offValue:r};return b.runKernelFunc(a,s,null,di,c)}const cs=m({oneHot_:Qw});function ex(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 r={x:n},o={perm:t};return b.runKernelFunc(i=>i.transpose(n,t),r,null,qi,o)}const K=m({transpose_:ex});function tx(e,t,n){const r=u(e,"labels","confusionMatrix"),o=u(t,"predictions","confusionMatrix");f(n==null||n>0&&Number.isInteger(n),()=>`If provided, numClasses must be a positive integer, but got ${n}`),f(r.rank===1,()=>`Expected the rank of labels to be 1, but got ${r.rank}`),f(o.rank===1,()=>`Expected the rank of predictions to be 1, but got ${o.rank}`),f(r.shape[0]===o.shape[0],()=>`Mismatch in the number of examples: ${r.shape[0]} vs. ${o.shape[0]}. Labels and predictions should have the same number of elements.`),f(n>0&&Number.isInteger(n),()=>`numClasses is required to be a positive integer, but got ${n}`);const i=cs(_(r,"int32"),n),a=cs(_(o,"int32"),n),s=K(i);return _(V(s,a),"int32")}const nx=m({confusionMatrix_:tx});const Tu={};_e(Tu,{confusionMatrix:()=>nx});function Sr(e,t,n){if(at(e),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");const r=Be(e,n);if(r.length!==3&&r.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(r.length===1&&t==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return Pe(e,t,r,n)}const Ir={};_e(Ir,{fromPixels:()=>ix,toPixels:()=>ox});let Tr;function rx(e,t=3){if(t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(e==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let n=!1,r=!1,o=!1,i=!1,a=!1;if(e.data instanceof Uint8Array)n=!0;else if(typeof ImageData!="undefined"&&e instanceof ImageData)r=!0;else if(typeof HTMLVideoElement!="undefined"&&e instanceof HTMLVideoElement)o=!0;else if(typeof HTMLImageElement!="undefined"&&e instanceof HTMLImageElement)i=!0;else if(e.getContext!=null)a=!0;else throw new Error(`pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was ${e.constructor.name}`);if(o){const g=2;if(o&&e.readyState<g)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.")}const s=Ji(na,b.backendName);if(s!=null){const g={pixels:e},x={numChannels:t};return b.runKernel(na,g,x)}const[c,p]=o?[e.videoWidth,e.videoHeight]:[e.width,e.height];let l;a?l=e.getContext("2d").getImageData(0,0,c,p).data:r||n?l=e.data:(i||o)&&(Tr==null&&(Tr=document.createElement("canvas").getContext("2d")),Tr.canvas.width=c,Tr.canvas.height=p,Tr.drawImage(e,0,0,c,p),l=Tr.getImageData(0,0,c,p).data);let h;if(t===4)h=new Int32Array(l);else{const g=c*p;h=new Int32Array(g*t);for(let x=0;x<g;x++)for(let w=0;w<t;++w)h[x*t+w]=l[x*4+w]}const d=[p,c,t];return Sr(h,d,"int32")}async function ox(e,t){let n=u(e,"img","toPixels");if(!(e instanceof te)){const p=n;n=_(p,"int32"),p.dispose()}if(n.rank!==2&&n.rank!==3)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${n.rank}.`);const[r,o]=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}`);if(n.dtype!=="float32"&&n.dtype!=="int32")throw new Error(`Unsupported type for toPixels: ${n.dtype}. Please use float32 or int32 tensors.`);const a=await n.data(),s=n.dtype==="float32"?255:1,c=new Uint8ClampedArray(o*r*4);for(let p=0;p<r*o;++p){const l=[0,0,0,255];for(let d=0;d<i;d++){const g=a[p*i+d];if(n.dtype==="float32"){if(g<0||g>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${g}.`)}else if(n.dtype==="int32"&&(g<0||g>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${g}.`);i===1?(l[0]=g*s,l[1]=g*s,l[2]=g*s):l[d]=g*s}const h=p*4;c[h+0]=Math.round(l[0]),c[h+1]=Math.round(l[1]),c[h+2]=Math.round(l[2]),c[h+3]=Math.round(l[3])}if(t!=null){t.width=o,t.height=r;const p=t.getContext("2d"),l=new ImageData(c,o,r);p.putImageData(l,0,0)}return n!==e&&n.dispose(),c}const ix=m({fromPixels_:rx});const Au={};_e(Au,{prepareAndValidate:()=>Nu});function Nu(e,t){if(e.rank<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${e.rank}.`);if(t.rank<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${t.rank}.`);if(t.dtype!=="int32")throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${t.dtype}.`);if(t.shape[t.rank-1]>e.rank)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[t.rank-1]} vs. ${e.rank}`);if(e.size===0)throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);const n=t.shape,r=n[n.length-1];let o=1;for(let p=0;p<n.length-1;++p)o*=n[p];const i=e.shape,a=n.slice();a.pop();let s=1;for(let p=r;p<e.rank;++p)s*=i[p],a.push(i[p]);const c=[...Ut(e.shape).map(p=>p/s),1].slice(0,r);return[a,o,s,c]}const Ru={};_e(Ru,{calculateShapes:()=>_u,validateInput:()=>ma,validateUpdateShape:()=>tl});function tl(e,t,n){const r=t.rank>1?t.shape[t.rank-1]:1,o=t.rank>1?t.rank-1:1,i=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${n.shape}, indices.shape: ${t.shape}, shape: ${e}, sliceDim: ${r}, and batchDim: ${o}.`;if(n.rank<o)throw new Error(i+` update.rank < ${o}. `);if(e.length<r+(n.rank-o))throw new Error(i+` Output shape length < ${r+(n.rank-o)}`);if(n.rank!==o+e.length-r)throw new Error(i+` update.rank != ${o+e.length-r}`);for(let a=0;a<o;++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-o;++a)if(n.shape[a+o]!==e[a+r])throw new Error(i+` updates.shape[${a+o}] (${n.shape[a+o]}) != shape[${a+o}] (${e[a+o]})`)}function ma(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}`)}tl(n,t,e)}function _u(e,t,n){const r=t.shape.length,o=r>1?t.shape[r-1]:1,i=n.length;let a=1;for(let h=o;h<i;++h)a*=n[h];const s=o<1?1:o,c=ee(t.shape)/s,p=[...Ut(n.slice(0,o)),1],l=ee(n);return{sliceRank:o,numUpdates:c,sliceSize:a,strides:p,outputSize:l}}const nl={};_e(nl,{assertParamsValid:()=>rl,computeFlatOffset:()=>ax,computeOutShape:()=>ol,getNormalizedAxes:()=>il,isSliceContinous:()=>sx,maskToAxes:()=>ps,parseSliceParams:()=>ls,startForAxis:()=>Mu,startIndicesWithElidedDims:()=>ku,stopForAxis:()=>Uu,stopIndicesWithElidedDims:()=>Du,stridesForAxis:()=>Fu,stridesWithElidedDims:()=>Cu});function rl(e,t,n){f(e.rank===t.length,()=>`Error in slice${e.rank}D: Length of begin ${t} must match the rank of the array (${e.rank}).`),f(e.rank===n.length,()=>`Error in slice${e.rank}D: Length of size ${n} must match the rank of the array (${e.rank}).`);for(let r=0;r<e.rank;++r)f(t[r]+n[r]<=e.shape[r],()=>`Error in slice${e.rank}D: begin[${r}] + size[${r}] (${t[r]+n[r]}) would overflow input.shape[${r}] (${e.shape[r]})`)}function ps(e){const t=[];let n=0;for(;e>0;)e&1&&t.push(n),e/=2,n++;return t}function ol(e,t,n){const r=[];for(let o=0;o<e.length;o++)r[o]=Math.ceil((t[o]-e[o])/n[o]);return r}function Cu(e,t,n,r){const o=[...e];for(let i=o.length;i<r.length;i++)o.push(1);for(let i=0;i<n;i++)i===0?o[t]=1:(o.splice(t,0,1),o.pop());return o}function Eu(e,t,n){return n<=e?n:n-(t-1)}function Ou(e,t){const n=[];for(let r=0;r<e;r++)n.push(t+r);return n}function il(e,t,n,r,o,i,a,s,c){const p=e.length;let l=new Array(p),h=new Array(p),d=new Array(p);if(t.length&&n>0){const g=t[0],x=n+1;l=ku(a,g,x,r,e),h=Du(s,g,x,o,e),d=Cu(i,g,x,e)}else for(let g=0;g<p;g++)l[g]=Mu(a,r,i,e,g,c),h[g]=Uu(s,o,i,e,g,c),d[g]=Fu(i,g,c);return{begin:l,end:h,strides:d}}function ku(e,t,n,r,o){const i=[...o],a=Ou(n,t);for(let s=0;s<i.length;s++)if(a.indexOf(s)>-1)i[s]=0;else{const c=Eu(t,n,s);let p=r[c];e&1<<c&&(p=0),i[s]=p}return i}function Du(e,t,n,r,o){const i=[...o],a=Ou(n,t);for(let s=0;s<i.length;s++)if(a.indexOf(s)>-1)i[s]=Number.MAX_SAFE_INTEGER;else{const c=Eu(t,n,s);let p=r[c];e&1<<c&&(p=Number.MAX_SAFE_INTEGER),i[s]=p}for(let s=0;s<i.length;s++){const c=o[s];i[s]<0&&(i[s]+=c),i[s]=dr(0,i[s],o[s])}return i}function Fu(e,t,n){let r=e[t];return(n&1<<t||r==null)&&(r=1),r}function Mu(e,t,n,r,o,i){let a=t[o];const s=n[o]||1;(e&1<<o||i&1<<o||a==null)&&(s>0?a=Number.MIN_SAFE_INTEGER:a=Number.MAX_SAFE_INTEGER);const c=r[o];return a<0&&(a+=c),a=dr(0,a,c-1),a}function Uu(e,t,n,r,o,i){let a=t[o];const s=n[o]||1;(e&1<<o||i&1<<o||a==null)&&(s>0?a=Number.MAX_SAFE_INTEGER:a=Number.MIN_SAFE_INTEGER);const c=r[o];return a<0&&(a+=c),s>0?a=dr(0,a,c):a=dr(-1,a,c-1),a}function sx(e,t,n){let r=n.length;for(let o=0;o<n.length;o++)if(n[o]>1){r=o;break}for(let o=r+1;o<n.length;o++)if(t[o]>0||n[o]!==e[o])return!1;return!0}function ax(e,t){let n=e.length>0?e[e.length-1]:1;for(let r=0;r<e.length-1;r++)n+=e[r]*t[r];return n}function ls(e,t,n){let r;typeof t=="number"?r=[t,...new Array(e.rank-1).fill(0)]:t.length<e.rank?r=t.concat(new Array(e.rank-t.length).fill(0)):r=t.slice(),r.forEach(i=>{f(i!==-1,()=>"slice() does not support negative begin indexing.")});let o;return n==null?o=new Array(e.rank).fill(-1):typeof n=="number"?o=[n,...new Array(e.rank-1).fill(-1)]:n.length<e.rank?o=n.concat(new Array(e.rank-n.length).fill(-1)):o=n,o=o.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]-r[a])),[r,o]}const Wu={};_e(Wu,{Serializable:()=>sl,SerializationMap:()=>Dn,registerClass:()=>Ze});class sl{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}}class Dn{constructor(){this.classNameMap={}}static getMap(){return Dn.instance==null&&(Dn.instance=new Dn),Dn.instance}static register(e){Dn.getMap().classNameMap[e.className]=[e,e.fromConfig]}}function Ze(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."),Dn.register(e)}const Bu={};_e(Bu,{TEST_EPSILON_FLOAT16:()=>$u,expectArrayBuffersEqual:()=>mx,expectArraysClose:()=>px,expectArraysEqual:()=>hx,expectNumbersClose:()=>ux,expectPromiseToFail:()=>lx,expectValuesInRange:()=>dx,testEpsilon:()=>al});const cx=.001,$u=.1;function px(e,t,n){return n==null&&(n=al()),cl(e,t,(r,o)=>pl(r,o,n))}function al(){return b.backend.floatPrecision()===32?cx:$u}function cl(e,t,n){let r=!0;if((Ne(e)||Ne(t))&&(r=!1),Ne(e)&&Ne(t)&&(r=!0),r){const a=e.constructor.name,s=t.constructor.name;if(a!==s)throw new Error(`Arrays are of different type. Actual: ${a}. Expected: ${s}`)}if(Array.isArray(e)&&Array.isArray(t)){const a=Be(e),s=Be(t);if(!Se(a,s))throw new Error(`Arrays have different shapes. Actual: [${a}]. Expected: [${s}]`)}const o=Ne(e)?e:Ft(e),i=Ne(t)?t:Ft(t);if(o.length!==i.length)throw new Error(`Arrays have different lengths actual: ${o.length} vs expected: ${i.length}.
Actual: ${o}.
Expected: ${i}.`);for(let a=0;a<i.length;++a){const s=o[a],c=i[a];if(!n(s,c))throw new Error(`Arrays differ: actual[${a}] = ${s}, expected[${a}] = ${c}.
Actual: ${o}.
Expected: ${i}.`)}}function lx(e,t){e().then(()=>t.fail(),()=>t())}function hx(e,t){const n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return Tt(e)||Tt(e[0])||Tt(t)||Tt(t[0])?cl(e,n,(r,o)=>r==o):cl(e,t,(r,o)=>pl(r,o,0))}function ux(e,t,n){if(n==null&&(n=al()),!pl(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function pl(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function dx(e,t,n){for(let r=0;r<e.length;r++)if(e[r]<t||e[r]>n)throw new Error(`Value out of range:${e[r]} low: ${t}, high: ${n}`)}function mx(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}const xc="2.4.0";function fx(){pe().set("PROD",!0)}function gx(){pe().set("DEBUG",!0)}function bx(){pe().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function ye(e){pe().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}pu(ye);function wx(){b.disposeVariables()}function xx(){return b}function yx(){return b.memory()}function Lx(e){return b.profile(e)}function O(e,t){return b.tidy(e,t)}function Le(e){const t=rs(e);t.forEach(n=>n.dispose())}function ll(e){return b.keep(e)}function vx(e){return b.time(e)}function Sx(e){return b.setBackend(e)}function Ix(){return b.ready()}function wc(){return b.backendName}function Tx(e){b.removeBackend(e)}function Ax(e){return b.findBackend(e)}function Nx(e){return b.findBackendFactory(e)}function Rx(e,t,n=1){return b.registerBackend(e,t,n)}function _x(){return b.backend}function Cx(e,t){pe().setPlatform(e,t)}function Ex(e,t){let n=u(e,"a","add"),r=u(t,"b","add");[n,r]=Y(n,r);const o=(a,s)=>{const c=a.add(n,r);return s([n,r]),c},i={a:n,b:r};return b.runKernelFunc(o,i,null,Cn)}const N=m({add_:Ex});function Ox(e,t){let n=u(e,"a","floorDiv"),r=u(t,"b","floorDiv");[n,r]=Y(n,r);const o=(a,s)=>{const c=a.floorDiv(n,r);return s([n,r]),c},i={a:n,b:r};return b.runKernelFunc(o,i,null,zo)}const fa=m({floorDiv_:Ox});function kx(e,t){let n=u(e,"a","div"),r=u(t,"b","div");if([n,r]=Y(n,r),n.dtype==="int32"&&r.dtype==="int32")return fa(n,r);const o=(s,c)=>{const p=s.realDivide(n,r);return c([n,r]),p},i={a:n,b:r},a={};return b.runKernelFunc(o,i,null,Bo,a)}const D=m({div_:kx});function Dx(e,t){let n=u(e,"a","mul"),r=u(t,"b","mul");[n,r]=Y(n,r);const o=(a,s)=>{const c=a.multiply(n,r);return s([n,r]),c},i={a:n,b:r};return b.runKernelFunc(o,i,null,li)}const v=m({mul_:Dx});function Fx(e){const t=u(e,"x","abs"),n={x:t};return b.runKernelFunc((r,o)=>(o([t]),t.dtype==="complex64"?r.complexAbs(t):r.abs(t)),n,null,ho)}const Oe=m({abs_:Fx});function Mx(e){const t=u(e,"x","acos"),n={x:t};return b.runKernelFunc((r,o)=>{const i=r.acos(t);return o([t]),i},n,null,uo)}const ju=m({acos_:Mx});function Ux(e){const t=u(e,"x","acosh"),n={x:t};return b.runKernelFunc((r,o)=>{const i=r.acosh(t);return o([t]),i},n,null,mo)}const Gu=m({acosh_:Ux});function Wx(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(!Se(i.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});const r=(i,a)=>{const s=i.addN(t);return a(t),s},o=t;return b.runKernelFunc(r,o,null,fo)}const Pu=m({addN_:Wx});function hl(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function qu(e,t,n){const r=e.length+t.length,o=[];let i=0,a=0;for(let s=0;s<r;s++)n.indexOf(s)===-1?o.push(e[i++]):o.push(t[a++]);return o}function ul(e,t){const n=[],r=e.length;for(let i=0;i<r;i++)t.indexOf(i)===-1&&n.push(e[i]);const o=t.map(i=>e[i]);return[n,o]}function we(e,t){const n=t.map(r=>1);return qu(e,n,t)}function Bx(e,t,n){f(hl(t,n),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`)}function fe(e,t){if(hl(e,t))return null;const n=[];for(let r=0;r<t;++r)e.indexOf(r)===-1&&n.push(r);return e.forEach(r=>n.push(r)),n}function Fn(e){return e.map((t,n)=>[n,t]).sort((t,n)=>t[1]-n[1]).map(t=>t[0])}function ke(e,t){const n=[];for(let r=t-e;r<t;++r)n.push(r);return n}function $x(e,t=null,n=!1){let r=u(e,"x","all","bool");const o=s=>{const c=H(t,r.shape);let p=c;const l=fe(p,r.rank);l!=null&&(r=K(r,l),p=ke(p.length,r.rank));const h=s.all(r,p);if(n){const d=we(h.shape,c);return y(h,d)}return h},i={x:r},a={axis:t,keepDims:n};return b.runKernelFunc(o,i,null,Oc,a)}const zu=m({all_:$x});function jx(e,t=null,n=!1){let r=u(e,"x","any","bool");const o=s=>{const c=H(t,r.shape);let p=c;const l=fe(p,r.rank);l!=null&&(r=K(r,l),p=ke(p.length,r.rank));const h=s.any(r,p);if(n){const d=we(h.shape,c);return y(h,d)}return h},i={x:r},a={axis:t,keepDims:n};return b.runKernelFunc(o,i,null,kc,a)}const Hu=m({any_:jx});function Gx(e,t=0){let n=u(e,"x","argMax");const r=(a,s)=>{s([n]);let c=H(t,n.shape);const p=fe(c,n.rank);return p!=null&&(n=K(n,p),c=ke(c.length,n.rank)),a.argMax(n,c[0])},o={x:n},i={axis:t};return b.runKernelFunc(r,o,null,go,i)}const Yu=m({argMax_:Gx});function Px(e,t=0){let n=u(e,"x","argMin");const r=(a,s)=>{s([n]),t==null&&(t=0);let c=H(t,n.shape);const p=fe(c,n.rank);return p!=null&&(n=K(n,p),c=ke(c.length,n.rank)),a.argMin(n,c[0])},o={x:n},i={axis:t};return b.runKernelFunc(r,o,null,bo,i)}const Vu=m({argMin_:Px});function qx(e){const t=u(e,"x","asin"),n={x:t};return b.runKernelFunc((r,o)=>{const i=r.asin(t);return o([t]),i},n,null,wo)}const Ku=m({asin_:qx});function zx(e){const t=u(e,"x","asinh"),n={x:t};return b.runKernelFunc((r,o)=>{const i=r.asinh(t);return o([t]),i},n,null,xo)}const Ju=m({asinh_:zx});function Hx(e){const t=u(e,"x","atan"),n={x:t};return b.runKernelFunc((r,o)=>{const i=r.atan(t);return o([t]),i},n,null,yo)}const Xu=m({atan_:Hx});function Yx(e,t){let n=u(e,"a","atan2"),r=u(t,"b","atan2");[n,r]=Y(n,r);const o=(a,s)=>{const c=a.atan2(n,r);return s([n,r]),c},i={a:n,b:r};return b.runKernelFunc(o,i,null,vo)}const Zu=m({atan2_:Yx});function Vx(e){const t=u(e,"x","atanh"),n={x:t};return b.runKernelFunc((r,o)=>{const i=r.atanh(t);return o([t]),i},n,null,Lo)}const Qu=m({atanh_:Vx});function Kx(e,t,n,r,o="NHWC",i){const a=e[3],s=[...t,a],c=gn(o);return je(e,s,n,i,r,null,null,c)}function Nt(e,t,n,r,o,i,a="channelsLast"){const[s,c]=ga(t);let p;if(a==="channelsLast")p=[s,c,e[3],e[3]];else if(a==="channelsFirst")p=[s,c,e[1],e[1]];else throw new Error(`Unknown dataFormat ${a}`);return je(e,p,n,r,o,i,!1,a)}function Xt(e,t,n,r,o,i,a="NDHWC"){const[s,c,p]=dl(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 bn(e,l,n,r,o,!1,h,i)}function je(e,t,n,r,o,i,a=!1,s="channelsLast"){let[c,p,l,h]=[-1,-1,-1,-1];if(s==="channelsLast")[c,p,l,h]=e;else if(s==="channelsFirst")[c,h,p,l]=e;else throw new Error(`Unknown dataFormat ${s}`);const[d,g,,x]=t,[w,L]=ga(n),[S,I]=ga(r),R=Ar(d,S),A=Ar(g,I),{padInfo:E,outHeight:F,outWidth:M}=Jx(o,p,l,w,L,R,A,i,s),j=a?x*h:x;let $;return s==="channelsFirst"?$=[c,j,F,M]:s==="channelsLast"&&($=[c,F,M,j]),{batchSize:c,dataFormat:s,inHeight:p,inWidth:l,inChannels:h,outHeight:F,outWidth:M,outChannels:j,padInfo:E,strideHeight:w,strideWidth:L,filterHeight:d,filterWidth:g,effectiveFilterHeight:R,effectiveFilterWidth:A,dilationHeight:S,dilationWidth:I,inShape:e,outShape:$,filterShape:t}}function bn(e,t,n,r,o,i=!1,a="channelsLast",s){let[c,p,l,h,d]=[-1,-1,-1,-1,-1];if(a==="channelsLast")[c,p,l,h,d]=e;else if(a==="channelsFirst")[c,d,p,l,h]=e;else throw new Error(`Unknown dataFormat ${a}`);const[g,x,w,,L]=t,[S,I,R]=dl(n),[A,E,F]=dl(r),M=Ar(g,A),j=Ar(x,E),$=Ar(w,F),{padInfo:U,outDepth:Q,outHeight:ne,outWidth:he}=Xx(o,p,l,h,S,I,R,M,j,$,s),xe=i?L*d:L;let Ue;return a==="channelsFirst"?Ue=[c,xe,Q,ne,he]:a==="channelsLast"&&(Ue=[c,Q,ne,he,xe]),{batchSize:c,dataFormat:a,inDepth:p,inHeight:l,inWidth:h,inChannels:d,outDepth:Q,outHeight:ne,outWidth:he,outChannels:xe,padInfo:U,strideDepth:S,strideHeight:I,strideWidth:R,filterDepth:g,filterHeight:x,filterWidth:w,effectiveFilterDepth:M,effectiveFilterHeight:j,effectiveFilterWidth:$,dilationDepth:A,dilationHeight:E,dilationWidth:F,inShape:e,outShape:Ue,filterShape:t}}function Zx(e,t,n,r,o){r==null&&(r=ml(e,t,n));const i=e[0],a=e[1],s=Mn((i-t+2*r)/n+1,o);f(X(s),()=>`The output # of rows (${s}) must be an integer. Change the stride and/or zero pad parameters`);const c=Mn((a-t+2*r)/n+1,o);return f(X(c),()=>`The output # of columns (${c}) must be an integer. Change the stride and/or zero pad parameters`),[s,c]}function Qx(e,t,n,r,o,i){o==null&&(o=ml(e,t,r));const a=e[0],s=e[1],c=e[2],p=Mn((a-t+2*o)/r+1,i);f(X(p),()=>`The output # of depths (${p}) must be an integer. Change the stride and/or zero pad parameters`);const l=Mn((s-t+2*o)/r+1,i);f(X(l),()=>`The output # of rows (${l}) must be an integer. Change the stride and/or zero pad parameters`);const h=Mn((c-t+2*o)/r+1,i);return f(X(h),()=>`The output # of columns (${h}) must be an integer. Change the stride and/or zero pad parameters`),[p,l,h,n]}function ml(e,t,n,r=1){const o=Ar(t,r);return Math.floor((e[0]*(n-1)-n+o)/2)}function ga(e){return typeof e=="number"?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function dl(e){return typeof e=="number"?[e,e,e]:e}function Ar(e,t){return t<=1?e:e+(e-1)*(t-1)}function Jx(e,t,n,r,o,i,a,s,c){let p,l,h;if(typeof e=="number"){const d=e===0?"VALID":"NUMBER";p={top:e,bottom:e,left:e,right:e,type:d};const g=Zx([t,n],i,r,e,s);l=g[0],h=g[1]}else if(e==="same"){l=Math.ceil(t/r),h=Math.ceil(n/o);const d=Math.max(0,(l-1)*r+i-t),g=Math.max(0,(h-1)*o+a-n),x=Math.floor(d/2),w=d-x,L=Math.floor(g/2),S=g-L;p={top:x,bottom:w,left:L,right:S,type:"SAME"}}else if(e==="valid")p={top:0,bottom:0,left:0,right:0,type:"VALID"},l=Math.ceil((t-i+1)/r),h=Math.ceil((n-a+1)/o);else if(typeof e=="object"){const d=c==="channelsLast"?e[1][0]:e[2][0],g=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&&g===0&&x===0&&w===0?"VALID":"EXPLICIT";p={top:d,bottom:g,left:x,right:w,type:L},l=Mn((t-i+d+g)/r+1,s),h=Mn((n-a+x+w)/o+1,s)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:p,outHeight:l,outWidth:h}}function Xx(e,t,n,r,o,i,a,s,c,p,l){let h,d,g,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=Qx([t,n,r,1],s,1,o,e,l);d=L[0],g=L[1],x=L[2]}else if(e==="same"){d=Math.ceil(t/o),g=Math.ceil(n/i),x=Math.ceil(r/a);const w=(d-1)*o+s-t,L=(g-1)*i+c-n,S=(x-1)*a+p-r,I=Math.floor(w/2),R=w-I,A=Math.floor(L/2),E=L-A,F=Math.floor(S/2),M=S-F;h={top:A,bottom:E,left:F,right:M,front:I,back:R,type:"SAME"}}else if(e==="valid")h={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},d=Math.ceil((t-s+1)/o),g=Math.ceil((n-c+1)/i),x=Math.ceil((r-p+1)/a);else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:h,outDepth:d,outHeight:g,outWidth:x}}function Mn(e,t){if(!t)return e;switch(t){case"round":return Math.round(e);case"ceil":return Math.ceil(e);case"floor":return Math.floor(e);default:throw new Error(`Unknown roundingMode ${t}`)}}function ct(e){const[t,n,r]=ga(e);return t===1&&n===1&&r===1}function le(e,t){return ct(e)||ct(t)}function gn(e){if(e==="NHWC")return"channelsLast";if(e==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function ey(e,t,n,r,o){const i=u(e,"x","avgPool","float32"),a=1;f(le(n,a),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`);let s=i,c=!1;i.rank===3&&(c=!0,s=y(i,[1,i.shape[0],i.shape[1],i.shape[2]])),f(s.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${s.rank}.`),o!=null&&f(X(r),()=>`Error in avgPool: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);const p=(g,x)=>{const w=Nt(s.shape,t,n,1,r,o);return x([s]),w.filterWidth===1&&w.filterHeight===1&&Se(w.inShape,w.outShape)?s.clone():g.avgPool(s,w)},l={x:s},h={filterSize:t,strides:n,pad:r,dimRoundingMode:o};let d=b.runKernelFunc(p,l,null,So,h);return d=_(d,i.dtype),c?y(d,[d.shape[1],d.shape[2],d.shape[3]]):d}const mt=m({avgPool_:ey});function ty(e,t,n,r,o,i="NDHWC",a){a==null?a=[1,1,1]:ye("dilations is deprecated, this field will be gone in v3.0.0.");const s=u(e,"x","avgPool3d","float32");let c=s,p=!1;s.rank===4&&(p=!0,c=y(s,[1,s.shape[0],s.shape[1],s.shape[2],s.shape[3]])),f(c.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${c.rank}.`),f(i==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${i}`),f(le(n,a),()=>`Error in avgPool3d: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),o!=null&&f(X(r),()=>`Error in avgPool3d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);const l=(x,w)=>{a==null&&(a=[1,1,1]);const L=Xt(c.shape,t,n,a,r,o,i);return w([c]),x.avgPool3d(c,L)},h={x:c},d={filterSize:t,strides:n,pad:r,dimRoundingMode:o,dataFormat:i,dilations:a};let g=b.runKernelFunc(l,h,null,Io,d);return g=_(g,c.dtype),p?y(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}const ed=m({avgPool3d_:ty});function fl(e,t){const n=e[0].length;e.forEach((o,i)=>{f(o.length===n,()=>`Error in concat${n}D: rank of tensors[${i}] must be the same as the rank of the rest (${n})`)}),f(t>=0&&t<n,()=>`Error in concat${n}D: axis must be between 0 and ${n-1}.`);const r=e[0];e.forEach((o,i)=>{for(let a=0;a<n;a++)f(a===t||o[a]===r[a],()=>`Error in concat${n}D: Shape of tensors[${i}] (${o}) does not match the shape of the rest (${r}) along the non-concatenated axis ${i}.`)})}function gl(e,t){const n=e[0].slice();for(let r=1;r<e.length;r++)n[t]+=e[r][t];return n}function ny(e,t=0){f(e.length>=1,()=>"Pass at least one tensor to concat");let n=Jt(e,"tensors","concat");n[0].dtype==="complex64"&&n.forEach(p=>{if(p.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor
with dtype ${p.dtype}. `)});const r=H(t,n[0].shape)[0],o=gl(n.map(p=>p.shape),r);if(ee(o)===0)return Xe([],o);if(n=n.filter(p=>p.size>0),n.length===1)return n[0];const i=n.map(p=>p.shape);fl(i,r);const a=(p,l)=>{const h=p.concat(n,r);return l(n),h},s=n,c={axis:t};return b.runKernelFunc(a,s,null,Co,c)}const Z=m({concat_:ny});function ry(e){const t=u(e,"x","sigmoid"),n={x:t};return b.runKernelFunc((r,o)=>{const i=r.sigmoid(t);return o([i]),i},n,null,Oi)}const ft=m({sigmoid_:ry});function oy(e,t,n){const r=u(e,"x","slice");if(r.rank===0)throw new Error("Slicing scalar is not possible");const[o,i]=ls(r,t,n);rl(r,o,i);const a=(p,l)=>(l([r]),p.slice(r,o,i)),s={x:r},c={begin:t,size:n};return b.runKernelFunc(a,s,null,Ri,c)}const P=m({slice_:oy});function iy(e){const t=u(e,"x","tanh"),n={x:t};return b.runKernelFunc((r,o)=>{const i=r.tanh(t);return o([i]),i},n,null,Gi)}const hs=m({tanh_:iy});function sy(e,t,n,r,o,i){const a=u(e,"forgetBias","basicLSTMCell"),s=u(t,"lstmKernel","basicLSTMCell"),c=u(n,"lstmBias","basicLSTMCell"),p=u(r,"data","basicLSTMCell"),l=u(o,"c","basicLSTMCell"),h=u(i,"h","basicLSTMCell"),d=Z([p,h],1),g=V(d,s),x=N(g,c),w=x.shape[0],L=x.shape[1]/4,S=[w,L],I=P(x,[0,0],S),R=P(x,[0,L],S),A=P(x,[0,L*2],S),E=P(x,[0,L*3],S),F=N(v(ft(I),hs(R)),v(l,ft(N(a,A)))),M=v(hs(F),ft(E));return[F,M]}const td=m({basicLSTMCell_:sy});function ay(e,t,n){const r=u(e,"x","batchToSpaceND"),o=t.reduce((c,p)=>c*p);f(r.rank>=1+t.length,()=>`input rank is ${r.rank} but should be > than blockShape.length ${t.length}`),f(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),f(r.shape[0]%o===0,()=>`input tensor batch is ${r.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${o}`);const i=c=>c.batchToSpaceND(r,t,n),a={x:r},s={blockShape:t,crops:n};return b.runKernelFunc(i,a,null,Ao,s)}const Nr=m({batchToSpaceND_:ay});function nd(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 cy(e,t,n,r,o,i){i==null&&(i=.001);const a=u(e,"x","batchNorm"),s=u(t,"mean","batchNorm"),c=u(n,"variance","batchNorm");let p;o!=null&&(p=u(o,"scale","batchNorm"));let l;r!=null&&(l=u(r,"offset","batchNorm")),f(s.rank===c.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),f(l==null||s.rank===l.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),f(p==null||s.rank===p.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");const h=nd(a),d=(L,S)=>(S([h,s,c,p]),L.batchNorm(h,ba(s),ba(c),ba(l),ba(p),i)),g={x:h,scale:p,offset:l,mean:s,variance:c},x={varianceEpsilon:i},w=b.runKernelFunc(d,g,null,Ho,x);return y(w,a.shape)}function ba(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 jt=m({batchNorm_:cy});function py(e,t,n,r,o,i){const a=u(e,"x","batchNorm"),s=u(t,"mean","batchNorm"),c=u(n,"variance","batchNorm");let p;o!=null&&(p=u(o,"scale","batchNorm"));let l;return r!=null&&(l=u(r,"offset","batchNorm")),f(a.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${a.rank}.`),f(s.rank===2||s.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${s.rank}.`),f(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${c.rank}.`),p!=null&&f(p.rank===2||p.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${p.rank}.`),l!=null&&f(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${l.rank}.`),jt(a,s,c,l,p,i)}const rd=m({batchNorm2d_:py});function ly(e,t,n,r,o,i){const a=u(e,"x","batchNorm"),s=u(t,"mean","batchNorm"),c=u(n,"variance","batchNorm");let p;o!=null&&(p=u(o,"scale","batchNorm"));let l;return r!=null&&(l=u(r,"offset","batchNorm")),f(a.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${a.rank}.`),f(s.rank===3||s.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${s.rank}.`),f(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${c.rank}.`),p!=null&&f(p.rank===3||p.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${p.rank}.`),l!=null&&f(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${l.rank}.`),jt(a,s,c,l,p,i)}const od=m({batchNorm3d_:ly});function hy(e,t,n,r,o,i){const a=u(e,"x","batchNorm"),s=u(t,"mean","batchNorm"),c=u(n,"variance","batchNorm");let p;o!=null&&(p=u(o,"scale","batchNorm"));let l;return r!=null&&(l=u(r,"offset","batchNorm")),f(a.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${a.rank}.`),f(s.rank===4||s.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${s.rank}.`),f(c.rank===4||c.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${c.rank}.`),p!=null&&f(p.rank===4||p.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${p.rank}.`),l!=null&&f(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${l.rank}.`),jt(a,s,c,l,p,i)}const id=m({batchNorm4d_:hy});function uy(e,t){let n=u(e,"broadcastTo","x");const r=n.shape;if(t.some(l=>!(l>0)||l%1!==0))throw new Error(`broadcastTo(): Invalid broadcast shape [${t}].`);if(t.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 o=n.shape,i=Array.from(t);for(let l=t.length-1;l>=0;l--)if(o[l]===t[l])i[l]=1;else if(n.shape[l]!==1)throw new Error(`broadcastTo(): [${r}] cannot be broadcast to [${t}].`);const a=i.map((l,h)=>l>1?h:-1).filter(l=>l>=0);if(a.length===0)return dt(n);const s=l=>l.tile(n,i),c={x:n},p={shape:t,inputShape:o};return b.runKernelFunc(s,c,null,No,p)}const us=m({broadcastTo_:uy});function dy(e){const t=u(e,"x","ceil"),n={x:t};return b.runKernelFunc(r=>r.ceil(t),n,null,Ro)}const sd=m({ceil_:dy});function my(e,t,n){const r=u(e,"x","clipByValue");f(t<=n,()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`);const o={x:r},i={clipValueMin:t,clipValueMax:n};return b.runKernelFunc((a,s)=>{const c=a.clip(r,t,n);return s([r]),c},o,null,_o,i)}const Rr=m({clipByValue_:my});function fy(e){return Z(e,0)}const ad=m({concat1d_:fy});function gy(e,t){return Z(e,t)}const cd=m({concat2d_:gy});function by(e,t){return Z(e,t)}const pd=m({concat3d_:by});function wy(e,t){return Z(e,t)}const ld=m({concat4d_:wy});function xy(e,t,n,r,o="NHWC",i=[1,1],a){const s=u(e,"x","conv2d"),c=u(t,"filter","conv2d");let p=s,l=!1;s.rank===3&&(l=!0,p=y(s,[1,s.shape[0],s.shape[1],s.shape[2]])),f(p.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${p.rank}.`),f(c.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${c.rank}.`),a!=null&&f(X(r),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${r}.`);const h=o==="NHWC"?p.shape[3]:p.shape[1];f(h===c.shape[2],()=>`Error in conv2d: depth of input (${h}) must match input depth for filter ${c.shape[2]}.`),f(le(n,i),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'`);const d=(L,S)=>{const I=gn(o),R=je(p.shape,c.shape,n,i,r,a,!1,I),A=L.conv2d(p,c,R);return S([p,c]),A},g={x:p,filter:c},x={strides:n,pad:r,dataFormat:o,dilations:i,dimRoundingMode:a},w=b.runKernelFunc(d,g,null,Eo,x);return l?y(w,[w.shape[1],w.shape[2],w.shape[3]]):w}const ve=m({conv2d_:xy});function yy(e,t,n,r,o="NWC",i=1,a){const s=u(e,"x","conv1d"),c=u(t,"filter","conv1d");let p=s,l=!1;s.rank===2&&(l=!0,p=y(s,[1,s.shape[0],s.shape[1]])),f(p.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${p.rank}.`),f(c.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${c.rank}.`),a!=null&&f(X(r),()=>`Error in conv1d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${r}.`),f(p.shape[2]===c.shape[1],()=>`Error in conv1d: depth of input (${p.shape[2]}) must match input depth for filter ${c.shape[1]}.`),f(le(n,i),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${i}'`),f(o==="NWC",()=>`Error in conv1d: got dataFormat of ${o} but only NWC is currently supported.`);const h=y(c,[1,c.shape[0],c.shape[1],c.shape[2]]),d=y(p,[p.shape[0],1,p.shape[1],p.shape[2]]),g=[1,n],x=[1,i],w="NHWC",L=ve(d,h,g,r,w,x,a);return l?y(L,[L.shape[2],L.shape[3]]):y(L,[L.shape[0],L.shape[2],L.shape[3]])}const hd=m({conv1d_:yy});function Ly(e,t,n,r,o,i="NHWC",a){f(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let s=e,c=t,p=!1;t.rank===3&&(p=!0,c=y(t,[1,t.shape[0],t.shape[1],t.shape[2]]),s=[1,e[0],e[1],e[2]]),f(s.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${s.length}.`),f(c.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${c.rank}`),f(n.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`);const l=i==="NHWC"?s[3]:s[1],h=i==="NHWC"?c.shape[3]:c.shape[1];f(l===n.shape[2],()=>`Error in conv2dDerInput: depth of input (${l}) must match input depth for filter ${n.shape[2]}.`),f(h===n.shape[3],()=>`Error in conv2dDerInput: depth of output (${h}) must match output depth for filter ${n.shape[3]}.`),a!=null&&f(X(o),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`);const d=(L,S)=>{const I=1,R=gn(i),A=je(s,n.shape,r,I,o,a,!1,R),E=L.conv2dDerInput(c,n,A);return S([c,n]),E},g={dy:c,filter:n},x={strides:r,pad:o,dataFormat:i,dimRoundingMode:a,inputShape:s},w=b.runKernelFunc(d,g,null,Oo,x);return p?y(w,[w.shape[1],w.shape[2],w.shape[3]]):w}const _r=m({conv2DBackpropInput_:Ly});function vy(e,t,n,r,o,i){const a=u(e,"x","conv2dTranspose"),s=u(t,"filter","conv2dTranspose");return _r(n,a,s,r,o,"NHWC",i)}const ud=m({conv2dTranspose_:vy});function Sy(e,t,n,r,o="NDHWC",i=[1,1,1]){const a=u(e,"x","conv3d"),s=u(t,"filter","conv3d");let c=a,p=!1;a.rank===4&&(p=!0,c=y(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),f(c.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${c.rank}.`),f(s.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${s.rank}.`),f(c.shape[4]===s.shape[3],()=>`Error in conv3d: depth of input (${c.shape[4]}) must match input depth for filter ${s.shape[3]}.`),f(le(n,i),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'`),f(o==="NDHWC",()=>`Error in conv3d: got dataFormat of ${o} but only NDHWC is currently supported.`);const l=(x,w)=>{const L=bn(c.shape,s.shape,n,i,r),S=x.conv3d(c,s,L);return w([c,s]),S},h={x:c,filter:s},d={strides:n,pad:r,dataFormat:o,dilations:i},g=b.runKernelFunc(l,h,null,ko,d);return p?y(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}const dd=m({conv3d_:Sy});function Iy(e,t,n,r,o){f(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let i=e,a=t,s=!1;t.rank===4&&(s=!0,a=y(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),i=[1,e[0],e[1],e[2],e[3]]);const c=i[4],p=a.shape[4];f(i.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${i.length}.`),f(a.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${a.rank}`),f(n.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`),f(c===n.shape[3],()=>`Error in conv3dDerInput: depth of input (${c}) must match input depth for filter ${n.shape[3]}.`),f(p===n.shape[4],()=>`Error in conv3dDerInput: depth of output (${p}) must match output depth for filter ${n.shape[4]}.`);const l=x=>{const w=1,L=bn(i,n.shape,r,w,o);return x.conv3dDerInput(a,n,L)},h={dy:a},d={pad:o},g=b.runKernelFunc(l,h,null,Bc,d);return s?y(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}const wa=m({conv3DBackpropInput_:Iy});function Ty(e,t,n,r,o){const i=u(e,"x","conv3dTranspose"),a=u(t,"filter","conv3dTranspose");return wa(n,i,a,r,o)}const md=m({conv3dTranspose_:Ty});function Ay(e){const t=u(e,"x","cos"),n={x:t};return b.runKernelFunc((r,o)=>{const i=r.cos(t);return o([t]),i},n,null,Do)}const Cr=m({cos_:Ay});function Ny(e){const t=u(e,"x","cosh"),n={x:t};return b.runKernelFunc((r,o)=>{const i=r.cosh(t);return o([t]),i},n,null,Fo)}const xa=m({cosh_:Ny});function Ry(e,t=0,n=!1,r=!1){const o=u(e,"x","cumsum"),i=(c,p)=>{const l=fe([t],o.rank);let h=o;l!=null&&(h=K(o,l));const d=ke(1,o.rank)[0];let g=c.cumsum(h,d,n,r);if(p([o]),l!=null){const x=Fn(l);g=K(g,x)}return g},a={x:o},s={axis:t,exclusive:n,reverse:r};return b.runKernelFunc(i,a,null,Mo,s)}const ya=m({cumsum_:Ry});function _y(e,t,n="NHWC"){const r=u(e,"x","depthToSpace"),o=n==="NHWC"?r.shape[1]:r.shape[2],i=n==="NHWC"?r.shape[2]:r.shape[3],a=n==="NHWC"?r.shape[3]:r.shape[1];f(o*t>=0,()=>`Negative dimension size caused by overflow when multiplying
${o} and ${t} for depthToSpace with input shape
${r.shape}`),f(i*t>=0,()=>`Negative dimension size caused by overflow when multiplying
${i} and ${t} for depthToSpace with input shape
${r.shape}`),f(a%(t*t)===0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${a} for depthToSpace with input shape ${r.shape}`);const s=l=>l.depthToSpace(r,t,n),c={x:r},p={blockSize:t,dataFormat:n};return b.runKernelFunc(s,c,null,jc,p)}const fd=m({depthToSpace_:_y});function Cy(e,t,n,r,o="NHWC",i=[1,1],a){const s=u(e,"x","depthwiseConv2d"),c=u(t,"filter","depthwiseConv2d");let p=s,l=!1;s.rank===3&&(l=!0,p=y(s,[1,s.shape[0],s.shape[1],s.shape[2]])),f(p.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${p.rank}.`),f(c.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${c.rank}.`),f(p.shape[3]===c.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${p.shape[3]}) must match the inChannels dimension in filter ${c.shape[2]}.`),a!=null&&f(X(r),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${r}.`);const h=(w,L)=>{i==null&&(i=[1,1]),f(le(n,i),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'`);const S=je(p.shape,c.shape,n,i,r,a,!0),I=w.depthwiseConv2D(p,c,S);return L([p,c]),I},d={x:p,filter:c},g={strides:n,pad:r,dataFormat:o,dilations:i,dimRoundingMode:a},x=b.runKernelFunc(h,d,null,Uo,g);return l?y(x,[x.shape[1],x.shape[2],x.shape[3]]):x}const wn=m({depthwiseConv2d_:Cy});function Ey(e){const t=u(e,"x","diag"),n=o=>{const i=y(t,[t.size]),a=o.diag(i),s=[...e.shape,...e.shape];return y(a,s)},r={x:t};return b.runKernelFunc(n,r,null,qc)}const gd=m({diag_:Ey});function Oy(e,t,n,r,o=[1,1],i="NHWC"){const a=u(e,"x","dilation2d"),s=u(t,"filter","dilation2d");f(a.rank===3||a.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${a.rank}.`),f(s.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${s.rank}.`),f(i==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${i}`);let c=a,p=!1;a.rank===3&&(c=y(a,[1,a.shape[0],a.shape[1],a.shape[2]]),p=!0);const l={x:c,filter:s},h={strides:n,pad:r,dilations:o},d=b.runKernel(Wo,l,h);return p?y(d,[d.shape[1],d.shape[2],d.shape[3]]):d}const bd=m({dilation2d_:Oy});function ky(e,t){const n=e.length,r=[];for(let o=0;o<n;o++){const i=n-1-o,a=e[i]||1,s=t[t.length-1-o]||1;s>1&&a===1&&r.unshift(i)}return r}function ae(e,t){const n=[];for(let r=0;r<t.length;r++){const o=e[e.length-r-1],i=t.length-r-1,a=t[i];(o==null||o===1&&a>1)&&n.unshift(i)}return n}function q(e,t){const n=[],r=Math.max(e.length,t.length);for(let o=0;o<r;o++){let i=e[e.length-o-1];i==null&&(i=1);let a=t[t.length-o-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 Dy(e,t){let n=u(e,"a","equal"),r=u(t,"b","equal");[n,r]=Y(n,r),q(n.shape,r.shape);const o=a=>a.equal(n,r),i={a:n,b:r};return b.runKernelFunc(o,i,null,Vc)}const xn=m({equal_:Dy});function Fy(e,t,n){const r=u(t,"a","where"),o=u(n,"b","where"),i=u(e,"condition","where","bool"),a=q(r.shape,o.shape),s=us(r,a),c=us(o,a);i.rank===1&&f(i.shape[0]===r.shape[0],()=>"The first dimension of `a` must match the size of `condition`."),i.rank!==1&&G(i.shape,c.shape,"Error in where: ");const p=(h,d)=>{const g=h.select(i,s,c);return d([i]),g},l={condition:i,t:s,e:c};return b.runKernelFunc(p,l,null,Ai)}const De=m({where_:Fy});function My(e){const t=u(e,"x","zerosLike"),n={x:t};return b.runKernelFunc(r=>r.zerosLike(t),n,null,Yi)}const B=m({zerosLike_:My});function Uy(e,t){let n=u(e,"a","div"),r=u(t,"b","div");[n,r]=Y(n,r);const o=D(n,r),i=B(o),a=xn(r,i);return De(a,i,o)}const wd=m({divNoNan_:Uy});function Wy(e,t){const n=u(e,"t1","dot"),r=u(t,"t2","dot");f((n.rank===1||n.rank===2)&&(r.rank===1||r.rank===2),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${r.rank}.`);const o=n.rank===1?n.size:n.shape[1],i=r.rank===1?r.size:r.shape[0];if(f(o===i,()=>`Error in dot: inner dimensions of inputs must match, but got ${o} and ${i}.`),n.rank===1&&r.rank===1){const a=y(n,[1,-1]),s=y(r,[-1,1]),c=V(a,s);return y(c,[])}else if(n.rank===1&&r.rank===2){const a=y(n,[1,-1]),s=y(r,[r.shape[0],r.shape[1]]),c=V(a,s);return y(c,[c.size])}else if(n.rank===2&&r.rank===1){const a=y(r,[-1,1]),s=V(n,a);return y(s,[s.size])}else{const a=y(r,[r.shape[0],r.shape[1]]),s=V(n,a);return s}}const xd=m({dot_:Wy});function By(e){const t=u(e,"x","elu"),n=(o,i)=>{const a=o.elu(t);return i([a]),a},r={x:t};return b.runKernelFunc(n,r,null,$o)}const La=m({elu_:By});function $y(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 b.runKernelFunc((r,o)=>{const i=r.erf(t);return o([t]),i},n,null,jo)}const yd=m({erf_:$y});function jy(e){const t=u(e,"x","exp"),n={x:t};return b.runKernelFunc((r,o)=>{const i=r.exp(t);return o([i]),i},n,null,Go)}const Te=m({exp_:jy});function Gy(e,t=0){const n=null,r=u(e,"x","expandDims",n);f(t<=r.rank,()=>"Axis must be <= rank of the tensor");const o=r.shape.slice();return t<0&&(f(-(r.rank+1)<=t,()=>`Axis must be in the interval [${-(r.rank+1)}, ${r.rank}]`),t=r.rank+t+1),o.splice(t,0,1),y(r,o)}const nt=m({expandDims_:Gy});function Py(e){const t=u(e,"x","expm1"),n={x:t};return b.runKernelFunc((r,o)=>{const i=r.expm1(t);return o([t]),i},n,null,Po)}const Ld=m({expm1_:Py});function qy(e,t){const n=null,r=u(e,"x","tile",n);f(r.rank===t.length,()=>`Error in transpose: rank of input ${r.rank} must match length of reps ${t}.`);const o=(c,p)=>{const l=c.tile(r,t);return p([r]),l},i=[r],a={x:r},s={reps:t};return b.runKernelFunc(o,a,null,Pi,s,i)}const Gt=m({tile_:qy});function zy(e,t,n,r="float32"){t==null&&(t=e);const o=Ee([e,t],r),i=e<=t?e:t;for(let s=0;s<i;++s)o.set(1,s,s);const a=y(o.toTensor(),[e,t]);if(n==null)return a;if(n.length===1)return Gt(nt(a,0),[n[0],1,1]);if(n.length===2)return Gt(nt(nt(a,0),0),[n[0],n[1],1,1]);if(n.length===3)return Gt(nt(nt(nt(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 va=m({eye_:zy});function qe(e,t,n){const r={shape:e,value:t,dtype:n};return b.runKernelFunc(o=>o.fill(e,t,n),{},null,Jc,r)}function Hy(e){const t=u(e,"x","floor"),n={x:t};return b.runKernelFunc(r=>r.floor(t),n,null,qo)}const Er=m({floor_:Hy});const Sa=30;function Yy(e){return e<=Sa?e:gr(e,Math.floor(Math.sqrt(e)))}const vd={};_e(vd,{collectGatherOpShapeInfo:()=>bl,computeOutShape:()=>Ky,segOpComputeOptimalWindowSize:()=>Vy});function Vy(e,t){let n=!1,r;for(e<=Sa?(r=e,n=!0):r=gr(e,Math.floor(Math.sqrt(e)));!n;)r>t||r===e?n=!0:r=gr(e,r+1);return r}function Ky(e,t,n){const r=[],o=e.length;for(let i=0;i<o;i++)i!==t?r.push(e[i]):r.push(n);return r}function bl(e,t,n){const r=e.shape[n],o=[];let i=1,a=1;for(let s=0;s<n;s++)o.push(e.shape[s]),i*=e.shape[s];for(let s=0;s<t.rank;s++)o.push(t.shape[s]);for(let s=n+1;s<e.rank;s++)o.push(e.shape[s]),a*=e.shape[s];return{batchSize:i,sliceSize:a,dimSize:r,outputShape:o}}function Jy(e,t,n=0){const r=u(e,"x","gather"),o=u(t,"indices","gather","int32"),i={x:r,indices:o},a={axis:n},s=(c,p)=>{const l=H(n,r.shape)[0],h=bl(r,o,l),d=c.gather(r,y(o,[o.size]),l);return p([r,o]),y(d,h.outputShape)};return b.runKernelFunc(s,i,null,Yo,a)}const Or=m({gather_:Jy});function Xy(e,t){let n=u(e,"a","greater"),r=u(t,"b","greater");[n,r]=Y(n,r),q(n.shape,r.shape);const o=a=>a.greater(n,r),i={a:n,b:r};return b.runKernelFunc(o,i,null,Qc)}const rt=m({greater_:Xy});function Zy(e,t){let n=u(e,"a","greaterEqual"),r=u(t,"b","greaterEqual");[n,r]=Y(n,r),q(n.shape,r.shape);const o=(a,s)=>{const c=a.greaterEqual(n,r);return s([n,r]),c},i={a:n,b:r};return b.runKernelFunc(o,i,null,Vo)}const gt=m({greaterEqual_:Zy});function Qy(e){const t=u(e,"input","imag"),n=o=>o.imag(t),r={input:t};return b.runKernelFunc(n,r,null,tp)}const yn=m({imag_:Qy});function eL(e){const t=u(e,"x","isFinite"),n={x:t};return b.runKernelFunc(r=>r.isFinite(t),n,null,Jo)}const Sd=m({isFinite_:eL});function tL(e){const t=u(e,"x","isInf"),n={x:t};return b.runKernelFunc(r=>r.isInf(t),n,null,Xo)}const Id=m({isInf_:tL});function nL(e){const t=u(e,"x","isNaN"),n={x:t};return b.runKernelFunc(r=>r.isNaN(t),n,null,Zo)}const Td=m({isNaN_:nL});function rL(e,t){let n=u(e,"a","maximum"),r=u(t,"b","maximum");[n,r]=Y(n,r),n.dtype==="bool"&&(n=_(n,"int32"),r=_(r,"int32")),q(n.shape,r.shape);const o=(a,s)=>{const c=a.maximum(n,r);return s([n,r]),c},i={a:n,b:r};return b.runKernelFunc(o,i,null,oi)}const Pt=m({maximum_:rL});function C(e,t){if((Ne(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"&&Ne(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");const n=[],r=[];return Pe(e,n,r,t)}function oL(e,t=.2){const n=u(e,"x","leakyRelu");return Pt(v(C(t),n),n)}const Ad=m({leakyRelu_:oL});function iL(e,t){let n=u(e,"a","less"),r=u(t,"b","less");[n,r]=Y(n,r),q(n.shape,r.shape);const o=a=>a.less(n,r),i={a:n,b:r};return b.runKernelFunc(o,i,null,np)}const kr=m({less_:iL});function sL(e,t){let n=u(e,"a","lessEqual"),r=u(t,"b","lessEqual");[n,r]=Y(n,r),q(n.shape,r.shape);const o=(a,s)=>{const c=a.lessEqual(n,r);return s([n,r]),c},i={a:n,b:r};return b.runKernelFunc(o,i,null,rp)}const bt=m({lessEqual_:sL});function Nd(e,t,n){if(n<=0)throw new Error("The number of values should be positive.");const r={start:e,stop:t,num:n};return b.runKernelFunc(o=>o.linspace(e,t,n),{},null,op,r)}function aL(e,t=5,n=1,r=1,o=.5){const i=u(e,"x","localResponseNormalization");f(i.rank===4||i.rank===3,()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got
rank ${i.rank}.`),f(X(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let a=i,s=!1;i.rank===3&&(s=!0,a=y(i,[1,i.shape[0],i.shape[1],i.shape[2]]));const c=(d,g)=>{const x=d.localResponseNormalization4D(a,t,n,r,o);return g([a,x]),x},p={x:a},l={depthRadius:t,bias:n,alpha:r,beta:o},h=b.runKernelFunc(c,p,null,ni,l);return s?y(h,[h.shape[1],h.shape[2],h.shape[3]]):h}const Rd=m({localResponseNormalization_:aL});function cL(e){const t=u(e,"x","log"),n={x:t};return b.runKernelFunc((r,o)=>{const i=r.log(t);return o([t]),i},n,null,Qo)}const Rt=m({log_:cL});function pL(e){const t=u(e,"x","log1p"),n={x:t};return b.runKernelFunc((r,o)=>{const i=r.log1p(t);return o([t]),i},n,null,ei)}const Ia=m({log1p_:pL});function lL(e){return f(Mt(e),()=>"The f passed in grad(f) must be a function"),(t,n)=>{const r=u(t,"x","tf.grad",null),o=n!=null?u(n,"dy","tf.grad"):null;return b.tidy(()=>{const{value:i,grads:a}=b.gradients(()=>e(r),[r],o);return o!=null&&G(i.shape,o.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Ta(a),a[0]})}}function hL(e){return f(Mt(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{f(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");const r=Jt(t,"args","tf.grads",null),o=n!=null?u(n,"dy","tf.grads"):null;return b.tidy(()=>{const{value:i,grads:a}=b.gradients(()=>e(...r),r,o);return o!=null&&G(i.shape,o.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Ta(a),a})}}function uL(e){return f(Mt(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{f(t instanceof te,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),f(n==null||n instanceof te,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");const{grads:r,value:o}=b.gradients(()=>e(t),[t],n);return Ta(r),{grad:r[0],value:o}}}function dL(e){return f(Mt(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{f(Array.isArray(t)&&t.every(o=>o instanceof te),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),f(n==null||n instanceof te,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");const r=b.gradients(()=>e(...t),t,n);return n!=null&&G(r.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Ta(r.grads),r}}function wl(e,t){f(Mt(e),()=>"The f passed in variableGrads(f) must be a function"),f(t==null||Array.isArray(t)&&t.every(p=>p instanceof $t),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");const n=t!=null;if(!n){t=[];for(const p in b.registeredVariables)t.push(b.registeredVariables[p])}const r=n?t.filter(p=>!p.trainable):null,o=t.length;t=t.filter(p=>p.trainable),f(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${o} variables is trainable.`);const i=!0,{value:a,grads:s}=b.gradients(e,t,null,i);f(s.some(p=>p!=null),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),f(a.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${a.rank} tensor`);const c={};return t.forEach((p,l)=>{s[l]!=null&&(c[p.name]=s[l])}),r!=null&&r.forEach(p=>c[p.name]=null),{value:a,grads:c}}function ze(e){return b.customGrad(e)}function Ta(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 mL(e){const t=u(e,"x","neg"),n={x:t};return b.runKernelFunc(r=>r.neg(t),n,null,hi)}const re=m({neg_:mL});function fL(e){const t=u(e,"x","softplus"),n={x:t};return b.runKernelFunc((r,o)=>{const i=r.softplus(t);return o([t]),i},n,null,ki)}const Aa=m({softplus_:fL});function gL(e){const t=u(e,"x","logSigmoid"),n=ze(r=>{const o=re(Aa(re(r))),i=a=>{const s=v(a,ft(re(r)));return s};return{value:o,gradFunc:i}});return n(t)}const _d=m({logSigmoid_:gL});function bL(e,t=null,n=!1){const r=u(e,"x","max"),o=(s,c)=>{const p=H(t,r.shape);let l=p;const h=fe(l,r.rank);let d=r;h!=null&&(d=K(r,h),l=ke(l.length,d.rank));const g=s.max(d,l);h!=null&&d.dispose();let x=g;if(n){const w=we(x.shape,H(t,r.shape));x=y(x,w),g.dispose()}return c([r,x]),x},i={x:r},a={reductionIndices:t,keepDims:n};return b.runKernelFunc(o,i,null,ri,a)}const qt=m({max_:bL});function wL(e,t){let n=u(e,"a","sub"),r=u(t,"b","sub");[n,r]=Y(n,r);const o=(a,s)=>{const c=a.subtract(n,r);return s([n,r]),c},i={a:n,b:r};return b.runKernelFunc(o,i,null,$i)}const k=m({sub_:wL});function xL(e,t=null,n=!1){let r=u(e,"x","sum");r.dtype==="bool"&&(r=_(r,"int32"));const o=(s,c)=>{c([r]);const p=H(t,r.shape),l=fe(p,r.rank);let h=p,d=r;l!=null&&(d=K(r,l),h=ke(h.length,r.rank));let g=s.sum(d,h);if(n){const x=we(g.shape,p);g=y(g,x)}return g},i={x:r},a={axis:t,keepDims:n};return b.runKernelFunc(o,i,null,Fi,a)}const W=m({sum_:xL});function yL(e,t=-1){const n=u(e,"logits","logSoftmax");if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and axis was ${t}`);const r=(a,s)=>{const c=!0,p=qt(e,t,!0),l=k(e,p),h=k(_(l,"float32"),Rt(W(Te(l),t,c)));return s([h]),h},o={logits:n},i={axis:t};return b.runKernelFunc(r,o,null,ti,i)}const Cd=m({logSoftmax_:yL});function LL(e,t=null,n=!1){const r=u(e,"x","logSumExp"),o=H(t,r.shape),i=qt(r,o,!0),a=k(r,i),s=Te(a),c=W(s,o),p=Rt(c),l=N(y(i,p.shape),p);if(n){const h=we(l.shape,o);return y(l,h)}return l}const Na=m({logSumExp_:LL});function vL(e,t){const n=u(e,"a","logicalAnd","bool"),r=u(t,"b","logicalAnd","bool");q(n.shape,r.shape);const o={a:n,b:r};return b.runKernelFunc(i=>i.logicalAnd(n,r),o,null,ip)}const _t=m({logicalAnd_:vL});function SL(e){const t=u(e,"x","logicalNot","bool"),n={x:t};return b.runKernelFunc(r=>r.logicalNot(t),n,null,sp)}const Dr=m({logicalNot_:SL});function IL(e,t){const n=u(e,"a","logicalOr","bool"),r=u(t,"b","logicalOr","bool");q(n.shape,r.shape);const o={a:n,b:r};return b.runKernelFunc(i=>i.logicalOr(n,r),o,null,ap)}const Ra=m({logicalOr_:IL});function TL(e,t){const n=u(e,"a","logicalXor","bool"),r=u(t,"b","logicalXor","bool");return q(n.shape,r.shape),_t(Ra(e,t),Dr(_t(e,t)))}const Ed=m({logicalXor_:TL});function AL(e,t,n,r,o){const i=u(e,"x","maxPool"),a=1;let s=i,c=!1;i.rank===3&&(c=!0,s=y(i,[1,i.shape[0],i.shape[1],i.shape[2]])),f(s.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${s.rank}.`),f(le(n,a),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),o!=null&&f(X(r),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);const p=(g,x)=>{const w=Nt(s.shape,t,n,1,r,o);let L;return w.filterWidth===1&&w.filterHeight===1&&Se(w.inShape,w.outShape)?L=s.clone():L=g.maxPool(s,w),x([s,L]),L},l={x:s},h={filterSize:t,strides:n,pad:r,dimRoundingMode:o},d=b.runKernelFunc(p,l,null,ii,h);return c?y(d,[d.shape[1],d.shape[2],d.shape[3]]):d}const Re=m({maxPool_:AL});function NL(e,t=[1,1,1],n,r,o,i="NDHWC",a){a==null?a=[1,1,1]:ye("dilations is deprecated, this field will be gone in v3.0.0.");const s=u(e,"x","maxPool3d");let c=s,p=!1;s.rank===4&&(p=!0,c=y(s,[1,s.shape[0],s.shape[1],s.shape[2],s.shape[3]])),f(c.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${c.rank}.`),f(i==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${i}`),f(le(n,a),()=>`Error in maxPool3d: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),o!=null&&f(X(r),()=>`Error in maxPool3d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);const l=(x,w)=>{a==null&&(a=[1,1,1]);const L=Xt(c.shape,t,n,a,r,o,i),S=x.maxPool3d(c,L);return w([c,S]),S},h={x:c},d={filterSize:t,strides:n,pad:r,dimRoundingMode:o,dataFormat:i,dilations:a},g=b.runKernelFunc(l,h,null,si,d);return p?y(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}const Od=m({maxPool3d_:NL});function RL(e,t,n,r,o=!1){const i=u(e,"x","maxPoolWithArgmax"),a={x:i},s={filterSize:t,strides:n,pad:r,includeBatchInIndex:o},c=b.runKernel(hp,a,s);return{result:c[0],indexes:c[1]}}const kd=m({maxPoolWithArgmax_:RL});function Ce(e,t="float32"){if(t==="complex64"){const r=Ce(e,"float32"),o=Ce(e,"float32");return Je(r,o)}const n=Wt(ee(e),t);return b.makeTensor(n,e,t)}function Ct(e,t="float32"){if(t==="complex64"){const r=Ct(e,"float32"),o=Ce(e,"float32");return Je(r,o)}const n=Zi(ee(e),t);return b.makeTensor(n,e,t)}function _L(e,t=null,n=!1){const r=u(e,"x","mean"),o=H(t,r.shape),i=ul(r.shape,o),a=i[1],s=ee(a),c=ze(p=>{const l=C(s),h=l.dtype===p.dtype?p:_(p,l.dtype),d=D(h,l),g=W(d,t,n),x=w=>{const L=p.shape.slice();o.forEach(R=>{L[R]=1});const S=y(w,L),I=D(v(S,Ct(p.shape,"float32")),s);return I};return{value:g,gradFunc:x}});return c(r)}const Un=m({mean_:_L});function CL(e,t=null,n=!1){const r=u(e,"x","min"),o=(s,c)=>{const p=H(t,r.shape);let l=p;const h=fe(l,r.rank);let d=r;h!=null&&(d=K(r,h),l=ke(l.length,r.rank));const g=s.min(d,l);h!=null&&d.dispose();let x=g;if(n){const w=we(x.shape,p);x=y(g,w),g.dispose()}return c([r,x]),x},i={x:r},a={axis:t,keepDims:n};return b.runKernelFunc(o,i,null,ai,a)}const ds=m({min_:CL});function EL(e,t){let n=u(e,"a","minimum"),r=u(t,"b","minimum");[n,r]=Y(n,r),n.dtype==="bool"&&(n=_(n,"int32"),r=_(r,"int32")),q(n.shape,r.shape);const o=(a,s)=>{const c=a.minimum(n,r);return s([n,r]),c},i={a:n,b:r};return b.runKernelFunc(o,i,null,ci)}const Fr=m({minimum_:EL});function OL(e,t){let n=u(e,"a","mod"),r=u(t,"b","mod");[n,r]=Y(n,r);const o=(a,s)=>{const c=a.mod(n,r);return s([n,r]),c},i={a:n,b:r};return b.runKernelFunc(o,i,null,pi)}const _a=m({mod_:OL});function kL(e){const t=u(e,"x","square"),n={},r=[t],o=[];return b.runKernelFunc((i,a)=>(a([t]),i.square(t)),{x:t},null,"Square",n,r,o)}const z=m({square_:kL});function DL(e,t=null,n=!1){e=u(e,"x","moments");const r=H(t,e.shape),o=Un(e,r,n);let i=o.shape;n||(i=we(o.shape,r));const a=z(k(_(e,"float32"),y(o,i))),s=Un(a,r,n);return{mean:o,variance:s}}const Dd=m({moments_:DL});function FL(e,t,n,r){const o=u(t,"data","multiRNNCell"),i=Jt(n,"c","multiRNNCell"),a=Jt(r,"h","multiRNNCell");let s=o;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 Fd=m({multiRNNCell_:FL});function ML(e,t,n,r=!1){const o=u(e,"logits","multinomial"),i=o.size,a=o.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(o,[1,-1]):o,c=b.runKernelFunc(p=>p.multinomial(s,r,t,n),{logits2D:s});return a===1?y(c,[c.size]):c}const Md=m({multinomial_:ML});function UL(e,t){let n=u(e,"a","notEqual"),r=u(t,"b","notEqual");[n,r]=Y(n,r),q(n.shape,r.shape);const o=a=>a.notEqual(n,r),i={a:n,b:r};return b.runKernelFunc(o,i,null,up)}const Mr=m({notEqual_:UL});function WL(e){const t=u(e,"input","real"),n=o=>o.real(t),r={input:t};return b.runKernelFunc(n,r,null,wp)}const Zt=m({real_:WL});function BL(e){const t=u(e,"x","onesLike"),n=(o,i)=>{if(t.dtype==="complex64"){const a=xl(Zt(t)),s=B(yn(t));return Je(a,s)}return o.onesLike(t)},r={x:t};return b.runKernelFunc(n,r,null,ui)}const xl=m({onesLike_:BL});function $L(e,t){const n=u(e,"v1","outerProduct"),r=u(t,"v2","outerProduct");f(n.rank===1&&r.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${r.rank}.`);const o=y(n,[-1,1]),i=y(r,[1,-1]);return V(o,i)}const Ud=m({outerProduct_:$L});function jL(e,t,n=0){const r=u(e,"x","pad");if(r.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");const o=(s,c)=>(c([r]),s.pad(r,t,n)),i={paddings:t,constantValue:n},a={x:r};return b.runKernelFunc(o,a,null,mi,i)}const He=m({pad_:jL});function GL(e,t,n=0){return f(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),He(e,[t],n)}const Wd=m({pad1d_:GL});function PL(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."),He(e,t,n)}const Bd=m({pad2d_:PL});function qL(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."),He(e,t,n)}const $d=m({pad3d_:qL});function zL(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."),He(e,t,n)}const jd=m({pad4d_:zL});function HL(e,t,n){const r=u(e,"x","spaceToBatchND");f(r.rank>=1+t.length,()=>`input rank ${r.rank} should be > than [blockShape] ${t.length}`),f(n.length===t.length,()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`),f(r.shape.reduce((s,c,p)=>p>0&&p<=t.length?s&&(c+n[p-1][0]+n[p-1][1])%t[p-1]===0:s,!0),()=>`input spatial dimensions ${r.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`);const o=s=>s.spaceToBatchND(r,t,n),i={x:r},a={blockShape:t,paddings:n};return b.runKernelFunc(o,i,null,Mi,a)}const Ur=m({spaceToBatchND_:HL});function KL(e,t,n,r,o,i){o==null&&(o=[1,1]),i==null&&(i=1),r===0&&(r="valid");const a=u(e,"x","maxPool");let s=a,c=!1;a.rank===3&&(c=!0,s=y(a,[1,a.shape[0],a.shape[1],a.shape[2]])),f(le(i,o),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${i} and dilations '${o}'`);const p=Nt(s.shape,t,i,o,r),l=[p.dilationHeight,p.dilationWidth];let h;r==="same"?h=VL([p.filterHeight,p.filterWidth],l):h=[[0,0],[0,0]];const d=l[0]===1&&l[1]===1,[g,x]=YL([p.inHeight,p.inWidth],l,h),w=d?r:"valid",L=d?s:Ur(s,l,g),S=n==="avg"?()=>mt(L,t,i,w):()=>Re(L,t,i,w),I=S(),R=d?I:Nr(I,l,x);return c?y(R,[R.shape[1],R.shape[2],R.shape[3]]):R}function YL(e,t,n){const r=n.map(l=>l[0]),o=n.map(l=>l[1]),i=e.concat(r,o),a=t.map((l,h)=>(l-i[h]%l)%l),s=o.map((l,h)=>l+a[h]),c=t.map((l,h)=>[r[h],s[h]]),p=t.map((l,h)=>[0,a[h]]);return[c,p]}function VL(e,t){const n=e.map((a,s)=>a+(a-1)*(t[s]-1)),r=n.map(a=>a-1),o=r.map(a=>Math.floor(a/2)),i=r.map((a,s)=>a-o[s]);return r.map((a,s)=>[o[s],i[s]])}const Gd=m({pool_:KL});function JL(e,t){let n=u(e,"base","pow"),r=u(t,"exp","pow");[n,r]=Y(n,r);const o={a:n,b:r},i=(a,s)=>{const c=a.pow(n,r);return s([n,r,c]),c};return b.runKernelFunc(i,o,null,fi)}const Qe=m({pow_:JL});function XL(e,t){const n=u(e,"x","prelu"),r=u(t,"alpha","prelu"),o=(a,s)=>{const c=a.prelu(n,r);return s([n,r]),c},i={x:n,alpha:r};return b.runKernelFunc(o,i,null,gi)}const Ca=m({prelu_:XL});function ZL(e,t=null,n=!1){let r=u(e,"x","prod");const o=s=>{r.dtype==="bool"&&(r=_(r,"int32"));const c=H(t,r.shape),p=fe(c,r.rank);let l=c,h=r;p!=null&&(h=K(r,p),l=ke(l.length,r.rank));let d=s.prod(h,l);if(n){const g=we(d.shape,c);d=y(d,g)}return d},i={x:r},a={axis:t,keepDims:n};return b.runKernelFunc(o,i,null,gp,a)}const Pd=m({prod_:ZL});function QL(e,t,n){const r=ee(e);let o=null;if(n==null||n==="float32")o=new Float32Array(r);else if(n==="int32")o=new Int32Array(r);else if(n==="bool")o=new Uint8Array(r);else throw new Error(`Unknown data type ${n}`);for(let i=0;i<r;i++)o[i]=t();return b.makeTensor(o,e,n)}const qd=m({rand_:QL});const Ea=zl(ah());class ms{constructor(e,t,n,r,o){this.mean=e,this.stdDev=t,this.dtype=n,this.nextVal=NaN,this.truncated=r,this.truncated&&(this.upper=this.mean+this.stdDev*2,this.lower=this.mean-this.stdDev*2);const i=o||Math.random();this.random=Ea.alea(i.toString())}nextValue(){if(!isNaN(this.nextVal)){const r=this.nextVal;return this.nextVal=NaN,r}let e,t,n=!1;for(;!n;){let r,o,i;do r=2*this.random()-1,o=2*this.random()-1,i=r*r+o*o;while(i>=1||i===0);const a=Math.sqrt(-2*Math.log(i)/i);e=this.mean+this.stdDev*r*a,t=this.mean+this.stdDev*o*a,(!this.truncated||this.isValidTruncated(e))&&(n=!0)}return(!this.truncated||this.isValidTruncated(t))&&(this.nextVal=this.convertValue(t)),this.convertValue(e)}convertValue(e){return this.dtype==null||this.dtype==="float32"?e:Math.round(e)}isValidTruncated(e){return e<=this.upper&&e>=this.lower}}class zd{constructor(e,t,n,r){this.alpha=e,this.beta=1/t,this.dtype=n;const o=r||Math.random();this.randu=Ea.alea(o.toString()),this.randn=new ms(0,1,n,!1,this.randu()),e<1?this.d=e+2/3:this.d=e-1/3,this.c=1/Math.sqrt(9*this.d)}nextValue(){let e,t,n,r,o,i;for(;;){do r=this.randn.nextValue(),i=1+this.c*r;while(i<=0);if(i*=i*i,e=r*r,t=1-.331*e*e,n=.5*e+this.d*(1-i+Math.log(i)),o=this.randu(),o<t||Math.log(o)<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 Hd{constructor(e=0,t=1,n,r){if(this.canReturnFloat=()=>this.dtype==null||this.dtype==="float32",this.min=e,this.range=t-e,this.dtype=n,r==null&&(r=Math.random()),typeof r=="number"&&(r=r.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=Ea.alea(r)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}function ev(e,t,n=1,r="float32",o){if(n==null&&(n=1),r==null&&(r="float32"),r!=="float32"&&r!=="int32")throw new Error(`Unsupported data type ${r}`);const i=new zd(t,n,r,o),a=Ee(e,r);for(let s=0;s<a.values.length;s++)a.values[s]=i.nextValue();return a.toTensor()}const Yd=m({randomGamma_:ev});function tv(e,t=0,n=1,r,o){if(r!=null&&r==="bool")throw new Error(`Unsupported data type ${r}`);const i=new ms(t,n,r,!1,o),a=Ee(e,r);for(let s=0;s<a.values.length;s++)a.values[s]=i.nextValue();return a.toTensor()}const Vd=m({randomNormal_:tv});function nv(e,t=0,n=1,r="float32",o){const i=Ee(e,r),a=new Hd(t,n,null,o);for(let s=0;s<i.values.length;s++)i.values[s]=a.nextValue();return i.toTensor()}const Oa=m({randomUniform_:nv});function ce(e,t){at(e);const n=Be(e,t);if(n.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");const r=null;return Pe(e,r,n,t)}function fs(e,t,n=1,r="float32"){if(n===0)throw new Error("Cannot have a step of zero");const o=()=>{const a=e===t,s=e<t&&n<0,c=t<e&&n>1;if(a||s||c)return Ce([0],r);const p=Math.abs(Math.ceil((t-e)/n)),l=Wt(p,r);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,r)},i={start:e,stop:t,step:n,dtype:r};return b.runKernelFunc(o,{},null,bp,i)}function rv(e){const t=u(e,"x","reciprocal"),n={x:t};return b.runKernelFunc((r,o)=>{const i=r.reciprocal(t);return o([t]),i},n,null,bi)}const Kd=m({reciprocal_:rv});function ov(e){const t=u(e,"x","relu"),n=(o,i)=>(i([t]),t.dtype==="bool"?_(t,"int32"):o.relu(t)),r={x:t};return b.runKernelFunc(n,r,null,wi)}const ie=m({relu_:ov});function iv(e){const t=u(e,"x","relu6"),n=(o,i)=>(i([t]),t.dtype==="bool"?_(t,"int32"):o.relu6(t)),r={x:t};return b.runKernelFunc(n,r,null,vi)}const ka=m({relu6_:iv});function sv(e,t){const n=u(e,"x","reverse"),r=a=>{const s=H(t,n.shape);if(n.rank===0)return dt(n);const c=a.reverse(n,s);return y(c,n.shape)},o={x:n},i={dims:t};return b.runKernelFunc(r,o,null,Si,i)}const et=m({reverse_:sv});function av(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}.`),et(t,0)}const Jd=m({reverse1d_:av});function cv(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}.`),et(n,t)}const Xd=m({reverse2d_:cv});function pv(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}.`),et(n,t)}const Zd=m({reverse3d_:pv});function lv(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}.`),et(n,t)}const Qd=m({reverse4d_:lv});function hv(e){const t=u(e,"x","round"),n={x:t};return b.runKernelFunc(r=>r.round(t),n,null,Ii)}const em=m({round_:hv});function uv(e){const t=u(e,"x","rsqrt"),n={x:t};return b.runKernelFunc((r,o)=>{const i=r.rsqrt(t);return o([t]),i},n,null,Ti)}const Da=m({rsqrt_:uv});function dv(e){const t=u(e,"x","selu"),n=(o,i)=>{const a=o.selu(t);return i([t]),a},r={x:t};return b.runKernelFunc(n,r,null,Ni)}const tm=m({selu_:dv});function mv(e,t,n,r,o,i=[1,1],a="NHWC"){const s=u(e,"x","separableConv2d"),c=u(t,"depthwiseFilter","separableConv2d"),p=u(n,"pointwiseFilter","separableConv2d");let l=s,h=!1;if(s.rank===3&&(h=!0,l=y(s,[1,s.shape[0],s.shape[1],s.shape[2]])),a==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");f(l.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${l.rank}.`),f(c.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${c.rank}.`),f(p.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${c.rank}.`),f(p.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${p.shape[0]}.`),f(p.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${p.shape[1]}.`);const d=c.shape[2],g=c.shape[3];f(p.shape[2]===d*g,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${d*g}, but got ${p.shape[2]}.`);const x=wn(l,c,r,o,a,i),w=1,L=ve(x,p,w,"valid",a);return h?y(L,[L.shape[1],L.shape[2],L.shape[3]]):L}const Wr=m({separableConv2d_:mv});async function fv(e,t){const n=u(e,"x","setdiff1d"),r=u(t,"y","setdiff1d");f(n.dtype===r.dtype,()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${r.dtype}).`),f(n.rank===1,()=>`x should be 1D tensor, but got x (${n.shape}).`),f(r.rank===1,()=>`y should be 1D tensor, but got y (${r.shape}).`);const o=await n.data(),i=await r.data(),a=new Set(i);let s=0;for(let l=0;l<o.length;l++)a.has(o[l])||s++;const c=new br([s],n.dtype),p=new br([s],"int32");for(let l=0,h=0;l<o.length;l++)a.has(o[l])||(c.values[h]=o[l],p.values[h]=l,h++);return[c.toTensor(),p.toTensor()]}const nm=fv;function gv(e){const t=u(e,"x","sign"),n={x:t};return b.runKernelFunc(r=>r.sign(t),n,null,Ei)}const rm=m({sign_:gv});function bv(e){const t=u(e,"x","sin"),n={x:t};return b.runKernelFunc((r,o)=>{const i=r.sin(t);return o([t]),i},n,null,_i)}const Fa=m({sin_:bv});function wv(e){const t=u(e,"x","sinh"),n={x:t};return b.runKernelFunc((r,o)=>{const i=r.sinh(t);return o([t]),i},n,null,Ci)}const Ma=m({sinh_:wv});function xv(e,t,n){const r=u(e,"x","slice1d");return f(r.rank===1,()=>`slice1d expects a rank-1 tensor, but got a rank-${r.rank} tensor`),P(r,[t],[n])}const om=m({slice1d_:xv});function yv(e,t,n){const r=u(e,"x","slice2d");return f(r.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${r.rank} tensor`),P(r,t,n)}const im=m({slice2d_:yv});function Lv(e,t,n){const r=u(e,"x","slice3d");return f(r.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${r.rank} tensor`),P(r,t,n)}const Ua=m({slice3d_:Lv});function vv(e,t,n){const r=u(e,"x","slice4d");return f(r.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${r.rank} tensor`),P(r,t,n)}const sm=m({slice4d_:vv});function Sv(e,t=-1){const n=u(e,"logits","softmax","float32");if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and dim was ${t}`);const r={logits:n},o={dim:t};return b.runKernelFunc((i,a)=>{const s=i.softmax(n,t);return a([s]),s},r,null,Wi,o)}const Ln=m({softmax_:Sv});function Iv(e){f(e.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);const t={input:e};return b.runKernelFunc(n=>{const r=e.shape[e.shape.length-1],o=e.size/r,i=e.as2D(o,r),a=n.fft(i);return a.reshape(e.shape)},t,null,Kc)}const Br=m({fft_:Iv});function Tv(e){f(e.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);const t={input:e};return b.runKernelFunc(n=>{const r=e.shape[e.shape.length-1],o=e.size/r,i=y(e,[o,r]),a=n.ifft(i);return y(a,e.shape)},t,null,ep)}const Wn=m({ifft_:Tv});function Av(e){const t=e.shape[e.shape.length-1],n=e.size/t;let r;if(t<=2){const o=y(e,[n,t]);r=Wn(o)}else{const o=[n,2*(t-1)],i=y(Zt(e),[n,t]),a=y(yn(e),[n,t]),s=et(P(i,[0,1],[n,t-2]),1),c=v(et(P(a,[0,1],[n,t-2]),1),C(-1)),p=Z([i,s],1),l=Z([a,c],1),h=y(Je(p,l),[o[0],o[1]]);r=Wn(h)}if(r=Zt(r),e.rank===3&&e.shape[0]!==0){const o=r,i=e.shape[0];r=y(r,[i,r.shape[0]/i,r.shape[1]]),o.dispose()}return r}const Wa=m({irfft_:Av});function yl(e,t,n=0){let r=[];if(typeof t=="number")f(e.shape[n]%t===0,()=>"Number of splits must evenly divide the axis."),r=new Array(t).fill(e.shape[n]/t);else{const o=t.reduce((a,s)=>(s===-1&&(a+=1),a),0);f(o<=1,()=>"There should be only one negative value in split array.");const i=t.indexOf(-1);if(i!==-1){const a=t.reduce((s,c)=>c>0?s+c:s);t[i]=e.shape[n]-a}f(e.shape[n]===t.reduce((a,s)=>a+s),()=>"The sum of sizes must match the size of the axis dimension."),r=t}return r}function Nv(e,t,n=0){const r=u(e,"x","split"),o=(s,c)=>{const p=H(n,r.shape)[0],l=yl(r,t,p);return s.split(r,l,p)},i={x:r},a={numOrSizeSplits:t,axis:n};return b.runKernelFunc(o,i,null,Ui,a)}const Qt=m({split_:Nv});function Rv(e,t){f(e.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${e.dtype}`);let n=e.shape[e.shape.length-1];const r=e.size/n;let o;if(t!=null&&t<n){const x=e.shape.map(L=>0),w=e.shape.map(L=>L);w[e.shape.length-1]=t,o=P(e,x,w),n=t}else if(t!=null&&t>n){const x=e.shape.map(w=>w);x[e.shape.length-1]=t-n,o=Z([e,Ce(x)],e.shape.length-1),n=t}else o=e;const i=B(o),a=y(Je(o,i),[r,n]),s=Br(a),c=Math.floor(n/2)+1,p=Zt(s),l=yn(s),h=Qt(p,[c,n-c],p.shape.length-1),d=Qt(l,[c,n-c],l.shape.length-1),g=o.shape.slice();return g[o.shape.length-1]=c,y(Je(h[0],d[0]),g)}const $r=m({rfft_:Rv});function _v(e){const t=u(e,"x","sqrt"),n={x:t};return b.runKernelFunc((r,o)=>{const i=r.sqrt(t);return o([t]),i},n,null,Di)}const ge=m({sqrt_:_v});function Cv(e,t){let n=u(e,"a","squaredDifference"),r=u(t,"b","squaredDifference");[n,r]=Y(n,r),q(n.shape,r.shape);const o=(s,c)=>{const p=s.squaredDifference(n,r);return c([n,r]),p},i={a:n,b:r},a={};return b.runKernelFunc(o,i,null,Bi,a)}const jr=m({squaredDifference_:Cv});function Ev(e,t){const n=u(e,"x","squeeze");return y(n,Cp(n.shape,t).newShape)}const Gr=m({squeeze_:Ev});function Ov(e,t=0){const n=Jt(e,"tensors","stack");if(f(n.length>=1,()=>"Pass at least one tensor to tf.stack"),n.length===1)return nt(n[0],t);const r=n[0].rank,o=n[0].shape,i=n[0].dtype;f(t<=r,()=>"Axis must be <= rank of the tensor"),n.forEach(s=>{G(o,s.shape,"All tensors passed to stack must have matching shapes"),f(i===s.dtype,()=>"All tensors passed to stack must have matching dtypes")});const a=n.map(s=>nt(s,t));return Z(a,t)}const Fe=m({stack_:Ov});function kv(e,t=0){const n=u(e,"x","step"),r={x:n},o={alpha:t};return b.runKernelFunc(i=>i.step(n,t),r,null,Vi,o)}const zt=m({step_:kv});function Dv(e,t,n,r,o=0,i=0,a=0,s=0,c=0){let p=u(e,"x","stridedSlice");const l=g=>{r==null&&(r=new Array(t.length));const x=ps(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=ps(s),S=p.shape.slice();L.forEach(U=>{t[U]=0,n[U]=1,S.splice(U,0,1)}),p=y(p,S);const{begin:I,end:R,strides:A}=il(p.shape,x,w,t,n,r,o,i,a);t=I,n=R,r=A;const E=ps(c);E.forEach(U=>{n[U]=t[U]+1,r[U]=1});const F=ol(t,n,r),M=F.filter((U,Q)=>E.indexOf(Q)===-1),j=r.every(U=>U===1);if(j)return y(P(p,t,F),M);const $=g.stridedSlice(p,t,n,r);return y($,M)},h={x:p},d={begin:t,end:n,strides:r,beginMask:o,endMask:i,ellipsisMask:a,newAxisMask:s,shrinkAxisMask:c};return b.runKernelFunc(l,h,null,Ip,d)}const am=m({stridedSlice_:Dv});function Fv(e){const t=u(e,"x","tan"),n={x:t};return b.runKernelFunc((r,o)=>{const i=r.tan(t);return o([t]),i},n,null,ji)}const cm=m({tan_:Fv});function wt(e,t,n){if(at(e),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");const r=Be(e,n);if(r.length!==2&&r.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(r.length===1&&t==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return Pe(e,t,r,n)}function xt(e,t,n){if(at(e),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");const r=Be(e,n);if(r.length!==4&&r.length!==1)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(r.length===1&&t==null)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return Pe(e,t,r,n)}function pm(e,t,n){if(at(e),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");const r=Be(e,n);if(r.length!==5&&r.length!==1)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(r.length===1&&t==null)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return Pe(e,t,r,n)}function lm(e,t,n){if(at(e),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");const r=Be(e,n);if(r.length!==6&&r.length!==1)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(r.length===1&&t==null)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return t=t||r,Pe(e,t,r,n)}function Mv(e,t=1,n=!0){const r=u(e,"x","topk");if(r.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");const o=r.shape[r.shape.length-1];if(t>o)throw new Error(`'k' passed to topk() must be <= the last dimension (${o}) but got ${t}`);const i={x:r},a={k:t,sorted:n},[s,c]=b.runKernelFunc(p=>p.topk(r,t,n),i,null,Tp,a);return{values:s,indices:c}}const hm=m({topk_:Mv});function Uv(e,t=0,n=1,r,o){if(r!=null&&r==="bool")throw new Error("Unsupported data type $ { dtype }");const i=new ms(t,n,r,!0,o),a=Ee(e,r);for(let s=0;s<a.values.length;s++)a.values[s]=i.nextValue();return a.toTensor()}const um=m({truncatedNormal_:Uv});function Wv(e,t,n){const r=u(e,"x","unsortedSegmentSum"),o=u(t,"segmentIds","unsortedSegmentSum","int32");f(X(n),()=>"numSegments must be of dtype int");const i={x:r,segmentIds:o},a={numSegments:n},s=(c,p)=>{const l=c.unsortedSegmentSum(r,o,n);return p([o]),l};return b.runKernelFunc(s,i,null,Hi,a)}const Ba=m({unsortedSegmentSum_:Wv});function Bv(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 r={value:n},o={axis:t},i=a=>a.unstack(n,t);return b.runKernelFunc(i,r,null,zi,o)}const Ae=m({unstack_:Bv});function dm(e,t=!0,n,r){return b.makeVariable(e,t,n,r)}function $a(e,t){const n=[];for(let i=0;i<t.length;i++)t[i]&&n.push(i);const r=Ee(e,"int32"),o=Ee([n.length,e.length],"int32");for(let i=0;i<n.length;i++){const a=r.indexToLoc(n[i]),s=i*e.length;o.values.set(a,s)}return o.toTensor()}async function $v(e){const t=u(e,"condition","whereAsync","bool"),n=await t.data(),r=$a(t.shape,n);return e!==t&&t.dispose(),r}const ja=$v;async function jv(e,t,n){const r=u(e,"tensor","boolMask"),o=u(t,"mask","boolMask","bool"),i=n==null?0:n,a=o.rank,s=r.shape;f(a>0,()=>"mask cannot be scalar"),G(s.slice(i,i+a),o.shape,"mask's shape must match the first K dimensions of tensor's shape,");let c=1;for(let w=i;w<i+a;w++)c*=s[w];const p=s.slice(0,i).concat([c],s.slice(i+a)),l=y(r,p),h=y(o,[-1]),d=await ja(h),g=Gr(d,[1]),x=Or(l,g,i);return e!==r&&r.dispose(),t!==o&&o.dispose(),g.dispose(),l.dispose(),h.dispose(),d.dispose(),x}const Gv=jv;function Pv(e,t){ye("strict variants of ops have been deprecated and will be removed in future");const n=u(e,"a","notEqualStrict"),r=u(t,"b","notEqualStrict");return G(n.shape,r.shape,"Error in notEqualStrict: "),Mr(n,r)}function qv(e,t){ye("strict variants of ops have been deprecated and will be removed in future");const n=u(e,"a","lessStrict"),r=u(t,"b","lessStrict");return G(n.shape,r.shape,"Error in lessStrict: "),kr(n,r)}function zv(e,t){ye("strict variants of ops have been deprecated and will be removed in future");const n=u(e,"a","equalStrict"),r=u(t,"b","equalStrict");return G(n.shape,r.shape,"Error in equalStrict: "),xn(n,r)}function Hv(e,t){ye("strict variants of ops have been deprecated and will be removed in future");const n=u(e,"a","lessEqualStrict"),r=u(t,"b","lessEqualStrict");return G(n.shape,r.shape,"Error in lessEqualStrict: "),bt(n,r)}function Yv(e,t){ye("strict variants of ops have been deprecated and will be removed in future");const n=u(e,"a","greaterStrict"),r=u(t,"b","greaterStrict");return G(n.shape,r.shape,"Error in greaterStrict: "),rt(n,r)}function Vv(e,t){ye("strict variants of ops have been deprecated and will be removed in future");const n=u(e,"a","greaterEqualStrict"),r=u(t,"b","greaterEqualStrict");return G(n.shape,r.shape,"Error in greaterEqualStrict: "),gt(n,r)}const Kv=m({equalStrict_:zv}),Jv=m({greaterEqualStrict_:Vv}),Xv=m({greaterStrict_:Yv}),Zv=m({lessEqualStrict_:Hv}),Qv=m({lessStrict_:qv}),eS=m({notEqualStrict_:Pv});function tS(e,t){ye("strict variants of ops have been deprecated and will be removed in future");const n=u(e,"a","addStrict"),r=u(t,"b","addStrict");return G(n.shape,r.shape,"Error in addStrict: "),N(n,r)}function nS(e,t){ye("strict variants of ops have been deprecated and will be removed in future");const n=u(e,"a","subStrict"),r=u(t,"b","subStrict");return G(n.shape,r.shape,"Error in subStrict: "),k(n,r)}function rS(e,t){return ye("strict variants of ops have been deprecated and will be removed in future"),G(e.shape,t.shape,"Error in powStrict: "),Qe(e,t)}function oS(e,t){ye("strict variants of ops have been deprecated and will be removed in future");const n=u(e,"a","mul"),r=u(t,"b","mul");return G(n.shape,r.shape,"Error in multiplyStrict: "),v(n,r)}function iS(e,t){ye("strict variants of ops have been deprecated and will be removed in future");const n=u(e,"a","div"),r=u(t,"b","div");return G(n.shape,r.shape,"Error in divideStrict: "),D(n,r)}function sS(e,t){ye("strict variants of ops have been deprecated and will be removed in future");const n=u(e,"a","modStrict"),r=u(t,"b","modStrict");return G(n.shape,r.shape,"Error in modStrict: "),_a(n,r)}function aS(e,t){ye("strict variants of ops have been deprecated and will be removed in future");const n=u(e,"a","minimumStrict"),r=u(t,"b","minimumStrict");return G(n.shape,r.shape,"Error in minimumStrict: "),Fr(n,r)}function cS(e,t){ye("strict variants of ops have been deprecated and will be removed in future");const n=u(e,"a","maximumStrict"),r=u(t,"b","maximumStrict");return G(n.shape,r.shape,"Error in maximumStrict: "),Pt(n,r)}function pS(e,t){ye("strict variants of ops have been deprecated and will be removed in future");const n=u(e,"a","squaredDifferenceStrict"),r=u(t,"b","squaredDifferenceStrict");return G(n.shape,r.shape,"Error in squaredDifferenceStrict: "),jr(n,r)}const lS=m({addStrict_:tS}),hS=m({divStrict_:iS}),uS=m({maximumStrict_:cS}),dS=m({minimumStrict_:aS}),mS=m({modStrict_:sS}),fS=m({mulStrict_:oS}),gS=m({powStrict_:rS}),bS=m({squaredDifferenceStrict_:pS}),wS=m({subStrict_:nS});function xS(e,t="euclidean",n=null,r=!1){e=u(e,"x","norm");const o=mm(e,t,n);let i=o.shape;if(r){const a=H(n,e.shape);i=we(o.shape,a)}return y(o,i)}function mm(e,t,n=null){if(e.rank===0)return Oe(e);if(e.rank!==1&&n===null)return mm(y(e,[-1]),t,n);if(e.rank===1||typeof n=="number"||Array.isArray(n)&&n.length===1){if(t===1)return W(Oe(e),n);if(t===Infinity)return qt(Oe(e),n);if(t===-Infinity)return ds(Oe(e),n);if(t==="euclidean"||t===2)return ge(W(Qe(Oe(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 qt(W(Oe(e),n[0]),n[1]-1);if(t===Infinity)return qt(W(Oe(e),n[1]),n[0]);if(t===-Infinity)return ds(W(Oe(e),n[1]),n[0]);if(t==="fro"||t==="euclidean")return ge(W(z(e),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${n}`)}const gs=m({norm_:xS});function yS(e,t,n,r,o=!0){const i=u(e,"v","movingAverage"),a=u(t,"x","movingAverage"),s=u(n,"decay","movingAverage");Pp(i,a),f(Se(i.shape,a.shape),()=>"Shape mismatch in v and x");const c=C(1),p=k(c,s);let l=v(k(a,i),p);if(o){f(r!=null,()=>"When using zeroDebias: true, step is required.");const h=u(r,"step","movingAverage");l=D(l,k(c,Qe(s,h)))}return N(i,l)}const LS=m({movingAverage_:yS});function vS(e,t,n){const r=u(e,"indices","scatterND","int32"),o=u(t,"updates","scatterND");ma(o,r,n);const i=c=>c.scatterND(r,o,n),a={indices:r,updates:o},s={shape:n};return b.runKernelFunc(i,a,null,Lp,s)}const SS=m({scatterND_:vS});function fm(e,t,n,r){if(e.dtype!=="int32")throw new Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was ${e.dtype}.`);if(e.rank>2)throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${e.shape}.`);const o=e.rank>0?e.shape[0]:1,i=e.rank>1?e.shape[1]:1;if(n.length!==i)throw new Error(`outputShape has incorrect number of elements:, ${n.length}, should be: ${i}.`);const a=t.size;if(!(t.rank===0||t.rank===1&&a===o))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${o}]`);if(t.dtype!==r.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}function IS(e,t,n,r=0){const o=u(e,"sparseIndices","sparseToDense","int32"),i=u(t,"sparseValues","sparseToDense"),a=u(r,"defaultValue","sparseToDense",i.dtype);fm(o,i,n,a);const s={sparseIndices:o,sparseValues:i,defaultValue:a},c={outputShape:n};return b.runKernelFunc(p=>p.sparseToDense(o,i,n,a),s,null,Sp,c)}const TS=m({sparseToDense_:IS});function AS(e,t){const n=u(t,"indices","gatherND","int32"),r=u(e,"x","gatherND"),o=a=>a.gatherND(r,n),i={params:r,indices:n};return b.runKernelFunc(o,i,null,Zc)}const NS=m({gatherND_:AS});function gm(e,t){if(t==null)return e.shape.slice();if(Se(e.shape,t))return t;if(e.shape.length===t.length){const n=[];for(let r=0;r<e.shape.length;r++)t[r]==null&&e.shape[r]!=null?n.push(e.shape[r]):n.push(t[r]);return n}return t}function RS(e,t,n,r){const o=u(e,"x","dropout");if(f(o.dtype==="float32",()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${o.dtype} tensor instead.`),f(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),t===0)return e instanceof te?o.clone():o;const i=gm(o,n),a=1-t,s=D(Er(N(Oa(i,0,1,"float32",r),a)),a);return v(o,s)}const _S=m({dropout_:RS});function Ll(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function bs(e,t,n){const r=1-e%2,o=new Float32Array(e);for(let i=0;i<e;++i){const a=2*Math.PI*i/(e+r-1);o[i]=t-n*Math.cos(a)}return ce(o,"float32")}async function CS(e,t,n=1){const r=u(e,"predictions","inTopK"),o=u(t,"targets","inTopK");f(r.rank>1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${r.rank}`),f(r.rank-1===o.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${r.rank} and targets rank ${o.rank}`),G(r.shape.slice(0,r.shape.length-1),o.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");const i=r.shape[r.shape.length-1];f(n>0&&n<=i,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${i}), but got ${n}`);const a=await r.data(),s=await o.data(),[c,p]=[a.length/i,i],l=mr("bool",c);for(let h=0;h<c;h++){const d=h*p,g=a.subarray(d,d+p),x=[];for(let w=0;w<g.length;w++)x.push({value:g[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!==r&&r.dispose(),t!==o&&o.dispose(),Xe(l,o.shape,"bool")}const ES=CS;function OS(e,t,n,r,o,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(o),()=>`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`);const h=x=>{const w=1,L=gn(i),S=je(s.shape,n,r,w,o,a,!1,L);return x.conv2dDerFilter(s,c,S)},d={x:s,dy:c},g={strides:r,pad:o,dataFormat:i,dimRoundingMode:a};return b.runKernelFunc(h,d,null,Uc,g)}const Pr=m({conv2DBackpropFilter_:OS});function Bn(e,t,n){if(n==null||n==="linear")return e;if(n==="relu")return v(e,zt(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function $n(e,t){let n=t;const r=ae(e.shape,t.shape);return r.length>0&&(n=W(n,r)),y(n,e.shape)}function jn(e,t,n){if(t==="linear")return e;if(t==="relu")return ie(e);if(t==="elu")return La(e);if(t==="relu6")return ka(e);if(t==="prelu")return Ca(e,n);throw new Error(`Unknown fused activation ${t}.`)}const Gn=(e,t)=>{const n=e>0;return!n||t==="linear"};function kS({x:e,filter:t,strides:n,pad:r,dataFormat:o="NHWC",dilations:i=[1,1],dimRoundingMode:a,bias:s,activation:c="linear",preluActivationWeights:p}){if(c=c||"linear",Gn(b.state.gradientDepth,c)===!1){let E=ve(e,t,n,r,o,i,a);return s!=null&&(E=N(E,s)),jn(E,c,p)}const l=u(e,"x","conv2d"),h=u(t,"filter","conv2d");let d=l,g=!1;l.rank===3&&(g=!0,d=y(l,[1,l.shape[0],l.shape[1],l.shape[2]])),f(d.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${d.rank}.`),f(h.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${h.rank}.`),a!=null&&f(X(r),()=>`Error in fused conv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${r}.`),f(d.shape[3]===h.shape[2],()=>`Error in conv2d: depth of input (${d.shape[3]}) must match input depth for filter ${h.shape[2]}.`),f(le(n,i),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'`),f(o==="NHWC",()=>`Error in conv2d: got dataFormat of ${o} but only NHWC is currently supported.`);const x=je(d.shape,h.shape,n,i,r,a);let w;s!=null&&(w=u(s,"bias","fused conv2d"),[w]=Y(w,l),q(x.outShape,w.shape));let L;p!=null&&(L=u(p,"prelu weights","fused conv2d"));const S=(E,F)=>{const[M,j,$,U]=F,Q=Bn(E,$,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 ne=_r(j.shape,Q,M,n,r),he=Pr(j,Q,M.shape,n,r),xe=[ne,he];if(U!=null){const Ue=$n(U,Q);xe.push(Ue)}return xe},I=E=>{const F=E.fusedConv2d({input:d,filter:h,convInfo:x,bias:w,activation:c,preluActivationWeights:L});return F},R={x:d,filter:h,bias:w,preluActivationWeights:L},A={strides:n,pad:r,dataFormat:o,dilations:i,dimRoundingMode:a,activation:c};if(s==null){const E=ze((F,M,j)=>{let $=b.runKernelFunc(I,R,null,oa,A);return j([M,F,$]),g&&($=y($,[$.shape[1],$.shape[2],$.shape[3]])),{value:$,gradFunc:S}});return E(d,h)}else{const E=ze((F,M,j,$)=>{let U=b.runKernelFunc(I,R,null,oa,A);return $([M,F,U,j]),g&&(U=y(U,[U.shape[1],U.shape[2],U.shape[3]])),{value:U,gradFunc:S}});return E(d,h,w)}}const DS=m({fusedConv2d_:kS});function FS(e,t,n,r){let o=e;e.rank===3&&(o=y(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let i=t;i.rank===3&&(i=y(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const a=c=>c.depthwiseConv2DDerFilter(o,i,r),s={x:o,dy:i};return b.runKernelFunc(a,s,null,Gc)}const Ga=m({depthwiseConv2dNativeBackpropFilter_:FS});function MS(e,t,n,r){let o=t,i=!1;t.rank===3&&(i=!0,o=y(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const a=p=>p.depthwiseConv2DDerInput(o,n,r),s={dy:o},c=b.runKernelFunc(a,s,null,Pc);return i?y(c,[c.shape[1],c.shape[2],c.shape[3]]):c}const Pa=m({depthwiseConv2dNativeBackpropInput_:MS});function US({x:e,filter:t,strides:n,pad:r,dataFormat:o="NHWC",dilations:i=[1,1],dimRoundingMode:a,bias:s,activation:c="linear",preluActivationWeights:p}){if(Gn(b.state.gradientDepth,c)===!1){let E=wn(e,t,n,r,o,i,a);return s!=null&&(E=N(E,s)),jn(E,c,p)}const l=u(e,"x","depthwiseConv2d"),h=u(t,"filter","depthwiseConv2d");let d=l,g=!1;l.rank===3&&(g=!0,d=y(l,[1,l.shape[0],l.shape[1],l.shape[2]])),f(d.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${d.rank}.`),f(h.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${h.rank}.`),f(d.shape[3]===h.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${d.shape[3]}) must match the inChannels dimension in filter ${h.shape[2]}.`),i==null&&(i=[1,1]),f(le(n,i),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'`),a!=null&&f(X(r),()=>`Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode ${a} but got pad ${r}.`);const x=je(d.shape,h.shape,n,i,r,a,!0);let w;s!=null&&(w=u(s,"bias","fused conv2d"),[w]=Y(w,l),q(x.outShape,w.shape));let L;p!=null&&(L=u(p,"prelu weights","fused depthwiseConv2d"));const S=(E,F)=>{f(ct(i),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${i}'`);const[M,j,$,U]=F,Q=Bn(E,$,c),ne=Pa(j.shape,Q,M,x),he=Ga(j,Q,M.shape,x);if(U!=null){const xe=$n(w,Q);return[ne,he,xe]}return[ne,he]},I=E=>{const F=E.fusedDepthwiseConv2D({input:d,filter:h,convInfo:x,bias:w,activation:c,preluActivationWeights:L});return F},R={x:d,filter:h,bias:w,preluActivationWeights:L},A={strides:n,pad:r,dataFormat:o,dilations:i,dimRoundingMode:a,activation:c};if(s==null){const E=ze((F,M,j)=>{let $=b.runKernelFunc(I,R,null,ia,A);return j([M,F,$]),g&&($=y($,[$.shape[1],$.shape[2],$.shape[3]])),{value:$,gradFunc:S}});return E(d,h)}else{const E=ze((F,M,j,$)=>{let U=b.runKernelFunc(I,R,null,ia,A);return $([M,F,U,j]),g&&(U=y(U,[U.shape[1],U.shape[2],U.shape[3]])),{value:U,gradFunc:S}});return E(d,h,w)}}const WS=m({fusedDepthwiseConv2d_:US});function BS({a:e,b:t,transposeA:n=!1,transposeB:r=!1,bias:o,activation:i="linear",preluActivationWeights:a}){if(Gn(b.state.gradientDepth,i)===!1){let U=V(e,t,n,r);return o!=null&&(U=N(U,o)),jn(U,i,a)}let s=u(e,"a","fused matMul"),c=u(t,"b","fused matMul");[s,c]=Y(s,c);const p=n?s.shape[s.rank-2]:s.shape[s.rank-1],l=r?c.shape[c.rank-1]:c.shape[c.rank-2],h=n?s.shape[s.rank-1]:s.shape[s.rank-2],d=r?c.shape[c.rank-2]:c.shape[c.rank-1],g=s.shape.slice(0,-2),x=c.shape.slice(0,-2),w=ee(g),L=ee(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(Se(g,x),()=>`Error in fused matMul: outer dimensions (${g}) and (${x}) of Tensors with shapes ${s.shape} and ${c.shape} must match.`),f(p===l,()=>`Error in fused matMul: inner shapes (${p}) and (${l}) of Tensors with shapes ${s.shape} and ${c.shape} and transposeA=${n} and transposeB=${r} must match.`);const S=s.shape.slice(0,-2).concat([h,d]),I=n?y(s,[w,p,h]):y(s,[w,h,p]),R=r?y(c,[L,d,l]):y(c,[L,l,d]);let A;o!=null&&(A=u(o,"bias","fused matMul"),[A]=Y(A,s),q(S,A.shape));let E;a!=null&&(E=u(a,"prelu weights","fused matMul"));const F=(U,Q)=>{const[ne,he,xe,Ue]=Q,vt=Bn(y(U,xe.shape),xe,i);let sn,tr;if(!n&&!r?(sn=V(vt,he,!1,!0),tr=V(ne,vt,!0,!1)):!n&&r?(sn=V(vt,he,!1,!1),tr=V(vt,ne,!0,!1)):n&&!r?(sn=V(he,vt,!1,!0),tr=V(ne,vt,!1,!1)):(sn=V(he,vt,!0,!0),tr=V(vt,ne,!0,!0)),o!=null){const Ab=$n(Ue,vt);return[sn,tr,Ab]}else return[sn,tr]},M=U=>{const Q=U.fusedBatchMatMul({a:I,b:R,transposeA:n,transposeB:r,bias:A,activation:i,preluActivationWeights:E});return Q},j={a:I,b:R,bias:A,preluActivationWeights:E},$={transposeA:n,transposeB:r,activation:i};if(o==null){const U=ze((Q,ne,he)=>{const xe=b.runKernelFunc(M,j,null,ra,$);return he([Q,ne,xe]),{value:y(xe,S),gradFunc:F}});return U(I,R)}else{const U=ze((Q,ne,he,xe)=>{const Ue=b.runKernelFunc(M,j,null,ra,$);return xe([Q,ne,Ue,he]),{value:y(Ue,S),gradFunc:F}});return U(I,R,A)}}const $S=m({fusedMatMul_:BS});const bm={};_e(bm,{conv2d:()=>DS,depthwiseConv2d:()=>WS,matMul:()=>$S});function jS(e){return bs(e,.54,.46)}const wm=m({hammingWindow_:jS});function GS(e){return bs(e,.5,.5)}const qa=m({hannWindow_:GS});function PS(e,t,n,r=!1,o=0){let i=0;const a=[];for(;i+t<=e.size;)a.push(P(e,i,t)),i+=n;if(r)for(;i<e.size;){const s=i+t-e.size,c=Z([P(e,i,t-s),qe([s],o)]);a.push(c),i+=n}return a.length===0?wt([],[0,t]):y(Z(a),[a.length,t])}const za=m({frame_:PS});function qS(e,t,n,r,o=qa){r==null&&(r=Ll(t));const i=za(e,t,n),a=v(i,o(t)),s=[];for(let c=0;c<i.shape[0];c++)s.push($r(P(a,[c,0],[1,t]),r));return Z(s)}const xm=m({stft_:qS});function zS(e,t,n,r,o,i){const a=u(e,"image","cropAndResize"),s=u(t,"boxes","cropAndResize","float32"),c=u(n,"boxInd","cropAndResize","int32");o=o||"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(r.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${r.length}.`),f(r[0]>=1&&r[1]>=1,()=>`cropSize must be atleast [1,1], but was ${r}`),f(o==="bilinear"||o==="nearest",()=>`method must be bilinear or nearest, but was ${o}`);const l=x=>x.cropAndResize(a,s,c,r,o,i),h={image:a,boxes:s,boxInd:c},d={method:o,extrapolationValue:i,cropSize:r},g=b.runKernelFunc(l,h,null,$c,d);return g}const ym=m({cropAndResize_:zS});function HS(e){const t=u(e,"image","flipLeftRight","float32");f(t.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);const n={image:t},r=b.runKernel(Xc,n,{});return r}const Lm=m({flipLeftRight_:HS});function YS(e,t,n=0,r=.5){const o=u(e,"image","rotateWithOffset","float32");f(o.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${o.rank}.`);const i={image:o},a={radians:t,fillValue:n,center:r},s=b.runKernel(Ap,i,a);return s}const vm=m({rotateWithOffset_:YS});function yt(e,t,n,r,o,i){r==null&&(r=.5),o==null&&(o=Number.NEGATIVE_INFINITY),i==null&&(i=0);const a=e.shape[0];return n=Math.min(n,a),f(0<=r&&r<=1,()=>`iouThreshold must be in [0, 1], but was '${r}'`),f(e.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`),f(e.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`),f(t.rank===1,()=>"scores must be a 1D tensor"),f(t.shape[0]===a,()=>`scores has incompatible shape with boxes. Expected ${a}, but was ${t.shape[0]}`),f(0<=i&&i<=1,()=>`softNmsSigma must be in [0, 1], but was '${i}'`),{maxOutputSize:n,iouThreshold:r,scoreThreshold:o,softNmsSigma:i}}function VS(e,t,n,r=.5,o=Number.NEGATIVE_INFINITY){const i=u(e,"boxes","nonMaxSuppression"),a=u(t,"scores","nonMaxSuppression"),s=yt(i,a,n,r,o);n=s.maxOutputSize,r=s.iouThreshold,o=s.scoreThreshold;const c={maxOutputSize:n,iouThreshold:r,scoreThreshold:o};return b.runKernelFunc(p=>p.nonMaxSuppression(i,a,n,r,o),{boxes:i,scores:a},null,dp,c)}const Sm=m({nonMaxSuppression_:VS});function Im(e,t,n){const r=KS(e,t,n),o=r<0?-(r+1):r;e.splice(o,0,t)}function KS(e,t,n){return XS(e,t,n||JS)}function JS(e,t){return e>t?1:e<t?-1:0}function XS(e,t,n){let r=0,o=e.length,i=0,a=!1;for(;r<o;){i=r+(o-r>>>1);const s=n(t,e[i]);s>0?r=i+1:(o=i,a=!s)}return a?r:-r-1}function Ha(e,t,n,r,o){return vl(e,t,n,r,o,0).selectedIndices}function Ya(e,t,n,r,o,i){return vl(e,t,n,r,o,0,!1,i,!0)}function Va(e,t,n,r,o,i){return vl(e,t,n,r,o,i,!0)}function vl(e,t,n,r,o,i,a=!1,s=!1,c=!1){const p=[];for(let L=0;L<t.length;L++)t[L]>o&&p.push({score:t[L],boxIndex:L,suppressBeginIndex:0});p.sort(Tm);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:R}=L;if(S<o)break;let A=!1;for(let E=h.length-1;E>=R;--E){const F=ZS(e,I,h[E]);if(F>=r){A=!0;break}if(L.score=L.score*QS(r,l,F),L.score<=o)break}L.suppressBeginIndex=h.length,A||(L.score===S?(h.push(I),d.push(L.score)):L.score>o&&Im(p,L,Tm))}const g=h.length,x=n-g;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(g,"int32")),w}function ZS(e,t,n){const r=e.subarray(t*4,t*4+4),o=e.subarray(n*4,n*4+4),i=Math.min(r[0],r[2]),a=Math.min(r[1],r[3]),s=Math.max(r[0],r[2]),c=Math.max(r[1],r[3]),p=Math.min(o[0],o[2]),l=Math.min(o[1],o[3]),h=Math.max(o[0],o[2]),d=Math.max(o[1],o[3]),g=(s-i)*(c-a),x=(h-p)*(d-l);if(g<=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),R=Math.max(S-w,0)*Math.max(I-L,0);return R/(g+x-R)}function QS(e,t,n){const r=Math.exp(t*n*n);return n<=e?r:0}function Tm(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function eI(e,t,n,r=.5,o=Number.NEGATIVE_INFINITY){const i=u(e,"boxes","nonMaxSuppressionAsync"),a=u(t,"scores","nonMaxSuppressionAsync"),s=yt(i,a,n,r,o);n=s.maxOutputSize,r=s.iouThreshold,o=s.scoreThreshold;const c=await Promise.all([i.data(),a.data()]),p=c[0],l=c[1],h=Ha(p,l,n,r,o);return i!==e&&i.dispose(),a!==t&&a.dispose(),h}const Am=eI;function tI(e,t,n,r=.5,o=Number.NEGATIVE_INFINITY,i=0){const a=u(e,"boxes","nonMaxSuppression"),s=u(t,"scores","nonMaxSuppression"),c=yt(a,s,n,r,o,i);n=c.maxOutputSize,r=c.iouThreshold,o=c.scoreThreshold,i=c.softNmsSigma;const p={boxes:a,scores:s},l={maxOutputSize:n,iouThreshold:r,scoreThreshold:o,softNmsSigma:i},h=b.runKernel(fp,p,l);return{selectedIndices:h[0],selectedScores:h[1]}}const Nm=m({nonMaxSuppressionWithScore_:tI});async function nI(e,t,n,r=.5,o=Number.NEGATIVE_INFINITY,i=0){const a=u(e,"boxes","nonMaxSuppressionAsync"),s=u(t,"scores","nonMaxSuppressionAsync"),c=yt(a,s,n,r,o,i);n=c.maxOutputSize,r=c.iouThreshold,o=c.scoreThreshold,i=c.softNmsSigma;const p=await Promise.all([a.data(),s.data()]),l=p[0],h=p[1],d=Va(l,h,n,r,o,i);return a!==e&&a.dispose(),s!==t&&s.dispose(),d}const Rm=nI;function rI(e,t,n,r=.5,o=Number.NEGATIVE_INFINITY,i=!1){const a=u(e,"boxes","nonMaxSuppression"),s=u(t,"scores","nonMaxSuppression"),c=yt(a,s,n,r,o,null),p=c.maxOutputSize,l=c.iouThreshold,h=c.scoreThreshold,d={boxes:a,scores:s},g={maxOutputSize:p,iouThreshold:l,scoreThreshold:h,padToMaxOutputSize:i},x=b.runKernel(mp,d,g);return{selectedIndices:x[0],validOutputs:x[1]}}const _m=m({nonMaxSuppressionPadded_:rI});async function oI(e,t,n,r=.5,o=Number.NEGATIVE_INFINITY,i=!1){const a=u(e,"boxes","nonMaxSuppressionAsync"),s=u(t,"scores","nonMaxSuppressionAsync"),c=yt(a,s,n,r,o,null),p=c.maxOutputSize,l=c.iouThreshold,h=c.scoreThreshold,[d,g]=await Promise.all([a.data(),s.data()]),x=Ya(d,g,p,l,h,i);return a!==e&&a.dispose(),s!==t&&s.dispose(),x}const Cm=oI;function iI(e,t,n=!1){const r=u(e,"images","resizeBilinear");f(r.rank===3||r.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${r.rank}.`),f(t.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`);let o=r,i=!1;r.rank===3&&(i=!0,o=y(r,[1,r.shape[0],r.shape[1],r.shape[2]]));const[a,s]=t,c=(d,g)=>(g([o]),d.resizeBilinear(o,a,s,n)),p={images:o},l={alignCorners:n,size:t},h=b.runKernelFunc(c,p,null,Li,l);return i?y(h,[h.shape[1],h.shape[2],h.shape[3]]):h}const Em=m({resizeBilinear_:iI});function sI(e,t,n=!1){const r=u(e,"images","resizeNearestNeighbor");f(r.rank===3||r.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${r.rank}.`),f(t.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),f(r.dtype==="float32"||r.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype");let o=r,i=!1;r.rank===3&&(i=!0,o=y(r,[1,r.shape[0],r.shape[1],r.shape[2]]));const[a,s]=t,c={images:o},p={alignCorners:n,size:t},l=(d,g)=>(g([o]),d.resizeNearestNeighbor(o,a,s,n)),h=b.runKernelFunc(l,c,null,yi,p);return i?y(h,[h.shape[1],h.shape[2],h.shape[3]]):h}const Om=m({resizeNearestNeighbor_:sI});function aI(e,t,n){f(t%1===0,()=>`bandPart(): numLower must be an integer, got ${t}.`),f(n%1===0,()=>`bandPart(): numUpper must be an integer, got ${n}.`);const r=u(e,"a","bandPart");f(r.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${r.rank}.`);const o=r.shape,[i,a]=r.shape.slice(-2);if(!(t<=i))throw new Error(`bandPart(): numLower (${t}) must not be greater than the number of rows (${i}).`);if(!(n<=a))throw new Error(`bandPart(): numUpper (${n}) must not be greater than the number of columns (${a}).`);t<0&&(t=i),n<0&&(n=a);const s=y(fs(0,i,1,"int32"),[-1,1]),c=fs(0,a,1,"int32"),p=k(s,c),l=_t(bt(p,C(+t,"int32")),gt(p,C(-n,"int32"))),h=Ce([i,a],r.dtype);return y(Fe(Ae(y(r,[-1,i,a])).map(d=>De(l,d,h))),o)}const km=m({bandPart_:aI});function cI(e){let t;if(Array.isArray(e)){t=!1,f(e!=null&&e.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");const o=e[0].shape[0];for(let i=1;i<e.length;++i)f(e[i].shape[0]===o,()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[i].shape[0]} vs. ${o})`)}else t=!0,e=Qt(e,e.shape[0],0).map(o=>Gr(o,[0]));f(e.length<=e[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`);const n=[],r=e;for(let o=0;o<e.length;++o)n.push(b.tidy(()=>{let i=r[o];if(o>0)for(let a=0;a<o;++a){const s=v(W(v(n[a],i)),n[a]);i=k(i,s)}return D(i,gs(i,"euclidean"))}));return t?Fe(n,0):n}const Dm=m({gramSchmidt_:cI});function pI(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 Fm(e,t);{const n=e.shape.slice(0,e.shape.length-2).reduce((c,p)=>c*p),r=Ae(y(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),o=[],i=[];r.forEach(c=>{const[p,l]=Fm(c,t);o.push(p),i.push(l)});const a=y(Fe(o,0),e.shape),s=y(Fe(i,0),e.shape);return[a,s]}}function Fm(e,t=!1){return b.tidy(()=>{f(e.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`);const n=e.shape[0],r=e.shape[1];let o=va(n),i=dt(e);const a=wt([[1]],[1,1]);let s=dt(a);const c=n>=r?r:n;for(let p=0;p<c;++p){const l=i,h=s,d=o;[s,i,o]=b.tidy(()=>{const g=P(i,[p,p],[n-p,1]),x=gs(g),w=P(i,[p,p],[1,1]),L=De(rt(w,0),wt([[-1]]),wt([[1]])),S=k(w,v(L,x)),I=D(g,S);I.shape[0]===1?s=dt(a):s=Z([a,P(I,[1,0],[I.shape[0]-1,I.shape[1]])],0);const R=re(D(V(L,S),x)),A=P(i,[p,0],[n-p,r]),E=v(R,s),F=K(s);if(p===0)i=k(A,V(E,V(F,A)));else{const $=k(A,V(E,V(F,A)));i=Z([P(i,[0,0],[p,r]),$],0)}const M=K(E),j=P(o,[0,p],[n,o.shape[1]-p]);if(p===0)o=k(j,V(V(j,s),M));else{const $=k(j,V(V(j,s),M));o=Z([P(o,[0,0],[n,p]),$],1)}return[s,i,o]}),Le([l,h,d])}return!t&&n>r&&(o=P(o,[0,0],[n,r]),i=P(i,[0,0],[r,r])),[o,i]})}const Mm=m({qr_:pI});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 lI(e,t,n=be.SUM_BY_NONZERO_WEIGHTS){const r=u(e,"losses","computeWeightedLoss");let o=null;t!=null&&(o=u(t,"weights","computeWeightedLoss"));const i=o==null?r:v(r,o);if(n===be.NONE)return i;if(n===be.SUM)return W(i);if(n===be.MEAN){if(o==null)return Un(i);{const a=r.size/o.size,s=D(W(i),W(o));return a>1?D(s,C(a)):s}}if(n===be.SUM_BY_NONZERO_WEIGHTS){if(o==null)return D(W(i),C(r.size));{const a=v(o,Ct(r.shape)),s=_(W(Mr(a,C(0))),"float32");return D(W(i),s)}}throw Error(`Unknown reduction: ${n}`)}const $e=m({computeWeightedLoss_:lI});function hI(e,t,n,r=be.SUM_BY_NONZERO_WEIGHTS){const o=u(e,"labels","absoluteDifference"),i=u(t,"predictions","absoluteDifference");let a=null;n!=null&&(a=u(n,"weights","absoluteDifference")),G(o.shape,i.shape,"Error in absoluteDifference: ");const s=Oe(k(o,i));return $e(s,a,r)}const Um=m({absoluteDifference_:hI});function uI(e,t,n,r,o=be.SUM_BY_NONZERO_WEIGHTS){const i=u(e,"labels","cosineDistance"),a=u(t,"predictions","cosineDistance");let s=null;r!=null&&(s=u(r,"weights","cosineDistance")),G(i.shape,a.shape,"Error in cosineDistance: ");const c=C(1),p=k(c,W(v(i,a),n,!0));return $e(p,s,o)}const Wm=m({cosineDistance_:uI});function dI(e,t,n,r=be.SUM_BY_NONZERO_WEIGHTS){let o=u(e,"labels","hingeLoss");const i=u(t,"predictions","hingeLoss");let a=null;n!=null&&(a=u(n,"weights","hingeLoss")),G(o.shape,i.shape,"Error in hingeLoss: ");const s=C(1);o=k(v(C(2),o),s);const c=ie(k(s,v(o,i)));return $e(c,a,r)}const Bm=m({hingeLoss_:dI});function mI(e,t,n,r=1,o=be.SUM_BY_NONZERO_WEIGHTS){const i=u(e,"labels","huberLoss"),a=u(t,"predictions","huberLoss");let s=null;n!=null&&(s=u(n,"weights","huberLoss")),G(i.shape,a.shape,"Error in huberLoss: ");const c=C(r),p=Oe(k(a,i)),l=Fr(p,c),h=k(p,l),d=N(v(C(.5),z(l)),v(c,h));return $e(d,s,o)}const $m=m({huberLoss_:mI});function fI(e,t,n,r=1e-7,o=be.SUM_BY_NONZERO_WEIGHTS){const i=u(e,"labels","logLoss"),a=u(t,"predictions","logLoss");let s=null;n!=null&&(s=u(n,"weights","logLoss")),G(i.shape,a.shape,"Error in logLoss: ");const c=C(1),p=C(r),l=re(v(i,Rt(N(a,p)))),h=v(k(c,i),Rt(N(k(c,a),p))),d=k(l,h);return $e(d,s,o)}const jm=m({logLoss_:fI});function gI(e,t,n,r=be.SUM_BY_NONZERO_WEIGHTS){const o=u(e,"labels","meanSquaredError"),i=u(t,"predictions","meanSquaredError");let a=null;n!=null&&(a=u(n,"weights","meanSquaredError")),G(o.shape,i.shape,"Error in meanSquaredError: ");const s=jr(o,i);return $e(s,a,r)}const Gm=m({meanSquaredError_:gI});function bI(e,t){const n=u(e,"labels","sigmoidCrossEntropyWithLogits"),r=u(t,"logits","sigmoidCrossEntropyWithLogits");G(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");const o=ie(r),i=v(r,n),a=Ia(Te(re(Oe(r))));return N(k(o,i),a)}function wI(e,t,n,r=0,o=be.SUM_BY_NONZERO_WEIGHTS){let i=u(e,"multiClassLabels","sigmoidCrossEntropy");const a=u(t,"logits","sigmoidCrossEntropy");let s=null;if(n!=null&&(s=u(n,"weights","sigmoidCrossEntropy")),G(i.shape,a.shape,"Error in sigmoidCrossEntropy: "),r>0){const p=C(r),l=C(1),h=C(.5);i=N(v(i,k(l,p)),v(h,p))}const c=bI(i,a);return $e(c,s,o)}const Pm=m({sigmoidCrossEntropy_:wI});function xI(e,t,n=-1){if(n===-1&&(n=t.rank-1),n!==t.rank-1)throw Error(`Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank ${t.rank} and dim was ${n}`);const r=ze((o,i,a)=>{const s=!0,c=Na(i,[n],s),p=k(_(i,"float32"),c);a([o,p]);const l=re(v(p,o)),h=W(l,[n]),d=(g,x)=>{const[w,L]=x,S=we(g.shape,[n]);return[v(y(g,S),k(_(w,"float32"),Te(L))),v(y(g,S),k(Te(L),_(w,"float32")))]};return{value:h,gradFunc:d}});return r(e,t)}function yI(e,t,n,r=0,o=be.SUM_BY_NONZERO_WEIGHTS){let i=u(e,"onehotLabels","softmaxCrossEntropy");const a=u(t,"logits","softmaxCrossEntropy");let s=null;if(n!=null&&(s=u(n,"weights","softmaxCrossEntropy")),G(i.shape,a.shape,"Error in softmaxCrossEntropy: "),r>0){const p=C(r),l=C(1),h=C(i.shape[1]);i=N(v(i,k(l,p)),D(p,h))}const c=xI(i,a);return $e(c,s,o)}const qm=m({softmaxCrossEntropy_:yI});const LI={fft:Br,ifft:Wn,rfft:$r,irfft:Wa},vI={hammingWindow:wm,hannWindow:qa,frame:za,stft:xm},Sl={flipLeftRight:Lm,resizeNearestNeighbor:Om,resizeBilinear:Em,rotateWithOffset:vm,cropAndResize:ym,nonMaxSuppression:Sm,nonMaxSuppressionAsync:Am,nonMaxSuppressionWithScore:Nm,nonMaxSuppressionWithScoreAsync:Rm,nonMaxSuppressionPadded:_m,nonMaxSuppressionPaddedAsync:Cm},SI={bandPart:km,gramSchmidt:Dm,qr:Mm},II={absoluteDifference:Um,computeWeightedLoss:$e,cosineDistance:Wm,hingeLoss:Bm,huberLoss:$m,logLoss:jm,meanSquaredError:Gm,sigmoidCrossEntropy:Pm,softmaxCrossEntropy:qm};class ot extends sl{minimize(e,t=!1,n){const{value:r,grads:o}=this.computeGradients(e,n);if(n!=null){const i=n.map(a=>({name:a.name,tensor:o[a.name]}));this.applyGradients(i)}else this.applyGradients(o);return Le(o),t?r:(r.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return wl(e,t)}dispose(){this.iterations_!=null&&Le(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(ot,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});class Pn extends ot{constructor(e,t,n=null){super();this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],n==null&&(this.epsilon=b.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);t.forEach((n,r)=>{const o=b.registeredVariables[n],i=!1;this.accumulatedGrads[r]==null&&(this.accumulatedGrads[r]={originalName:`${n}/accum_grad`,variable:O(()=>B(o).variable(i))}),this.accumulatedUpdates[r]==null&&(this.accumulatedUpdates[r]={originalName:`${n}/accum_var`,variable:O(()=>B(o).variable(i))});const a=Array.isArray(e)?e[r].tensor:e[n];if(a==null)return;const s=this.accumulatedGrads[r].variable,c=this.accumulatedUpdates[r].variable;O(()=>{const p=N(v(s,this.rho),v(z(a),1-this.rho)),l=v(D(ge(N(c,this.epsilon)),ge(N(s,this.epsilon))),a),h=N(v(c,this.rho),v(z(l),1-this.rho));s.assign(p),c.assign(h);const d=N(v(l,-this.learningRate),o);o.assign(d)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(Le(this.accumulatedGrads.map(e=>e.variable)),Le(this.accumulatedUpdates.map(e=>e.variable)))}async getWeights(){const e=[...this.accumulatedGrads,...this.accumulatedUpdates];return[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e);const t=e.length/2,n=!1;this.accumulatedGrads=e.slice(0,t).map(r=>({originalName:r.name,variable:r.tensor.variable(n)})),this.accumulatedUpdates=e.slice(t,t*2).map(r=>({originalName:r.name,variable:r.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}}Pn.className="Adadelta";Ze(Pn);class qn extends ot{constructor(e,t=.1){super();this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);t.forEach((n,r)=>{const o=b.registeredVariables[n];if(this.accumulatedGrads[r]==null){const s=!1;this.accumulatedGrads[r]={originalName:`${n}/accumulator`,variable:O(()=>qe(o.shape,this.initialAccumulatorValue).variable(s))}}const i=Array.isArray(e)?e[r].tensor:e[n];if(i==null)return;const a=this.accumulatedGrads[r].variable;O(()=>{const s=N(a,z(i));a.assign(s);const c=N(v(D(i,ge(N(s,b.backend.epsilon()))),-this.learningRate),o);o.assign(c)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&Le(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)}}qn.className="Adagrad";Ze(qn);class zn extends ot{constructor(e,t,n,r=null){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=r,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],O(()=>{this.accBeta1=C(t).variable(),this.accBeta2=C(n).variable()}),r==null&&(this.epsilon=b.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);O(()=>{const n=k(1,this.accBeta1),r=k(1,this.accBeta2);t.forEach((o,i)=>{const a=b.registeredVariables[o],s=!1;this.accumulatedFirstMoment[i]==null&&(this.accumulatedFirstMoment[i]={originalName:`${o}/m`,variable:O(()=>B(a).variable(s))}),this.accumulatedSecondMoment[i]==null&&(this.accumulatedSecondMoment[i]={originalName:`${o}/v`,variable:O(()=>B(a).variable(s))});const c=Array.isArray(e)?e[i].tensor:e[o];if(c==null)return;const p=this.accumulatedFirstMoment[i].variable,l=this.accumulatedSecondMoment[i].variable,h=N(v(p,this.beta1),v(c,1-this.beta1)),d=N(v(l,this.beta2),v(z(c),1-this.beta2)),g=D(h,n),x=D(d,r);p.assign(h),l.assign(d);const w=N(v(D(g,N(ge(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&&Le(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&Le(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),O(()=>{this.accBeta1.assign(Qe(this.beta1,this.iterations_+1)),this.accBeta2.assign(Qe(this.beta2,this.iterations_+1))});const t=e.length/2,n=!1;this.accumulatedFirstMoment=e.slice(0,t).map(r=>({originalName:r.name,variable:r.tensor.variable(n)})),this.accumulatedSecondMoment=e.slice(t,t*2).map(r=>({originalName:r.name,variable:r.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)}}zn.className="Adam";Ze(zn);class Hn extends ot{constructor(e,t,n,r=null,o=0){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=r,this.decay=o,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],O(()=>{this.iteration=C(0).variable(),this.accBeta1=C(t).variable()}),r==null&&(this.epsilon=b.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);O(()=>{const n=k(1,this.accBeta1),r=D(-this.learningRate,N(v(this.iteration,this.decay),1));t.forEach((o,i)=>{const a=b.registeredVariables[o],s=!1;this.accumulatedFirstMoment[i]==null&&(this.accumulatedFirstMoment[i]={originalName:`${o}/m`,variable:B(a).variable(s)}),this.accumulatedWeightedInfNorm[i]==null&&(this.accumulatedWeightedInfNorm[i]={originalName:`${o}/v`,variable:B(a).variable(s)});const c=Array.isArray(e)?e[i].tensor:e[o];if(c==null)return;const p=this.accumulatedFirstMoment[i].variable,l=this.accumulatedWeightedInfNorm[i].variable,h=N(v(p,this.beta1),v(c,1-this.beta1)),d=v(l,this.beta2),g=Oe(c),x=Pt(d,g);p.assign(h),l.assign(x);const w=N(v(D(r,n),D(h,N(x,this.epsilon))),a);a.assign(w)}),this.iteration.assign(N(this.iteration,1)),this.accBeta1.assign(v(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&Le(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&Le(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)}}Hn.className="Adamax";Ze(Hn);class en extends ot{constructor(e){super();this.learningRate=e,this.setLearningRate(e)}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);t.forEach((n,r)=>{const o=Array.isArray(e)?e[r].tensor:e[n];if(o==null)return;const i=b.registeredVariables[n];O(()=>{const a=N(v(this.c,o),i);i.assign(a)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=ll(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)}}en.className="SGD";Ze(en);class Yn extends en{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,r)=>{const o=b.registeredVariables[n];if(this.accumulations[r]==null){const s=!1;this.accumulations[r]={originalName:`${n}/momentum`,variable:O(()=>B(o).variable(s))}}const i=this.accumulations[r].variable,a=Array.isArray(e)?e[r].tensor:e[n];if(a==null)return;O(()=>{let s;const c=N(v(this.m,i),a);this.useNesterov?s=N(v(this.c,N(a,v(c,this.m))),o):s=N(v(this.c,c),o),i.assign(c),o.assign(s)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&Le(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)}}Yn.className="Momentum";Ze(Yn);class Vn extends ot{constructor(e,t=.9,n=0,r=null,o=!1){super();if(this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=r,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=o,r==null&&(this.epsilon=b.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);t.forEach((n,r)=>{const o=b.registeredVariables[n],i=!1;this.accumulatedMeanSquares[r]==null&&(this.accumulatedMeanSquares[r]={originalName:`${n}/rms`,variable:O(()=>B(o).variable(i))}),this.accumulatedMoments[r]==null&&(this.accumulatedMoments[r]={originalName:`${n}/momentum`,variable:O(()=>B(o).variable(i))}),this.accumulatedMeanGrads[r]==null&&this.centered&&(this.accumulatedMeanGrads[r]={originalName:`${n}/mg`,variable:O(()=>B(o).variable(i))});const a=Array.isArray(e)?e[r].tensor:e[n];if(a==null)return;const s=this.accumulatedMeanSquares[r].variable,c=this.accumulatedMoments[r].variable;O(()=>{const p=N(v(s,this.decay),v(z(a),1-this.decay));if(this.centered){const l=this.accumulatedMeanGrads[r].variable,h=N(v(l,this.decay),v(a,1-this.decay)),d=D(v(a,this.learningRate),ge(k(p,N(z(h),this.epsilon)))),g=N(v(c,this.momentum),d);s.assign(p),l.assign(h),c.assign(g);const x=k(o,g);o.assign(x)}else{const l=N(v(s,this.decay),v(z(a),1-this.decay)),h=N(v(c,this.momentum),D(v(a,this.learningRate),ge(N(l,this.epsilon))));s.assign(l),c.assign(h);const d=k(o,h);o.assign(d)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&Le(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&Le(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&Le(this.accumulatedMoments.map(e=>e.variable))}async getWeights(){const e=[...this.accumulatedMeanSquares,...this.accumulatedMoments];return this.centered&&e.push(...this.accumulatedMeanGrads),[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e);const t=this.centered?e.length/3:e.length/2,n=!1;this.accumulatedMeanSquares=e.slice(0,t).map(r=>({originalName:r.name,variable:r.tensor.variable(n)})),this.accumulatedMoments=e.slice(t,t*2).map(r=>({originalName:r.name,variable:r.tensor.variable(n)})),this.centered&&(this.accumulatedMeanGrads=e.slice(t*2,t*3).map(r=>({originalName:r.name,variable:r.tensor.variable(n)})))}getConfig(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}}static fromConfig(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)}}Vn.className="RMSProp";Ze(Vn);class vn{static sgd(e){return new en(e)}static momentum(e,t,n=!1){return new Yn(e,t,n)}static rmsprop(e,t=.9,n=0,r=null,o=!1){return new Vn(e,t,n,r,o)}static adam(e=.001,t=.9,n=.999,r=null){return new zn(e,t,n,r)}static adadelta(e=.001,t=.95,n=null){return new Pn(e,t,n)}static adamax(e=.002,t=.9,n=.999,r=null,o=0){return new Hn(e,t,n,r,o)}static adagrad(e,t=.1){return new qn(e,t)}}Yn,en,Pn,qn,Vn,Hn,zn;const TI={sgd:vn.sgd,momentum:vn.momentum,adadelta:vn.adadelta,adagrad:vn.adagrad,rmsprop:vn.rmsprop,adamax:vn.adamax,adam:vn.adam};const AI=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:e=>e())();function NI(){return new Promise(e=>AI(()=>e()))}function RI(e,t,n){const r=n*(typeof e=="number"?e:e[0]),o=t*(typeof e=="number"?e:e[1]);return[r,o]}function _I(e,t,n,r=!0){let o=[];if(r)o=o.concat(t.slice(0)),o.push(e[0]/n),o=o.concat(e.slice(1));else{o=o.concat(e[0]);const i=t.length;for(let a=0;a<i;++a)o=o.concat([e[a+1]/t[a],t[a]]);o=o.concat(e.slice(i+1))}return o}function CI(e,t,n=!0){const r=[];if(n){r.push(t);for(let o=t+1;o<e;++o)o<=2*t?(r.push(o),r.push(o-(t+1))):r.push(o)}else{const o=[],i=[];for(let a=1;a<e;++a)a>=t*2+1||a%2===1?i.push(a):o.push(a);r.push(...o),r.push(0),r.push(...i)}return r}function EI(e,t,n,r=!0){const o=[];r?o.push(e[0]/n):o.push(e[0]*n);for(let i=1;i<e.length;++i)i<=t.length?r?o.push(t[i-1]*e[i]):o.push(e[i]/t[i-1]):o.push(e[i]);return o}function OI(e,t){const n=[0];for(let r=0;r<t;++r)n.push(e[r][0]);return n}function kI(e,t,n){const r=e.slice(0,1);for(let o=0;o<n;++o)r.push(e[o+1]-t[o][0]-t[o][1]);return r}const Il=1.7580993408473768,Tl=1.0507009873554805;const DI=.3275911,FI=.254829592,MI=-.284496736,UI=1.421413741,WI=-1.453152027,BI=1.061405429;function $I(...e){pe().getBool("IS_TEST")||console.warn(...e)}function jI(...e){pe().getBool("IS_TEST")||console.log(...e)}function GI(e,t){if(e.length!==t.length)throw new Error(`Cannot merge real and imag arrays of different lengths. real:${e.length}, imag: ${t.length}.`);const n=new Float32Array(e.length*2);for(let r=0;r<n.length;r+=2)n[r]=e[r/2],n[r+1]=t[r/2];return n}function PI(e){const t=new Float32Array(e.length/2),n=new Float32Array(e.length/2);for(let r=0;r<e.length;r+=2)t[r/2]=e[r],n[r/2]=e[r+1];return{real:t,imag:n}}function qI(e){const t=Math.ceil(e.length/4),n=new Float32Array(t),r=new Float32Array(t);for(let o=0;o<e.length;o+=4)n[Math.floor(o/4)]=e[o],r[Math.floor(o/4)]=e[o+1];return{real:n,imag:r}}function zI(e){const t=Math.floor(e.length/4),n=new Float32Array(t),r=new Float32Array(t);for(let o=2;o<e.length;o+=4)n[Math.floor(o/4)]=e[o],r[Math.floor(o/4)]=e[o+1];return{real:n,imag:r}}function HI(e,t){const n=e[t*2],r=e[t*2+1];return{real:n,imag:r}}function YI(e,t,n,r){e[r*2]=t,e[r*2+1]=n}function VI(e,t){const n=new Float32Array(e/2),r=new Float32Array(e/2);for(let o=0;o<Math.ceil(e/2);o++){const i=(t?2:-2)*Math.PI*(o/e);n[o]=Math.cos(i),r[o]=Math.sin(i)}return{real:n,imag:r}}function KI(e,t,n){const r=(n?2:-2)*Math.PI*(e/t),o=Math.cos(r),i=Math.sin(r);return{real:o,imag:i}}const zm={};_e(zm,{ERF_A1:()=>FI,ERF_A2:()=>MI,ERF_A3:()=>UI,ERF_A4:()=>WI,ERF_A5:()=>BI,ERF_P:()=>DI,PARALLELIZE_THRESHOLD:()=>Sa,SELU_SCALE:()=>Tl,SELU_SCALEALPHA:()=>Il,applyActivation:()=>jn,assertAndGetBroadcastShape:()=>q,assertAxesAreInnerMostDims:()=>Bx,assertParamsConsistent:()=>fl,assignToTypedArray:()=>YI,axesAreInnerMostDims:()=>hl,calculateShapes:()=>_u,castTensor:()=>JI,combineLocations:()=>qu,complexWithEvenIndex:()=>qI,complexWithOddIndex:()=>zI,computeConv2DInfo:()=>je,computeConv3DInfo:()=>bn,computeDefaultPad:()=>ml,computeDilation2DInfo:()=>Kx,computeOptimalWindowSize:()=>Yy,computeOutAndReduceShapes:()=>ul,computeOutShape:()=>gl,computePool2DInfo:()=>Nt,computePool3DInfo:()=>Xt,convertConv2DDataFormat:()=>gn,eitherStridesOrDilationsAreOne:()=>le,expandShapeToKeepDim:()=>we,exponent:()=>KI,exponents:()=>VI,getAxesPermutation:()=>fe,getBroadcastDims:()=>ky,getComplexWithIndex:()=>HI,getFusedBiasGradient:()=>$n,getFusedDyActivation:()=>Bn,getImageCenter:()=>RI,getInnerMostAxes:()=>ke,getPermuted:()=>CI,getReductionAxes:()=>ae,getReshaped:()=>_I,getReshapedPermuted:()=>EI,getSliceBeginCoords:()=>OI,getSliceSize:()=>kI,getUndoAxesPermutation:()=>Fn,linspaceImpl:()=>ZI,log:()=>jI,mergeRealAndImagArrays:()=>GI,prepareAndValidate:()=>Nu,prepareSplitSize:()=>yl,reshapeTensor:()=>XI,segment_util:()=>vd,shouldFuse:()=>Gn,slice_util:()=>nl,splitRealAndImagArrays:()=>PI,tupleValuesAreOne:()=>ct,upcastType:()=>xr,validateInput:()=>ma,validateUpdateShape:()=>tl,warn:()=>$I});function JI(e,t,n){if(t==="complex64"){if(e.dtype==="complex64")return e.clone();const r=Ce(e.shape),o=_(e,"float32"),i=n.complex(o,r);return r.dispose(),o.dispose(),i}if(!kp(e.dtype,t))return b.makeTensorFromDataId(e.dataId,e.shape,t);if(e.dtype==="complex64"){const r=n.real(e),o=_(r,t);return r.dispose(),o}if(t==="int32")return n.int(e);if(t==="bool"){const r=C(0,e.dtype),o=n.notEqual(e,r);return r.dispose(),o}else throw new Error(`Error in Cast: failed to cast ${e.dtype} to ${t}`)}function XI(e,t){return b.makeTensorFromDataId(e.dataId,t,e.dtype)}function ZI(e,t,n){const r=(t-e)/(n-1),o=Wt(n,"float32");o[0]=e;for(let i=1;i<o.length;i++)o[i]=o[i-1]+r;return ce(o,"float32")}function Hm(e,t,n){const r=new Array(e.rank).fill(0),o=e.shape.slice();return t.map(i=>{const a=[...o];a[n]=i;const s=P(e,r,a);return r[n]+=i,s})}function Ym(e,t){const n=new Array(e.rank);for(let o=0;o<n.length;o++)n[o]=e.shape[o]*t[o];const r=Ee(n,e.dtype);for(let o=0;o<r.values.length;++o){const i=r.indexToLoc(o),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);r.values[o]=e.values[s]}return r.toTensor()}function Vm(e,t,n,r,o){const i=t[t.length-1],[a,s]=[e.length/i,i],c=mr(n,a*r),p=mr("int32",a*r);for(let h=0;h<a;h++){const d=h*s,g=e.subarray(d,d+s),x=[];for(let I=0;I<g.length;I++)x.push({value:g[I],index:I});x.sort((I,R)=>R.value-I.value);const w=h*r,L=c.subarray(w,w+r),S=p.subarray(w,w+r);for(let I=0;I<r;I++)L[I]=x[I].value,S[I]=x[I].index}const l=t.slice();return l[l.length-1]=r,[Xe(c,l,n),Xe(p,l,"int32")]}const Km={};_e(Km,{nonMaxSuppressionV3Impl:()=>Ha,nonMaxSuppressionV4Impl:()=>Ya,nonMaxSuppressionV5Impl:()=>Va,split:()=>Hm,tile:()=>Ym,topkImpl:()=>Vm,whereImpl:()=>$a});const QI=1e-7,eT=1e-4;class tT{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 nT{time(e){return T("time")}read(e){return T("read")}readSync(e){return T("readSync")}numDataIds(){return T("numDataIds")}disposeData(e){return T("disposeData")}write(e,t,n){return T("write")}move(e,t,n,r){return T("move")}memory(){return T("memory")}floatPrecision(){return T("floatPrecision")}epsilon(){return this.floatPrecision()===32?QI:eT}batchMatMul(e,t,n,r){return T("batchMatMul")}fusedBatchMatMul({a:e,b:t,transposeA:n,transposeB:r,bias:o,activation:i,preluActivationWeights:a}){return T("fusedBatchMatMul")}slice(e,t,n){return T("slice")}stridedSlice(e,t,n,r){return T("stridedSlice")}unstack(e,t){return T("unstack")}reverse(e,t){return T("reverse")}concat(e,t){return T("concat")}neg(e){return T("neg")}add(e,t){return T("add")}addN(e){return T("addN")}subtract(e,t){return T("subtract")}multiply(e,t){return T("multiply")}realDivide(e,t){return T("realDivide")}floorDiv(e,t){return T("floorDiv")}sum(e,t){return T("sum")}prod(e,t){return T("prod")}unsortedSegmentSum(e,t,n){return T("unsortedSegmentSum")}argMin(e,t){return T("argMin")}argMax(e,t){return T("argMax")}equal(e,t){return T("equal")}notEqual(e,t){return T("notEqual")}less(e,t){return T("less")}lessEqual(e,t){return T("lessEqual")}greater(e,t){return T("greater")}greaterEqual(e,t){return T("greaterEqual")}logicalNot(e){return T("logicalNot")}logicalAnd(e,t){return T("logicalAnd")}logicalOr(e,t){return T("logicalOr")}where(e){return T("where")}select(e,t,n){return T("select")}topk(e,t,n){return T("topk")}min(e,t){return T("min")}minimum(e,t){return T("minimum")}mod(e,t){return T("mod")}max(e,t){return T("max")}maximum(e,t){return T("maximum")}all(e,t){return T("all")}any(e,t){return T("any")}squaredDifference(e,t){return T("squaredDifference")}ceil(e){return T("ceil")}floor(e){return T("floor")}round(e){return T("round")}sign(e){return T("sign")}isNaN(e){return T("isNaN")}isInf(e){return T("isInf")}isFinite(e){return T("isFinite")}pow(e,t){return T("pow")}exp(e){return T("exp")}expm1(e){return T("expm1")}softmax(e,t){return T("softmax")}log(e){return T("log")}log1p(e){return T("log1p")}sqrt(e){return T("sqrt")}rsqrt(e){return T("rsqrt")}square(e){return T("square")}reciprocal(e){return T("reciprocal")}relu(e){return T("relu")}relu6(e){return T("relu6")}prelu(e,t){return T("prelu")}elu(e){return T("elu")}eluDer(e,t){return T("eluDer")}selu(e){return T("selu")}int(e){return T("int")}clip(e,t,n){return T("clip")}abs(e){return T("abs")}complexAbs(e){return T("complexAbs")}sigmoid(e){return T("sigmoid")}softplus(e){return T("softplus")}sin(e){return T("sin")}cos(e){return T("cos")}tan(e){return T("tan")}asin(e){return T("asin")}acos(e){return T("acos")}atan(e){return T("atan")}atan2(e,t){return T("atan2")}sinh(e){return T("sinh")}cosh(e){return T("cosh")}tanh(e){return T("tanh")}asinh(e){return T("asinh")}acosh(e){return T("acosh")}atanh(e){return T("atanh")}erf(e){return T("erf")}step(e,t){return T("step")}fusedConv2d({input:e,filter:t,convInfo:n,bias:r,activation:o,preluActivationWeights:i}){return T("fusedConv2d")}conv2d(e,t,n){return T("conv2d")}conv2dDerInput(e,t,n){return T("conv2dDerInput")}conv2dDerFilter(e,t,n){return T("conv2dDerFilter")}fusedDepthwiseConv2D({input:e,filter:t,convInfo:n,bias:r,activation:o,preluActivationWeights:i}){return T("fusedDepthwiseConv2D")}depthwiseConv2D(e,t,n){return T("depthwiseConv2D")}depthwiseConv2DDerInput(e,t,n){return T("depthwiseConv2DDerInput")}depthwiseConv2DDerFilter(e,t,n){return T("depthwiseConv2DDerFilter")}conv3d(e,t,n){return T("conv3d")}conv3dDerInput(e,t,n){return T("conv3dDerInput")}conv3dDerFilter(e,t,n){return T("conv3dDerFilter")}maxPool(e,t){return T("maxPool")}maxPoolBackprop(e,t,n,r){return T("maxPoolBackprop")}avgPool(e,t){return T("avgPool")}avgPoolBackprop(e,t,n){return T("avgPoolBackprop")}avgPool3d(e,t){return T("avgPool3d")}avgPool3dBackprop(e,t,n){return T("avgPool3dBackprop")}maxPool3d(e,t){return T("maxPool3d")}maxPool3dBackprop(e,t,n,r){return T("maxPool3dBackprop")}reshape(e,t){return T("reshape")}cast(e,t){return T("cast")}tile(e,t){return T("tile")}pad(e,t,n){return T("pad")}transpose(e,t){return T("transpose")}gather(e,t,n){return T("gather")}gatherND(e,t){return T("gatherND")}scatterND(e,t,n){return T("scatterND")}batchToSpaceND(e,t,n){return T("batchToSpaceND")}spaceToBatchND(e,t,n){return T("spaceToBatchND")}resizeBilinear(e,t,n,r){return T("resizeBilinear")}resizeBilinearBackprop(e,t,n){return T("resizeBilinearBackprop")}resizeNearestNeighbor(e,t,n,r){return T("resizeNearestNeighbor")}resizeNearestNeighborBackprop(e,t,n){return T("resizeNearestNeighborBackprop")}batchNorm(e,t,n,r,o,i){return T("batchNorm")}localResponseNormalization4D(e,t,n,r,o){return T("localResponseNormalization4D")}LRNGrad(e,t,n,r,o,i,a){return T("LRNGrad")}multinomial(e,t,n,r){return T("multinomial")}oneHot(e,t,n,r){return T("oneHot")}cumsum(e,t,n,r){return T("cumsum")}nonMaxSuppression(e,t,n,r,o){return T("nonMaxSuppression")}fft(e){return T("fft")}ifft(e){return T("ifft")}complex(e,t){return T("complex")}real(e){return T("real")}imag(e){return T("imag")}cropAndResize(e,t,n,r,o,i){return T("cropAndResize")}depthToSpace(e,t,n){return T("depthToSpace")}split(e,t,n){return T("split")}sparseToDense(e,t,n,r){return T("sparseToDense")}diag(e){return T("diag")}fill(e,t,n){return T("fill")}onesLike(e){return T("onesLike")}zerosLike(e){return T("zerosLike")}linspace(e,t,n){return T("linspace")}dispose(){return T("dispose")}}function T(e){throw new Error(`'${e}' not yet implemented or not found in the registry. Did you forget to import the kernel?`)}const Jm={kernelName:ho,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(e,zt(_(n,"float32"),-1))}}};const Xm={kernelName:uo,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const r=z(_(n,"float32")),o=ge(k(C(1),r));return re(D(e,o))}}}};const Zm={kernelName:mo,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const r=ge(k(z(_(n,"float32")),1));return D(e,r)}}}};const Qm={kernelName:Cn,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,o=q(n.shape,r.shape),i=()=>{let s=e;const c=ae(n.shape,o);return c.length>0&&(s=W(s,c)),y(s,n.shape)},a=()=>{let s=e;const c=ae(r.shape,o);return c.length>0&&(s=W(s,c)),y(s,r.shape)};return{a:i,b:a}}};const ef={kernelName:fo,saveAllInputs:!0,gradFunc:(e,t)=>{const n={};return t.forEach((r,o)=>{n[o]=()=>e.clone()}),n}};const tf={kernelName:go,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>B(n)}}};const nf={kernelName:bo,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>B(n)}}};const rf={kernelName:wo,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>D(e,ge(k(C(1),z(_(n,"float32")))))}}};const of={kernelName:xo,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const r=ge(N(C(1),z(_(n,"float32"))));return D(e,r)}}}};const sf={kernelName:vo,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,o=q(n.shape,r.shape),i=()=>{const s=N(z(n),z(r));let c=v(e,D(r,s));const p=ae(n.shape,o);return p.length>0&&(c=W(c,p)),y(c,n.shape)},a=()=>{const s=N(z(n),z(r));let c=re(v(e,D(n,s)));const p=ae(r.shape,o);return p.length>0&&(c=W(c,p)),y(c,r.shape)};return{a:i,b:a}}};const af={kernelName:yo,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>D(e,N(z(_(n,"float32")),1))}}};const cf={kernelName:Lo,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>D(e,k(C(1),z(_(n,"float32"))))}}};function rT(e,t,n,r,o=[1,1,1],i,a){const s=u(e,"dy","avgPool3dBackprop"),c=u(t,"input","avgPool3dBackprop");let p=s,l=c,h=!1;c.rank===4&&(h=!0,p=y(s,[1,s.shape[0],s.shape[1],s.shape[2],s.shape[3]]),l=y(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]])),f(p.rank===5,()=>`Error in avgPool3dBackprop: dy must be rank 5 but got rank ${p.rank}.`),f(l.rank===5,()=>`Error in avgPool3dBackprop: input must be rank 5 but got rank ${l.rank}.`),f(le(r,o),()=>`Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides ${r} and dilations '${o}'`),a!=null&&f(X(i),()=>`Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode ${a} but got pad ${i}.`);const d=L=>{const S=Xt(l.shape,n,r,o,i,a);return L.avgPool3dBackprop(p,l,S)},g={dy:p,input:l},x={filterSize:n,strides:r,dilations:o,pad:i,dimRoundingMode:a},w=b.runKernelFunc(d,g,null,Fc,x);return h?y(w,[w.shape[1],w.shape[2],w.shape[3],w.shape[4]]):w}const pf=m({avgPool3dBackprop_:rT});const lf={kernelName:Io,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{filterSize:o,strides:i,dilations:a,pad:s,dimRoundingMode:c}=n,p=a==null?[1,1,1]:a;return{x:()=>pf(e,r,o,i,p,s,c)}}};function oT(e,t,n,r,o){const i=u(e,"dy","avgPoolBackprop"),a=u(t,"input","avgPoolBackprop");f(a.rank===i.rank,()=>`Rank of input (${a.rank}) does not match rank of dy (${i.rank})`);let s=a,c=i,p=!1;a.rank===3&&(p=!0,s=y(a,[1,a.shape[0],a.shape[1],a.shape[2]]),c=y(i,[1,i.shape[0],i.shape[1],i.shape[2]])),f(c.rank===4,()=>`Error in avgPoolBackprop: dy must be rank 4 but got rank ${c.rank}.`),f(s.rank===4,()=>`Error in avgPoolBackprop: input must be rank 4 but got rank ${s.rank}.`);const l=x=>{const w=Nt(s.shape,n,r,1,o);return x.avgPoolBackprop(c,s,w)},h={dy:c,input:s},d={filterSize:n,strides:r,pad:o},g=b.runKernelFunc(l,h,null,Dc,d);return p?y(g,[g.shape[1],g.shape[2],g.shape[3]]):g}const hf=m({avgPoolBackprop_:oT});const uf={kernelName:So,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{filterSize:o,strides:i,pad:a}=n;return{x:()=>hf(e,r,o,i,a)}}};const df={kernelName:To,inputsToSave:["a","b"],gradFunc:(e,t,n)=>{const[r,o]=t,{transposeA:i,transposeB:a}=n;return!i&&!a?{a:()=>V(e,o,!1,!0),b:()=>V(r,e,!0,!1)}:!i&&a?{a:()=>V(e,o,!1,!1),b:()=>V(e,r,!0,!1)}:i&&!a?{a:()=>V(o,e,!1,!0),b:()=>V(r,e,!1,!1)}:{a:()=>V(o,e,!0,!0),b:()=>V(e,r,!0,!0)}}};const mf={kernelName:Ao,gradFunc:(e,t,n)=>{const{blockShape:r,crops:o}=n;return{x:()=>Ur(e,r,o)}}};const ff={kernelName:No,gradFunc:(e,t,n)=>{const r=n,o=r.inputShape,i=r.shape,a=Array.from(i);for(let c=o.length-1;c>=0;c--)if(o[c]===i[c])a[c]=1;else if(o[c]!==1)throw new Error(`broadcastTo(): [${o}] cannot be broadcast to [${i}].`);const s=[];for(let c=0;c<a.length;c++)a[c]>1&&s.push(c);return{x:()=>W(e,s,!0)}}};const gf={kernelName:En,gradFunc:e=>({x:()=>e.clone()})};const bf={kernelName:Ro,gradFunc:e=>({x:()=>B(e)})};const wf={kernelName:_o,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{clipValueMin:o,clipValueMax:i}=n;return{x:()=>De(_t(gt(r,o),bt(r,i)),e,B(e))}}};const xf={kernelName:Co,saveAllInputs:!0,gradFunc:(e,t,n)=>{const r=t.map(c=>c.shape),{axis:o}=n,i=H(o,t[0].shape)[0],a=r.map(c=>c[i]),s=Qt(e,a,i);return s.map(c=>()=>c)}};const yf={kernelName:Eo,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[r,o]=t,{dilations:i,strides:a,pad:s,dataFormat:c}=n;return f(ct(i),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${i}'`),{x:()=>_r(r.shape,e,o,a,s,c),filter:()=>Pr(r,e,o.shape,a,s,c)}}};const Lf={kernelName:Oo,inputsToSave:["dy","filter"],gradFunc:(e,t,n)=>{const[r,o]=t,{strides:i,pad:a,dataFormat:s,dimRoundingMode:c}=n;return{dy:()=>ve(e,o,i,a,s,1,c),filter:()=>Pr(e,r,o.shape,i,a,s,c)}}};function iT(e,t,n,r,o){let i=e;e.rank===4&&(i=y(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let a=t;a.rank===4&&(a=y(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),f(i.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${i.shape}.`),f(a.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${a.shape}.`),f(n.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${n}.`),f(i.shape[4]===n[3],()=>`Error in conv3dDerFilter: depth of input ${i.shape[4]}) must match input depth in filter (${n[3]}.`),f(a.shape[4]===n[4],()=>`Error in conv3dDerFilter: depth of dy (${a.shape[4]}) must match output depth for filter (${n[4]}).`);const s=l=>{const h=1,d=bn(i.shape,n,r,h,o);return l.conv3dDerFilter(i,a,d)},c={x:i,y:a},p={strides:r,pad:o};return b.runKernelFunc(s,c,null,Wc,p)}const vf=m({conv3DBackpropFilter_:iT});const Sf={kernelName:ko,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:r,strides:o,pad:i}=n;f(ct(r),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${r}'`);const[a,s]=t;return{x:()=>wa(a.shape,e,s,o,i),filter:()=>vf(a,e,s.shape,o,i)}}};const If={kernelName:Do,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(re(Fa(_(n,"float32"))),e)}}};const Tf={kernelName:Fo,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(Ma(_(n,"float32")),e)}}};const Af={kernelName:Mo,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{axis:o,exclusive:i,reverse:a}=n;return{x:()=>{const s=fe([o],r.rank);let c=ya(e,o,i,!a);return s!=null&&(c=K(c,s)),c}}}};const Nf={kernelName:Uo,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:r,strides:o,pad:i,dimRoundingMode:a}=n,s=r==null?[1,1]:r;f(ct(s),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${s}'`);const[c,p]=t;f(c.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${c.rank}.`),f(p.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${p.rank}.`),f(c.shape[3]===p.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${c.shape[3]}) must match the inChannels dimension in filter ${p.shape[2]}.`),f(le(o,s),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${s}'.`),a!=null&&f(X(i),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${i}.`);const l=je(c.shape,p.shape,o,s,i,a,!0);return{x:()=>Pa(c.shape,e,p,l),filter:()=>Ga(c,e,p.shape,l)}}};const Rf={kernelName:Wo,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[r,o]=t,i={x:r,filter:o,dy:e},a={x:r,filter:o,dy:e};return{x:()=>b.runKernel(zc,i,n),filter:()=>b.runKernel(Hc,a,n)}}};const _f={kernelName:Bo,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,o=q(n.shape,r.shape),i=()=>{const s=D(e,_(r,"float32")),c=ae(n.shape,o);return c.length>0?y(W(s,c),n.shape):s},a=()=>{let s=v(e,_(n,"float32"));const c=ae(r.shape,o);c.length>0&&(s=y(W(s,c),r.shape));const p=z(r);return re(D(s,_(p,"float32")))};return{a:i,b:a}}};const Cf={kernelName:$o,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t,r=i=>i.eluDer(e,n),o={dy:e,y:n};return{x:()=>b.runKernelFunc(r,o,null,Yc)}}};const Ef={kernelName:jo,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,r=v(Te(re(z(n))),2/Math.sqrt(Math.PI));return{x:()=>v(e,r)}}};const Of={kernelName:Go,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(e,n)}}};const kf={kernelName:Po,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(e,Te(n))}}};const Df={kernelName:qo,gradFunc:e=>({x:()=>B(e)})};const Ff={kernelName:zo,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,o=q(n.shape,r.shape),i=()=>{const s=D(e,_(r,"float32")),c=ae(n.shape,o);return c.length>0?y(W(s,c),n.shape):s},a=()=>{let s=v(e,_(n,"float32"));const c=ae(r.shape,o);c.length>0&&(s=y(W(s,c),r.shape));const p=z(r);return re(D(s,_(p,"float32")))};return{a:i,b:a}}};const Mf={kernelName:Ho,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{const{varianceEpsilon:r}=n,[o,i,a,s]=t,c=s==null?C(1):s,p=ae(i.shape,o.shape),l=[];if(i.rank===1){for(let A=0;A<o.shape.length-1;++A)l.push(o.shape[A]);l.push(1)}const h=k(o,i),d=v(e,c),g=Da(N(a,C(r))),x=v(v(v(g,g),g),C(-.5)),w=()=>i.rank===1?y(v(v(e,Gt(y(g,[1,1,1,i.shape[0]]),l)),c),o.shape):y(v(v(e,g),c),o.shape),L=()=>{let A=v(v(g,C(-1)),d);return i.rank===1&&(A=W(A,p)),y(A,i.shape)},S=()=>{let A=v(v(x,h),d);return i.rank===1&&(A=W(A,p)),y(A,i.shape)},I=()=>{const A=v(h,g);let E=v(e,A);return i.rank===1&&(E=W(E,p)),y(E,i.shape)},R=()=>{let A=e;return i.rank===1&&(A=W(A,p)),y(A,i.shape)};return{x:w,mean:L,variance:S,scale:I,offset:R}}};const Bf={kernelName:Yo,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{const[r,o]=t,{axis:i}=n,a=H(i,r.shape)[0],s=()=>{const c=r.shape,p=o.size,l=c.slice(0,a),h=l.length,d=c.slice(i,c.length).slice(1),g=d.length,x=Uf(0,h),w=Uf(h+1,h+1+g),L=Wf([l,[p],d]),S=y(e,L),I=y(o,[p]),R=Wf([[h],x,w]),A=K(S,R);let E=Ba(A,I,r.shape[a]);const F=Fn(R);return E=K(E,F),E};return{x:s,indices:()=>o}}};function Uf(e,t){const n=[];for(let r=e;r<t;++r)n.push(r);return n}function Wf(e){const t=[];for(let n=0;n<e.length;++n)for(let r=0;r<e[n].length;++r)t.push(e[n][r]);return t}const $f={kernelName:Vo,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t;return{a:()=>B(n),b:()=>B(r)}}};const jf={kernelName:Ko,gradFunc:e=>({x:()=>_(e,"float32")})};const Gf={kernelName:Jo,gradFunc:e=>({x:()=>B(e)})};const Pf={kernelName:Xo,gradFunc:e=>({x:()=>B(e)})};const qf={kernelName:Zo,gradFunc:e=>({x:()=>B(e)})};const zf={kernelName:ei,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>D(e,N(n,1))}}};const Hf={kernelName:Qo,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>D(e,_(n,"float32"))}}};const Yf={kernelName:ti,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r]=t,{axis:o}=n;return{logits:()=>{const i=!0,a=Te(r);return k(e,v(W(e,o,i),a))}}}};function sT(e,t,n,r=5,o=1,i=1,a=.5){const s=l=>l.LRNGrad(n,e,t,r,o,i,a),c={x:e,y:t,dy:n},p={depthRadius:r,bias:o,alpha:i,beta:a};return b.runKernelFunc(s,c,null,cp,p)}const Vf=m({localResponseNormalizationBackprop_:sT});const Kf={kernelName:ni,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r,o]=t,{depthRadius:i,bias:a,alpha:s,beta:c}=n;return{x:()=>Vf(r,o,e,i,a,s,c)}}};function Ka(e,t,n,r,o){return t.rank<n.rank&&(t=y(t,we(t.shape,r))),e.rank<n.rank&&(e=y(e,we(e.shape,r))),{x:()=>{const i=v(e,_(xn(n,t),e.dtype));return o==null?i:K(i,o)}}}const Al={kernelName:ri,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const r=n,{reductionIndices:o}=r,[i,a]=t,s=H(o,i.shape),c=fe(s,i.rank),p=Ka(e,a,i,s,c);return{x:()=>{let l=p.x();return c!=null&&(l=K(l)),l}}}};const Jf={kernelName:oi,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,o=()=>v(e,_(gt(n,r),"float32")),i=()=>v(e,_(kr(n,r),"float32"));return{a:o,b:i}}};function aT(e,t,n,r,o,i=[1,1,1],a,s){const c=u(e,"dy","maxPool3dBackprop"),p=u(t,"input","maxPool3dBackprop"),l=u(n,"output","maxPool3dBackprop");let h=c,d=p,g=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]]),g=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(g.rank===5,()=>`Error in maxPool3dBackprop: output must be rank 5 but got rank ${g.rank}.`),f(le(o,i),()=>`Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides ${o} and dilations '${i}'`),s!=null&&f(X(a),()=>`Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode ${s} but got pad ${a}.`);const w=R=>{const A=Xt(d.shape,r,o,i,a,s);return R.maxPool3dBackprop(h,d,g,A)},L={dy:h,input:d,output:g},S={filterSize:r,strides:o,dilations:i,pad:a,dimRoundingMode:s},I=b.runKernelFunc(w,L,null,lp,S);return x?y(I,[I.shape[1],I.shape[2],I.shape[3],I.shape[4]]):I}const Xf=m({maxPool3dBackprop_:aT});const Zf={kernelName:si,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r,o]=t,{filterSize:i,strides:a,dilations:s,pad:c,dimRoundingMode:p}=n,l=s==null?[1,1,1]:s;return{x:()=>Xf(e,r,o,i,a,l,c,p)}}};function cT(e,t,n,r,o,i,a){const s=u(e,"dy","maxPoolBackprop"),c=u(t,"input","maxPoolBackprop"),p=u(n,"output","maxPoolBackprop");f(c.rank===s.rank,()=>`Rank of input (${c.rank}) does not match rank of dy (${s.rank})`),f(s.rank===4,()=>`Error in maxPoolBackprop: dy must be rank 4 but got rank ${s.rank}.`),f(c.rank===4,()=>`Error in maxPoolBackprop: input must be rank 4 but got rank ${c.rank}.`),a!=null&&f(X(i),()=>`Error in maxPoolBackprop: pad must be an integer when using, dimRoundingMode ${a} but got pad ${i}.`);const l=g=>{const x=Nt(c.shape,r,o,1,i,a);return g.maxPoolBackprop(s,c,p,x)},h={dy:s,input:c,output:p},d={filterSize:r,strides:o,pad:i,dimRoundingMode:a};return b.runKernelFunc(l,h,null,pp,d)}const Qf=m({maxPoolBackprop_:cT});const eg={kernelName:ii,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r,o]=t,{filterSize:i,strides:a,pad:s}=n;return{x:()=>Qf(e,r,o,i,a,s)}}};const tg={kernelName:ai,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const r=n,{axis:o}=r,[i,a]=t,s=H(o,i.shape),c=fe(s,i.rank),p=Ka(e,a,i,s,c);return{x:()=>{let l=p.x();return c!=null&&(l=K(l)),l}}}};const ng={kernelName:ci,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,o=()=>v(e,_(bt(n,r),"float32")),i=()=>v(e,_(rt(n,r),"float32"));return{a:o,b:i}}};const rg={kernelName:pi,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,o=q(n.shape,r.shape),i=()=>{const s=ae(n.shape,o);return s.length>0?y(W(e,s),n.shape):e},a=()=>{const s=v(e,re(Er(D(n,r)))),c=ae(r.shape,o);return c.length>0?y(W(s,c),r.shape):s};return{a:i,b:a}}};const og={kernelName:li,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,o=q(n.shape,r.shape),i=()=>{const s=v(e,_(r,"float32")),c=ae(n.shape,o);return c.length>0?y(W(s,c),n.shape):s},a=()=>{const s=v(e,_(n,"float32")),c=ae(r.shape,o);return c.length>0?y(W(s,c),r.shape):s};return{a:i,b:a}}};const ig={kernelName:hi,gradFunc:e=>({x:()=>re(e)})};const sg={kernelName:di,inputsToSave:["indices"],gradFunc:(e,t)=>{const n=t[0];return{indices:()=>Ce(n.shape,"float32")}}};const ag={kernelName:ui,gradFunc:e=>({x:()=>B(e)})};const Nl={kernelName:mi,inputsToSave:["x"],gradFunc:(e,t,n)=>{const r=t[0],{paddings:o}=n,i=o.map(a=>a[0]);return{x:()=>P(e,i,r.shape)}}};const cg={kernelName:fi,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{const[n,r,o]=t,i=n,a=r,s=q(i.shape,a.shape),c=()=>{const l=_(a,"float32");let h=v(e,v(l,Qe(i,k(l,C(1)))));const d=ae(i.shape,s);return d.length>0&&(h=W(h,d)),y(h,i.shape)},p=()=>{const l=rt(i,0),h=De(l,Rt(i),B(i));let d=v(e,v(o,h));const g=ae(a.shape,s);return g.length>0&&(d=W(d,g)),y(d,a.shape)};return{a:c,b:p}}};const pg={kernelName:gi,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{const[n,r]=t,o=rt(n,0);return{x:()=>De(o,e,v(e,r)),alpha:()=>{let i=De(o,B(e),v(e,n));const a=ae(r.shape,e.shape);return a.length>0&&(i=W(i,a)),y(i,r.shape)}}}};const lg={kernelName:bi,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>D(e,re(z(n)))}}};const hg={kernelName:vi,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,r=v(bt(n,6),zt(n));return{x:()=>v(e,_(r,"float32"))}}};const ug={kernelName:wi,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(e,_(zt(n),"float32"))}}};const dg={kernelName:xi,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>y(e,n.shape)}}};const mg={kernelName:Li,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[r]=t,o=s=>{const{alignCorners:c}=n;return s.resizeBilinearBackprop(e,r,c)},i={images:r},a=()=>b.runKernelFunc(o,i,null,yp,n);return{images:a}}};const fg={kernelName:yi,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[r]=t,o=s=>{const{alignCorners:c}=n;return s.resizeNearestNeighborBackprop(e,r,c)},i={images:r},a=()=>b.runKernelFunc(o,i,null,xp,n);return{images:a}}};const gg={kernelName:Si,gradFunc:(e,t,n)=>{const{dims:r}=n,o=H(r,e.shape);return{x:()=>et(e,o)}}};const bg={kernelName:Ii,gradFunc:e=>({x:()=>B(e)})};const wg={kernelName:Ti,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>re(D(e,v(Qe(n,1.5),2)))}}};const xg={kernelName:Ai,inputsToSave:["condition"],gradFunc:(e,t)=>{const[n]=t;return{condition:()=>_(B(n),"float32"),t:()=>v(e,_(n,e.dtype)),e:()=>v(e,_(Dr(n),e.dtype))}}};const yg={kernelName:Ni,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const r=rt(n,C(0)),o=C(Il),i=C(Tl),a=v(e,i),s=v(v(e,o),Te(_(n,"float32")));return De(r,a,s)}}}};const Lg={kernelName:Oi,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(e,v(n,k(C(1),n)))}}};const vg={kernelName:Ei,gradFunc:e=>({x:()=>B(e)})};const Sg={kernelName:_i,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(Cr(_(n,"float32")),e)}}};const Ig={kernelName:Ci,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(xa(_(n,"float32")),e)}}};const Tg={kernelName:Ri,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{begin:o,size:i}=n,a=r.shape,[s,c]=ls(r,o,i),p=[];for(let l=0;l<e.rank;l++)p.push([s[l],a[l]-s[l]-c[l]]);return{x:()=>He(e,p)}}};const Ag={kernelName:Wi,outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r]=t,{dim:o}=n,i=!0,a=v(e,r);return{logits:()=>k(a,v(W(a,[o],i),r))}}};const Ng={kernelName:ki,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(e,ft(n))}}};const Rl={kernelName:Mi,gradFunc:(e,t,n)=>{const{blockShape:r,paddings:o}=n;return{x:()=>Nr(e,r,o)}}};const _l={kernelName:Ui,gradFunc:(e,t,n)=>{const{axis:r}=n;return{x:()=>Z(e,r)}}};const Rg={kernelName:Di,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>D(e,v(ge(_(n,"float32")),2))}}};const _g={kernelName:vp,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(e,v(_(n,"float32"),2))}}};const Cg={kernelName:Bi,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,o=C(2),i=()=>v(e,v(o,k(n,r))),a=()=>v(e,v(o,k(r,n)));return{a:i,b:a}}};const Eg={kernelName:Vi,gradFunc:e=>({x:()=>B(e)})};const Og={kernelName:$i,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,o=q(n.shape,r.shape),i=()=>{let s=e;const c=ae(n.shape,o);return c.length>0&&(s=W(s,c)),y(s,n.shape)},a=()=>{let s=e;const c=ae(r.shape,o);return c.length>0&&(s=W(s,c)),y(re(s),r.shape)};return{a:i,b:a}}};const kg={kernelName:Fi,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,o=r.shape.slice(),{axis:i}=n,a=H(i,r.shape);a.forEach(p=>{o[p]=1});const s=y(e,o),c=v(s,Ct(r.shape,"float32"));return{x:()=>c}}};const Dg={kernelName:ji,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>D(e,z(Cr(n)))}}};const Fg={kernelName:Gi,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>v(k(C(1),z(n)),e)}}};const Mg={kernelName:Pi,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{reps:o}=n,i=()=>{let a=B(r);if(r.rank===1)for(let s=0;s<o[0];++s)a=N(a,P(e,[s*r.shape[0]],[r.shape[0]]));else if(r.rank===2)for(let s=0;s<o[0];++s)for(let c=0;c<o[1];++c)a=N(a,P(e,[s*r.shape[0],c*r.shape[1]],[r.shape[0],r.shape[1]]));else if(r.rank===3)for(let s=0;s<o[0];++s)for(let c=0;c<o[1];++c)for(let p=0;p<o[2];++p)a=N(a,P(e,[s*r.shape[0],c*r.shape[1],p*r.shape[2]],[r.shape[0],r.shape[1],r.shape[2]]));else if(r.rank===4)for(let s=0;s<o[0];++s)for(let c=0;c<o[1];++c)for(let p=0;p<o[2];++p)for(let l=0;l<o[3];++l)a=N(a,P(e,[s*r.shape[0],c*r.shape[1],p*r.shape[2],l*r.shape[3]],[r.shape[0],r.shape[1],r.shape[2],r.shape[3]]));else throw new Error(`Gradient for tile operation is not implemented for rank-${r.rank} tensors yet.`);return a};return{x:i}}};const Ug={kernelName:qi,gradFunc:(e,t,n)=>{const r=n,{perm:o}=r,i=Fn(o);return{x:()=>K(e,i)}}};const Wg={kernelName:zi,gradFunc:(e,t,n)=>{const r=n,{axis:o}=r;return{value:()=>Fe(e,o)}}};const Bg={kernelName:Hi,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{const[n]=t,r=()=>pT(e,n);return{x:r}}};function pT(e,t){const n=Pt(t,B(t)),r=Or(e,n);let o=gt(t,C(0,"int32"));const i=r.rank-o.rank;for(let s=0;s<i;++s)o=nt(o,s+1);o=_t(o,Ct(r.shape,"bool"));const a=B(r);return De(o,r,a)}const $g={kernelName:Yi,gradFunc:e=>({x:()=>B(e)})};const lT=[Jm,Xm,Zm,Qm,ef,tf,nf,rf,of,sf,af,cf,lf,uf,df,mf,ff,gf,bf,wf,xf,Lf,yf,Sf,If,Tf,Af,Nf,Rf,_f,Cf,Ef,Of,kf,Ff,Df,Mf,Bf,$f,jf,Gf,Pf,qf,zf,Hf,Yf,Kf,Al,Al,Jf,Zf,eg,tg,ng,rg,og,ig,sg,ag,Nl,Nl,cg,pg,lg,hg,ug,dg,mg,fg,gg,bg,wg,xg,yg,Lg,vg,Sg,Ig,Tg,Ag,Ng,Rl,Rl,_l,_l,Rg,Cg,_g,Eg,Og,kg,Dg,Fg,Mg,Ug,Wg,Bg,$g];for(const e of lT)Rp(e);const Rs={};_e(Rs,{Abs:()=>ho,Acos:()=>uo,Acosh:()=>mo,AdadeltaOptimizer:()=>Pn,AdagradOptimizer:()=>qn,AdamOptimizer:()=>zn,AdamaxOptimizer:()=>Hn,Add:()=>Cn,AddN:()=>fo,All:()=>Oc,Any:()=>kc,ArgMax:()=>go,ArgMin:()=>bo,Asin:()=>wo,Asinh:()=>xo,Atan:()=>yo,Atan2:()=>vo,Atanh:()=>Lo,AvgPool:()=>So,AvgPool3D:()=>Io,AvgPool3DBackprop:()=>Fc,AvgPoolBackprop:()=>Dc,BatchMatMul:()=>To,BatchToSpaceND:()=>Ao,BroadcastTo:()=>No,Cast:()=>En,Ceil:()=>Ro,ClipByValue:()=>_o,Complex:()=>Mc,Concat:()=>Co,Conv2D:()=>Eo,Conv2DBackpropFilter:()=>Uc,Conv2DBackpropInput:()=>Oo,Conv3D:()=>ko,Conv3DBackpropFilterV2:()=>Wc,Conv3DBackpropInputV2:()=>Bc,Cos:()=>Do,Cosh:()=>Fo,CropAndResize:()=>$c,Cumsum:()=>Mo,DataStorage:()=>tT,DepthToSpace:()=>jc,DepthwiseConv2dNative:()=>Uo,DepthwiseConv2dNativeBackpropFilter:()=>Gc,DepthwiseConv2dNativeBackpropInput:()=>Pc,Diag:()=>qc,Dilation2D:()=>Wo,Dilation2DBackpropFilter:()=>Hc,Dilation2DBackpropInput:()=>zc,Div:()=>Bo,ENV:()=>Rc,Elu:()=>$o,EluGrad:()=>Yc,Environment:()=>Nc,Equal:()=>Vc,Erf:()=>jo,Exp:()=>Go,Expm1:()=>Po,FFT:()=>Kc,Fill:()=>Jc,FlipLeftRight:()=>Xc,Floor:()=>qo,FloorDiv:()=>zo,FromPixels:()=>na,FusedBatchNorm:()=>Ho,FusedConv2D:()=>oa,FusedDepthwiseConv2D:()=>ia,GatherNd:()=>Zc,GatherV2:()=>Yo,Greater:()=>Qc,GreaterEqual:()=>Vo,IFFT:()=>ep,Identity:()=>Ko,Imag:()=>tp,IsFinite:()=>Jo,IsInf:()=>Xo,IsNan:()=>Zo,KernelBackend:()=>nT,LRN:()=>ni,LRNBackprop:()=>cp,Less:()=>np,LessEqual:()=>rp,LinSpace:()=>op,Log:()=>Qo,Log1p:()=>ei,LogSoftmax:()=>ti,LogicalAnd:()=>ip,LogicalNot:()=>sp,LogicalOr:()=>ap,Max:()=>ri,MaxPool:()=>ii,MaxPool3D:()=>si,MaxPool3DBackprop:()=>lp,MaxPoolBackprop:()=>pp,MaxPoolWithArgmax:()=>hp,Maximum:()=>oi,Mean:()=>qb,Min:()=>ai,Minimum:()=>ci,Mod:()=>pi,MomentumOptimizer:()=>Yn,Multiply:()=>li,Negate:()=>hi,NonMaxSuppressionV3:()=>dp,NonMaxSuppressionV4:()=>mp,NonMaxSuppressionV5:()=>fp,NotEqual:()=>up,OP_SCOPE_SUFFIX:()=>Hp,OneHot:()=>di,OnesLike:()=>ui,Optimizer:()=>ot,PadV2:()=>mi,Pool:()=>zb,Pow:()=>fi,Prelu:()=>gi,Prod:()=>gp,RMSPropOptimizer:()=>Vn,Range:()=>bp,Rank:()=>Wp,Real:()=>wp,Reciprocal:()=>bi,Reduction:()=>be,Relu:()=>wi,Relu6:()=>vi,Reshape:()=>xi,ResizeBilinear:()=>Li,ResizeBilinearGrad:()=>yp,ResizeNearestNeighbor:()=>yi,ResizeNearestNeighborGrad:()=>xp,Reverse:()=>Si,RotateWithOffset:()=>Ap,Round:()=>Ii,Rsqrt:()=>Ti,SGDOptimizer:()=>en,ScatterNd:()=>Lp,SelectV2:()=>Ai,Selu:()=>Ni,Sigmoid:()=>Oi,Sign:()=>Ei,Sin:()=>_i,Sinh:()=>Ci,Slice:()=>Ri,Softmax:()=>Wi,Softplus:()=>ki,SpaceToBatchND:()=>Mi,SparseToDense:()=>Sp,SplitV:()=>Ui,Sqrt:()=>Di,Square:()=>vp,SquaredDifference:()=>Bi,Step:()=>Vi,StridedSlice:()=>Ip,Sub:()=>$i,Sum:()=>Fi,Tan:()=>ji,Tanh:()=>Gi,Tensor:()=>te,TensorBuffer:()=>br,Tile:()=>Pi,TopK:()=>Tp,Transpose:()=>qi,Unpack:()=>zi,UnsortedSegmentSum:()=>Hi,Variable:()=>$t,ZerosLike:()=>Yi,_FusedMatMul:()=>ra,abs:()=>Oe,acos:()=>ju,acosh:()=>Gu,add:()=>N,addN:()=>Pu,addStrict:()=>lS,all:()=>zu,any:()=>Hu,argMax:()=>Yu,argMin:()=>Vu,asin:()=>Ku,asinh:()=>Ju,atan:()=>Xu,atan2:()=>Zu,atanh:()=>Qu,avgPool:()=>mt,avgPool3d:()=>ed,backend:()=>_x,backend_util:()=>zm,basicLSTMCell:()=>td,batchNorm:()=>jt,batchNorm2d:()=>rd,batchNorm3d:()=>od,batchNorm4d:()=>id,batchToSpaceND:()=>Nr,booleanMaskAsync:()=>Gv,broadcastTo:()=>us,browser:()=>Ir,buffer:()=>Ee,cast:()=>_,ceil:()=>sd,clipByValue:()=>Rr,clone:()=>dt,complex:()=>Je,concat:()=>Z,concat1d:()=>ad,concat2d:()=>cd,concat3d:()=>pd,concat4d:()=>ld,conv1d:()=>hd,conv2d:()=>ve,conv2dTranspose:()=>ud,conv3d:()=>dd,conv3dTranspose:()=>md,cos:()=>Cr,cosh:()=>xa,cosineWindow:()=>bs,cumsum:()=>ya,customGrad:()=>ze,deprecationWarn:()=>ye,depthToSpace:()=>fd,depthwiseConv2d:()=>wn,device_util:()=>du,diag:()=>gd,dilation2d:()=>bd,disableDeprecationWarnings:()=>bx,dispose:()=>Le,disposeVariables:()=>wx,div:()=>D,divNoNan:()=>wd,divStrict:()=>hS,dot:()=>xd,dropout:()=>_S,elu:()=>La,enableDebugMode:()=>gx,enableProdMode:()=>fx,enclosingPowerOfTwo:()=>Ll,engine:()=>xx,env:()=>pe,equal:()=>xn,equalStrict:()=>Kv,erf:()=>yd,exp:()=>Te,expandDims:()=>nt,expm1:()=>Ld,eye:()=>va,fft:()=>Br,fill:()=>qe,findBackend:()=>Ax,findBackendFactory:()=>Nx,floor:()=>Er,floorDiv:()=>fa,fused:()=>bm,gather:()=>Or,gatherND:()=>NS,gather_util:()=>Au,getBackend:()=>wc,getGradient:()=>sa,getKernel:()=>Ji,getKernelsForBackend:()=>aa,grad:()=>lL,grads:()=>hL,greater:()=>rt,greaterEqual:()=>gt,greaterEqualStrict:()=>Jv,greaterStrict:()=>Xv,ifft:()=>Wn,imag:()=>yn,image:()=>Sl,inTopKAsync:()=>ES,io:()=>vr,irfft:()=>Wa,isFinite:()=>Sd,isInf:()=>Id,isNaN:()=>Td,keep:()=>ll,kernel_impls:()=>Km,leakyRelu:()=>Ad,less:()=>kr,lessEqual:()=>bt,lessEqualStrict:()=>Zv,lessStrict:()=>Qv,linalg:()=>SI,linspace:()=>Nd,localResponseNormalization:()=>Rd,log:()=>Rt,log1p:()=>Ia,logSigmoid:()=>_d,logSoftmax:()=>Cd,logSumExp:()=>Na,logicalAnd:()=>_t,logicalNot:()=>Dr,logicalOr:()=>Ra,logicalXor:()=>Ed,losses:()=>II,matMul:()=>V,math:()=>Tu,max:()=>qt,maxPool:()=>Re,maxPool3d:()=>Od,maxPoolWithArgmax:()=>kd,maximum:()=>Pt,maximumStrict:()=>uS,mean:()=>Un,memory:()=>yx,min:()=>ds,minimum:()=>Fr,minimumStrict:()=>dS,mod:()=>_a,modStrict:()=>mS,moments:()=>Dd,movingAverage:()=>LS,mul:()=>v,mulStrict:()=>fS,multiRNNCell:()=>Fd,multinomial:()=>Md,neg:()=>re,nextFrame:()=>NI,norm:()=>gs,notEqual:()=>Mr,notEqualStrict:()=>eS,oneHot:()=>cs,ones:()=>Ct,onesLike:()=>xl,op:()=>m,outerProduct:()=>Ud,pad:()=>He,pad1d:()=>Wd,pad2d:()=>Bd,pad3d:()=>$d,pad4d:()=>jd,pool:()=>Gd,pow:()=>Qe,powStrict:()=>gS,prelu:()=>Ca,print:()=>da,prod:()=>Pd,profile:()=>Lx,rand:()=>qd,randomGamma:()=>Yd,randomNormal:()=>Vd,randomUniform:()=>Oa,range:()=>fs,ready:()=>Ix,real:()=>Zt,reciprocal:()=>Kd,registerBackend:()=>Rx,registerGradient:()=>Rp,registerKernel:()=>Hb,relu:()=>ie,relu6:()=>ka,removeBackend:()=>Tx,reshape:()=>y,reverse:()=>et,reverse1d:()=>Jd,reverse2d:()=>Xd,reverse3d:()=>Zd,reverse4d:()=>Qd,rfft:()=>$r,round:()=>em,rsqrt:()=>Da,scalar:()=>C,scatterND:()=>SS,scatter_util:()=>Ru,selu:()=>tm,separableConv2d:()=>Wr,serialization:()=>Wu,setBackend:()=>Sx,setPlatform:()=>Cx,setdiff1dAsync:()=>nm,sigmoid:()=>ft,sign:()=>rm,signal:()=>vI,sin:()=>Fa,sinh:()=>Ma,slice:()=>P,slice1d:()=>om,slice2d:()=>im,slice3d:()=>Ua,slice4d:()=>sm,slice_util:()=>nl,softmax:()=>Ln,softplus:()=>Aa,spaceToBatchND:()=>Ur,sparseToDense:()=>TS,spectral:()=>LI,split:()=>Qt,sqrt:()=>ge,square:()=>z,squaredDifference:()=>jr,squaredDifferenceStrict:()=>bS,squeeze:()=>Gr,stack:()=>Fe,step:()=>zt,stridedSlice:()=>am,sub:()=>k,subStrict:()=>wS,sum:()=>W,sumOutType:()=>mw,tan:()=>cm,tanh:()=>hs,tensor:()=>Xe,tensor1d:()=>ce,tensor2d:()=>wt,tensor3d:()=>Sr,tensor4d:()=>xt,tensor5d:()=>pm,tensor6d:()=>lm,tensor_util:()=>lu,test_util:()=>Bu,tidy:()=>O,tile:()=>Gt,time:()=>vx,topk:()=>hm,train:()=>TI,transpose:()=>K,truncatedNormal:()=>um,unregisterGradient:()=>Vb,unregisterKernel:()=>Yb,unsortedSegmentSum:()=>Ba,unstack:()=>Ae,upcastType:()=>xr,util:()=>Kh,valueAndGrad:()=>uL,valueAndGrads:()=>dL,variable:()=>dm,variableGrads:()=>wl,version_core:()=>xc,where:()=>De,whereAsync:()=>ja,zeros:()=>Ce,zerosLike:()=>B});function tn(e,t,n=!1){if(e.beginPath(),t.slice(1).forEach(({x:r,y:o},i)=>{const a=t[i];e.moveTo(a.x,a.y),e.lineTo(r,o)}),n){const r=t[t.length-1],o=t[0];if(!r||!o)return;e.moveTo(r.x,r.y),e.lineTo(o.x,o.y)}e.stroke()}class Ke{constructor(e,t){if(!Et(e)||!Et(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 Ke(1/this.width,1/this.height)}}const Cs={};_e(Cs,{computeReshapedDimensions:()=>Ol,getCenterPoint:()=>Xn,isDimensions:()=>Xa,isEven:()=>Ja,isFloat:()=>El,isTensor:()=>Kn,isTensor1D:()=>hT,isTensor2D:()=>Cl,isTensor3D:()=>nn,isTensor4D:()=>pt,isValidNumber:()=>Et,isValidProbablitiy:()=>qr,range:()=>Ht,round:()=>Jn});function Kn(e,t){return e instanceof te&&e.shape.length===t}function hT(e){return Kn(e,1)}function Cl(e){return Kn(e,2)}function nn(e){return Kn(e,3)}function pt(e){return Kn(e,4)}function El(e){return e%1!==0}function Ja(e){return e%2===0}function Jn(e,t=2){const n=Math.pow(10,t);return Math.floor(e*n)/n}function Xa(e){return e&&e.width&&e.height}function Ol({width:e,height:t},n){const r=n/Math.max(t,e);return new Ke(Math.round(e*r),Math.round(t*r))}function Xn(e){return e.reduce((t,n)=>t.add(n),new J(0,0)).div(new J(e.length,e.length))}function Ht(e,t,n){return Array(e).fill(0).map((r,o)=>t+o*n)}function Et(e){return!!e&&e!==Infinity&&e!==-Infinity&&!isNaN(e)||e===0}function qr(e){return Et(e)&&0<=e&&e<=1}class J{constructor(e,t){this._x=e,this._y=t}get x(){return this._x}get y(){return this._y}add(e){return new J(this.x+e.x,this.y+e.y)}sub(e){return new J(this.x-e.x,this.y-e.y)}mul(e){return new J(this.x*e.x,this.y*e.y)}div(e){return new J(this.x/e.x,this.y/e.y)}abs(){return new J(Math.abs(this.x),Math.abs(this.y))}magnitude(){return Math.sqrt(Math.pow(this.x,2)+Math.pow(this.y,2))}floor(){return new J(Math.floor(this.x),Math.floor(this.y))}}class de{constructor(e,t=!0){const n=e||{},r=[n.left,n.top,n.right,n.bottom].every(Et),o=[n.x,n.y,n.width,n.height].every(Et);if(!o&&!r)throw new Error(`Box.constructor - expected box to be IBoundingBox | IRect, instead have ${JSON.stringify(n)}`);const[i,a,s,c]=o?[n.x,n.y,n.width,n.height]:[n.left,n.top,n.right-n.left,n.bottom-n.top];de.assertIsValidBox({x:i,y:a,width:s,height:c},"Box.constructor",t),this._x=i,this._y=a,this._width=s,this._height=c}static isRect(e){return!!e&&[e.x,e.y,e.width,e.height].every(Et)}static assertIsValidBox(e,t,n=!1){if(!de.isRect(e))throw new Error(`${t} - invalid box: ${JSON.stringify(e)}, expected object with properties x, y, width, height`);if(!n&&(e.width<0||e.height<0))throw new Error(`${t} - width (${e.width}) and height (${e.height}) must be positive numbers`)}get x(){return this._x}get y(){return this._y}get width(){return this._width}get height(){return this._height}get left(){return this.x}get top(){return this.y}get right(){return this.x+this.width}get bottom(){return this.y+this.height}get area(){return this.width*this.height}get topLeft(){return new J(this.left,this.top)}get topRight(){return new J(this.right,this.top)}get bottomLeft(){return new J(this.left,this.bottom)}get bottomRight(){return new J(this.right,this.bottom)}round(){const[e,t,n,r]=[this.x,this.y,this.width,this.height].map(o=>Math.round(o));return new de({x:e,y:t,width:n,height:r})}floor(){const[e,t,n,r]=[this.x,this.y,this.width,this.height].map(o=>Math.floor(o));return new de({x:e,y:t,width:n,height:r})}toSquare(){let{x:e,y:t,width:n,height:r}=this;const o=Math.abs(n-r);return n<r&&(e-=o/2,n+=o),r<n&&(t-=o/2,r+=o),new de({x:e,y:t,width:n,height:r})}rescale(e){const t=Xa(e)?e.width:e,n=Xa(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,r,o,i]=[this.x-e/2,this.y-t/2,this.width+e,this.height+t];return new de({x:n,y:r,width:o,height:i})}clipAtImageBorders(e,t){const{x:n,y:r,right:o,bottom:i}=this,a=Math.max(n,0),s=Math.max(r,0),c=o-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:r}=this,o=this.x+e,i=this.y+t;return new de({x:o,y:i,width:n,height:r})}padAtBorders(e,t){const n=this.width+1,r=this.height+1;let o=1,i=1,a=n,s=r,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+r,h=e),c<1&&(s=2-c,c=1),p<1&&(s=2-p,p=1),{dy:i,edy:s,dx:o,edx:a,y:p,ey:h,x:c,ex:l,w:n,h:r}}calibrate(e){return new de({left:this.left+e.left*this.width,top:this.top+e.top*this.height,right:this.right+e.right*this.width,bottom:this.bottom+e.bottom*this.height}).toSquare().round()}}class hr extends de{constructor(e,t,n,r,o=!1){super({left:e,top:t,right:n,bottom:r},o)}}class _n{constructor(e,t,n,r,o){this._imageDims=new Ke(o.width,o.height),this._score=e,this._classScore=t,this._className=n,this._box=new de(r).rescale(this._imageDims)}get score(){return this._score}get classScore(){return this._classScore}get className(){return this._className}get box(){return this._box}get imageDims(){return this._imageDims}get imageWidth(){return this.imageDims.width}get imageHeight(){return this.imageDims.height}get relativeBox(){return new de(this._box).rescale(this.imageDims.reverse())}forSize(e,t){return new _n(this.score,this.classScore,this.className,this.relativeBox,{width:e,height:t})}}class me extends _n{constructor(e,t,n){super(e,e,"",t,n)}forSize(e,t){const{score:n,relativeBox:r,imageDims:o}=super.forSize(e,t);return new me(n,r,o)}}function Us(e,t,n=!0){const r=Math.max(0,Math.min(e.right,t.right)-Math.max(e.left,t.left)),o=Math.max(0,Math.min(e.bottom,t.bottom)-Math.max(e.top,t.top)),i=r*o;return n?i/(e.area+t.area-i):i/Math.min(e.area,t.area)}function Ms(e){const t=e.map(s=>s.x),n=e.map(s=>s.y),r=t.reduce((s,c)=>c<s?c:s,Infinity),o=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 hr(r,o,i,a)}function Fs(e,t,n,r=!0){let o=t.map((a,s)=>({score:a,boxIndex:s})).sort((a,s)=>a.score-s.score).map(a=>a.boxIndex);const i=[];for(;o.length>0;){const a=o.pop();i.push(a);const s=o,c=[];for(let p=0;p<s.length;p++){const l=s[p],h=e[a],d=e[l];c.push(Us(h,d,r))}o=o.filter((p,l)=>c[l]<=n)}return i}function ht(e,t){return O(()=>{const[n,r,o]=t,i=qe([...e.shape.slice(0,3),1],n),a=qe([...e.shape.slice(0,3),1],r),s=qe([...e.shape.slice(0,3),1],o),c=Z([i,a,s],3);return k(e,c)})}function Ds(e,t=!1){return O(()=>{const[n,r]=e.shape.slice(1);if(n===r)return e;const o=Math.abs(n-r),i=Math.round(o*(t?.5:1)),a=n>r?2:1,s=d=>{const g=e.shape.slice();return g[a]=d,qe(g,0)},c=s(i),p=o-c.shape[a],l=t&&p?s(p):null,h=[l,e,c].filter(d=>!!d).map(d=>_(d,"float32"));return Z(h,a)})}function gh(e){const t=e.slice();for(let n=t.length-1;n>0;n--){const r=Math.floor(Math.random()*(n+1)),o=t[n];t[n]=t[r],t[r]=o}return t}function or(e){return 1/(1+Math.exp(-e))}function bh(e){return Math.log(e/(1-e))}class pr extends de{constructor(e,t,n,r,o=!1){super({x:e,y:t,width:n,height:r},o)}}const uT=.5,dT=.43,mT=.45;class st{constructor(e,t,n=new J(0,0)){const{width:r,height:o}=t;this._imgDims=new Ke(r,o),this._shift=n,this._positions=e.map(i=>i.mul(new J(r,o)).add(n))}get shift(){return new J(this._shift.x,this._shift.y)}get imageWidth(){return this._imgDims.width}get imageHeight(){return this._imgDims.height}get positions(){return this._positions}get relativePositions(){return this._positions.map(e=>e.sub(this._shift).div(new J(this.imageWidth,this.imageHeight)))}forSize(e,t){return new this.constructor(this.relativePositions,{width:e,height:t})}shiftBy(e,t){return new this.constructor(this.relativePositions,this._imgDims,new J(e,t))}shiftByPoint(e){return this.shiftBy(e.x,e.y)}align(e,t={}){if(e){const o=e instanceof me?e.box.floor():new de(e);return this.shiftBy(o.x,o.y).align(null,t)}const{useDlibAlignment:n,minBoxPadding:r}=Object.assign({},{useDlibAlignment:!1,minBoxPadding:.2},t);return n?this.alignDlib():this.alignMinBbox(r)}alignDlib(){const e=this.getRefPointsForAlignment(),[t,n,r]=e,o=l=>r.sub(l).magnitude(),i=(o(t)+o(n))/2,a=Math.floor(i/mT),s=Xn(e),c=Math.floor(Math.max(0,s.x-uT*a)),p=Math.floor(Math.max(0,s.y-dT*a));return new pr(c,p,Math.min(a,this.imageWidth+c),Math.min(a,this.imageHeight+p))}alignMinBbox(e){const t=Ms(this.positions);return t.pad(t.width*e,t.height*e)}getRefPointsForAlignment(){throw new Error("getRefPointsForAlignment not implemented by base class")}}class zh extends st{getRefPointsForAlignment(){const e=this.positions;return[e[0],e[1],Xn([e[3],e[4]])]}}class lr 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(Xn)}}class lo{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?` (${Jn(this.distance)})`:""}`}}class po extends de{constructor(e,t){super(e);this._label=t}static assertIsValidLabeledBox(e,t){if(de.assertIsValidBox(e,t),!Et(e.label))throw new Error(`${t} - expected property label (${e.label}) to be a number`)}get label(){return this._label}}class fn{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 fn(e.label,t)}}class qh extends po{constructor(e,t,n,r){super(e,t);this._score=n,this._classScore=r}static assertIsValidPredictedBox(e,t){if(po.assertIsValidLabeledBox(e,t),!qr(e.score)||!qr(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 It(e){return e.detection instanceof me}function ln(e,t){const n={detection:t};return Object.assign({},e,n)}function kl(){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 Za(e){let t="";if(!e)try{e=require("fs")}catch(r){t=r.toString()}const n=e?function(r){return new Promise((o,i)=>{e.readFile(r,function(a,s){return a?i(a):o(s)})})}:function(){throw new Error(`readFile - failed to require fs in nodejs environment with error: ${t}`)};return{readFile:n}}function Dl(){const e=global.Canvas||global.HTMLCanvasElement,t=global.Image||global.HTMLImageElement,n=function(){if(e)return new e;throw new Error("createCanvasElement - missing Canvas implementation for nodejs environment")},r=function(){if(t)return new t;throw new Error("createImageElement - missing Image implementation for nodejs environment")},o=global.fetch||function(){throw new Error("fetch - missing fetch implementation for nodejs environment")},i=Za();return As({Canvas:e||class{},CanvasRenderingContext2D:global.CanvasRenderingContext2D||class{},Image:t||class{},ImageData:global.ImageData||class{},Video:global.HTMLVideoElement||class{},createCanvasElement:n,createImageElement:r,fetch:o},i)}function Fl(){return typeof window=="object"&&typeof document!="undefined"&&typeof HTMLImageElement!="undefined"&&typeof HTMLCanvasElement!="undefined"&&typeof HTMLVideoElement!="undefined"&&typeof ImageData!="undefined"&&typeof CanvasRenderingContext2D!="undefined"}const Ml=zl(ph());let Me;function fT(){if(!Me)throw new Error("getEnv - environment is not defined, check isNodejs() and isBrowser()");return Me}function Ul(e){Me=e}function Wl(){if(Fl())return Ul(kl());if(Ml.isNodejs())return Ul(Dl())}function gT(e){if(Me||Wl(),!Me)throw new Error("monkeyPatch - environment is not defined, check isNodejs() and isBrowser()");const{Canvas:t=Me.Canvas,Image:n=Me.Image}=e;Me.Canvas=t,Me.Image=n,Me.createCanvasElement=e.createCanvasElement||(()=>new t),Me.createImageElement=e.createImageElement||(()=>new n),Me.ImageData=e.ImageData||Me.ImageData,Me.Video=e.Video||Me.Video,Me.fetch=e.fetch||Me.fetch,Me.readFile=e.readFile||Me.readFile}const se={getEnv:fT,setEnv:Ul,initialize:Wl,createBrowserEnv:kl,createFileSystem:Za,createNodejsEnv:Dl,monkeyPatch:gT,isBrowser:Fl,isNodejs:Ml.isNodejs};Wl();function un(e){return!se.isNodejs()&&typeof e=="string"?document.getElementById(e):e}function Ge(e){const{Canvas:t,CanvasRenderingContext2D:n}=se.getEnv();if(e instanceof n)return e;const r=un(e);if(!(r instanceof t))throw new Error("resolveContext2d - expected canvas to be of instance of Canvas");const o=r.getContext("2d");if(!o)throw new Error("resolveContext2d - canvas 2d context is null");return o}var Yt;(function(e){e.TOP_LEFT="TOP_LEFT",e.TOP_RIGHT="TOP_RIGHT",e.BOTTOM_LEFT="BOTTOM_LEFT",e.BOTTOM_RIGHT="BOTTOM_RIGHT"})(Yt||(Yt={}));class Qa{constructor(e={}){const{anchorPosition:t,backgroundColor:n,fontColor:r,fontSize:o,fontStyle:i,padding:a}=e;this.anchorPosition=t||Yt.TOP_LEFT,this.backgroundColor=n||"rgba(0, 0, 0, 0.5)",this.fontColor=r||"rgba(255, 255, 255, 1)",this.fontSize=o||14,this.fontStyle=i||"Georgia",this.padding=a||4}}class zr{constructor(e,t,n={}){this.text=typeof e=="string"?[e]:e instanceof zr?e.text:e,this.anchor=t,this.options=new Qa(n)}measureWidth(e){const{padding:t}=this.options;return this.text.map(n=>e.measureText(n).width).reduce((n,r)=>n<r?r:n,0)+2*t}measureHeight(){const{fontSize:e,padding:t}=this.options;return this.text.length*e+2*t}getUpperLeft(e,t){const{anchorPosition:n}=this.options,r=n===Yt.BOTTOM_RIGHT||n===Yt.TOP_RIGHT,o=n===Yt.BOTTOM_LEFT||n===Yt.BOTTOM_RIGHT,i=this.measureWidth(e),a=this.measureHeight(),s=r?this.anchor.x-i:this.anchor.x,c=o?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=un(e),n=Ge(t),{backgroundColor:r,fontColor:o,fontSize:i,fontStyle:a,padding:s}=this.options;n.font=`${i}px ${a}`;const c=this.measureWidth(n),p=this.measureHeight();n.fillStyle=r;const l=this.getUpperLeft(n,t);n.fillRect(l.x,l.y,c,p),n.fillStyle=o,this.text.forEach((h,d)=>{const g=s+l.x,x=s+l.y+(d+1)*i;n.fillText(h,g,x)})}}class jg{constructor(e={}){const{boxColor:t,lineWidth:n,label:r,drawLabelOptions:o}=e;this.boxColor=t||"rgba(0, 0, 255, 1)",this.lineWidth=n||2,this.label=r;const i={anchorPosition:Yt.BOTTOM_LEFT,backgroundColor:this.boxColor};this.drawLabelOptions=new Qa(Object.assign({},i,o))}}class Bl{constructor(e,t={}){this.box=new de(e),this.options=new jg(t)}draw(e){const t=Ge(e),{boxColor:n,lineWidth:r}=this.options,{x:o,y:i,width:a,height:s}=this.box;t.strokeStyle=n,t.lineWidth=r,t.strokeRect(o,i,a,s);const{label:c}=this.options;c&&new zr([c],{x:o-r/2,y:i},this.options.drawLabelOptions).draw(e)}}function bT(e,t){const n=Array.isArray(t)?t:[t];n.forEach(r=>{const o=r instanceof me?r.score:It(r)?r.detection.score:void 0,i=r instanceof me?r.box:It(r)?r.detection.box:new de(r),a=o?`${Jn(o)}`:void 0;new Bl(i,{label:a}).draw(e)})}function ar(e){const{Image:t,Video:n}=se.getEnv();return e instanceof t&&e.complete||e instanceof n&&e.readyState>=3}function ea(e){return new Promise((t,n)=>{if(e instanceof se.getEnv().Canvas||ar(e))return t(null);function r(i){if(!i.currentTarget)return;i.currentTarget.removeEventListener("load",r),i.currentTarget.removeEventListener("error",o),t(i)}function o(i){if(!i.currentTarget)return;i.currentTarget.removeEventListener("load",r),i.currentTarget.removeEventListener("error",o),n(i)}e.addEventListener("load",r),e.addEventListener("error",o)})}function Qs(e){return new Promise((t,n)=>{if(!(e instanceof Blob))return n("bufferToImage - expected buf to be of type: Blob");const r=new FileReader;r.onload=()=>{if(typeof r.result!="string")return n("bufferToImage - expected reader.result to be a string, in onload");const o=se.getEnv().createImageElement();o.onload=()=>t(o),o.onerror=n,o.src=r.result},r.onerror=n,r.readAsDataURL(e)})}function dn(e){const{Image:t,Video:n}=se.getEnv();return e instanceof t?new Ke(e.naturalWidth,e.naturalHeight):e instanceof n?new Ke(e.videoWidth,e.videoHeight):new Ke(e.width,e.height)}function Rn({width:e,height:t}){const{createCanvasElement:n}=se.getEnv(),r=n();return r.width=e,r.height=t,r}function cr(e,t){const{ImageData:n}=se.getEnv();if(!(e instanceof n)&&!ar(e))throw new Error("createCanvasFromMedia - media has not finished loading yet");const{width:r,height:o}=t||dn(e),i=Rn({width:r,height:o});return e instanceof n?Ge(i).putImageData(e,0,0):Ge(i).drawImage(e,0,0,r,o),i}async function Xs(e,t){const n=t||se.getEnv().createCanvasElement(),[r,o,i]=e.shape.slice(pt(e)?1:0),a=O(()=>e.as3D(r,o,i).toInt());return await Ir.toPixels(a,n),a.dispose(),n}function co(e){const{Image:t,Canvas:n,Video:r}=se.getEnv();return e instanceof t||e instanceof n||e instanceof r}function Js(e,t,n=!1){const{Image:r,Canvas:o}=se.getEnv();if(!(e instanceof r||e instanceof o))throw new Error("imageToSquare - expected arg0 to be HTMLImageElement | HTMLCanvasElement");const i=dn(e),a=t/Math.max(i.height,i.width),s=a*i.width,c=a*i.height,p=Rn({width:t,height:t}),l=e instanceof o?e:cr(e),h=Math.abs(s-c)/2,d=n&&s<c?h:0,g=n&&c<s?h:0;return Ge(p).drawImage(l,d,g,s,c),p}class Vt{constructor(e,t=!1){if(this._imageTensors=[],this._canvases=[],this._treatAsBatchInput=!1,this._inputDimensions=[],!Array.isArray(e))throw new Error(`NetInput.constructor - expected inputs to be an Array of TResolvedNetInput or to be instanceof tf.Tensor4D, instead have ${e}`);this._treatAsBatchInput=t,this._batchSize=e.length,e.forEach((n,r)=>{if(nn(n)){this._imageTensors[r]=n,this._inputDimensions[r]=n.shape;return}if(pt(n)){const i=n.shape[0];if(i!==1)throw new Error(`NetInput - tf.Tensor4D with batchSize ${i} passed, but not supported in input array`);this._imageTensors[r]=n,this._inputDimensions[r]=n.shape.slice(1);return}const o=n instanceof se.getEnv().Canvas?n:cr(n);this._canvases[r]=o,this._inputDimensions[r]=[o.height,o.width,3]})}get imageTensors(){return this._imageTensors}get canvases(){return this._canvases}get isBatchInput(){return this.batchSize>1||this._treatAsBatchInput}get batchSize(){return this._batchSize}get inputDimensions(){return this._inputDimensions}get inputSize(){return this._inputSize}get reshapedInputDimensions(){return Ht(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 Ol({width:t,height:n},this.inputSize)}toBatchTensor(e,t=!0){return this._inputSize=e,O(()=>{const n=Ht(this.batchSize,0,1).map(o=>{const i=this.getInput(o);if(i instanceof te){let a=pt(i)?i:i.expandDims();return a=Ds(a,t),(a.shape[1]!==e||a.shape[2]!==e)&&(a=Sl.resizeBilinear(a,[e,e])),a.as3D(e,e,3)}if(i instanceof se.getEnv().Canvas)return Ir.fromPixels(Js(i,e,t));throw new Error(`toBatchTensor - at batchIdx ${o}, expected input to be instanceof tf.Tensor or instanceof HTMLCanvasElement, instead have ${i}`)}),r=Fe(n.map(o=>_(o,"float32"))).as4D(this.batchSize,e,e,3);return r})}}async function ue(e){if(e instanceof Vt)return e;let t=Array.isArray(e)?e:[e];if(!t.length)throw new Error("toNetInput - empty array passed as input");const n=o=>Array.isArray(e)?` at input index ${o}:`:"",r=t.map(un);return r.forEach((o,i)=>{if(!co(o)&&!nn(o)&&!pt(o))throw typeof t[i]=="string"?new Error(`toNetInput -${n(i)} string passed, but could not resolve HTMLElement for element id ${t[i]}`):new Error(`toNetInput -${n(i)} expected media to be of type HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | tf.Tensor3D, or to be an element id`);if(pt(o)){const a=o.shape[0];if(a!==1)throw new Error(`toNetInput -${n(i)} tf.Tensor4D with batchSize ${a} passed, but not supported in input array`)}}),await Promise.all(r.map(o=>co(o)&&ea(o))),new Vt(r,Array.isArray(e))}async function An(e,t){const{Canvas:n}=se.getEnv();let r=e;if(!(e instanceof n)){const a=await ue(e);if(a.batchSize>1)throw new Error("extractFaces - batchSize > 1 not supported");const s=a.getInput(0);r=s instanceof n?s:await Xs(s)}const o=Ge(r),i=t.map(a=>a instanceof me?a.forSize(r.width,r.height).box.floor():a).map(a=>a.clipAtImageBorders(r.width,r.height));return i.map(({x:a,y:s,width:c,height:p})=>{const l=Rn({width:c,height:p});return Ge(l).putImageData(o.getImageData(a,s,c,p),0,0),l})}async function Nn(e,t){if(!nn(e)&&!pt(e))throw new Error("extractFaceTensors - expected image tensor to be 3D or 4D");if(pt(e)&&e.shape[0]>1)throw new Error("extractFaceTensors - batchSize > 1 not supported");return O(()=>{const[n,r,o]=e.shape.slice(pt(e)?1:0),i=t.map(s=>s instanceof me?s.forSize(r,n).box:s).map(s=>s.clipAtImageBorders(r,n)),a=i.map(({x:s,y:c,width:p,height:l})=>Ua(e.as3D(n,r,o),[c,s,0],[l,p,o]));return a})}async function mn(e,t){const n=se.getEnv().fetch,r=await n(e,t);if(!(r.status<400))throw new Error(`failed to fetch: (${r.status}) ${r.statusText}, from url: ${r.url}`);return r}async function Ph(e){const t=await mn(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 Qs(n)}async function Zs(e){return(await mn(e)).json()}async function Gh(e){return new Float32Array(await(await mn(e)).arrayBuffer())}function ec(e,t){const n=`${t}-weights_manifest.json`;if(!e)return{modelBaseUri:"",manifestUri:n};if(e==="/")return{modelBaseUri:"/",manifestUri:`/${n}`};const r=e.startsWith("http://")?"http://":e.startsWith("https://")?"https://":"";e=e.replace(r,"");const o=e.split("/").filter(s=>s),i=e.endsWith(".json")?o[o.length-1]:n;let a=r+(e.endsWith(".json")?o.slice(0,o.length-1):o).join("/");return a=e.startsWith("/")?`/${a}`:a,{modelBaseUri:a,manifestUri:a==="/"?`/${i}`:`${a}/${i}`}}async function Ks(e,t){const{manifestUri:n,modelBaseUri:r}=ec(e,t);let o=await Zs(n);return vr.loadWeights(o,r)}function jh(e,t,n=!1){const{width:r,height:o}=n?dn(t):t;return e.width=r,e.height=o,{width:r,height:o}}class We{constructor(e){this._name=e,this._params=void 0,this._paramMappings=[]}get params(){return this._params}get paramMappings(){return this._paramMappings}get isLoaded(){return!!this.params}getParamFromPath(e){const{obj:t,objProp:n}=this.traversePropertyPath(e);return t[n]}reassignParamFromPath(e,t){const{obj:n,objProp:r}=this.traversePropertyPath(e);n[r].dispose(),n[r]=t}getParamList(){return this._paramMappings.map(({paramPath:e})=>({path:e,tensor:this.getParamFromPath(e)}))}getTrainableParams(){return this.getParamList().filter(e=>e.tensor instanceof $t)}getFrozenParams(){return this.getParamList().filter(e=>!(e.tensor instanceof $t))}variable(){this.getFrozenParams().forEach(({path:e,tensor:t})=>{this.reassignParamFromPath(e,t.variable())})}freeze(){this.getTrainableParams().forEach(({path:e,tensor:t})=>{const n=Xe(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 Ks(e,this.getDefaultModelName());this.loadFromWeightMap(t)}async loadFromDisk(e){if(e&&typeof e!="string")throw new Error(`${this._name}.loadFromDisk - expected model file path`);const{readFile:t}=se.getEnv(),{manifestUri:n,modelBaseUri:r}=ec(e,this.getDefaultModelName()),o=c=>Promise.all(c.map(p=>t(p).then(l=>l.buffer))),i=vr.weightsLoaderFactory(o),a=JSON.parse((await t(n)).toString()),s=await i(a,r);this.loadFromWeightMap(s)}loadFromWeightMap(e){const{paramMappings:t,params:n}=this.extractParamsFromWeigthMap(e);this._paramMappings=t,this._params=n}extractWeights(e){const{paramMappings:t,params:n}=this.extractParams(e);this._paramMappings=t,this._params=n}traversePropertyPath(e){if(!this.params)throw new Error("traversePropertyPath - model has no loaded params");const t=e.split("/").reduce((o,i)=>{if(!o.nextObj.hasOwnProperty(i))throw new Error(`traversePropertyPath - object does not have property ${i}, for path ${e}`);return{obj:o.nextObj,objProp:i,nextObj:o.nextObj[i]}},{nextObj:this.params}),{obj:n,objProp:r}=t;if(!n||!r||!(n[r]instanceof te))throw new Error(`traversePropertyPath - parameter is not a tensor, for path ${e}`);return{obj:n,objProp:r}}}function tt(e,t,n){return O(()=>{let r=Wr(e,t.depthwise_filter,t.pointwise_filter,n,"same");return r=N(r,t.bias),r})}function tc(e,t,n=!1){return O(()=>{const r=ie(n?N(ve(e,t.conv0.filters,[2,2],"same"),t.conv0.bias):tt(e,t.conv0,[2,2])),o=tt(r,t.conv1,[1,1]),i=ie(N(r,o)),a=tt(i,t.conv2,[1,1]);return ie(N(r,N(o,a)))})}function ws(e,t,n=!1,r=!0){return O(()=>{const o=ie(n?N(ve(e,t.conv0.filters,r?[2,2]:[1,1],"same"),t.conv0.bias):tt(e,t.conv0,r?[2,2]:[1,1])),i=tt(o,t.conv1,[1,1]),a=ie(N(o,i)),s=tt(a,t.conv2,[1,1]),c=ie(N(o,N(i,s))),p=tt(c,t.conv3,[1,1]);return ie(N(o,N(i,N(s,p))))})}function Zn(e,t,n="same",r=!1){return O(()=>{const o=N(ve(e,t.filters,[1,1],n),t.bias);return r?ie(o):o})}function Ye(e,t){Object.keys(e).forEach(n=>{t.some(r=>r.originalPath===n)||e[n].dispose()})}function Hr(e,t){return function(n,r,o,i){const a=xt(e(n*r*o*o),[o,o,n,r]),s=ce(e(r));return t.push({paramPath:`${i}/filters`},{paramPath:`${i}/bias`}),{filters:a,bias:s}}}function nc(e,t){return function(n,r,o){const i=wt(e(n*r),[n,r]),a=ce(e(r));return t.push({paramPath:`${o}/weights`},{paramPath:`${o}/bias`}),{weights:i,bias:a}}}class $l{constructor(e,t,n){this.depthwise_filter=e,this.pointwise_filter=t,this.bias=n}}function Yr(e,t){return function(n,r,o){const i=xt(e(3*3*n),[3,3,n,1]),a=xt(e(n*r),[1,1,n,r]),s=ce(e(r));return t.push({paramPath:`${o}/depthwise_filter`},{paramPath:`${o}/pointwise_filter`},{paramPath:`${o}/bias`}),new $l(i,a,s)}}function Vr(e){return function(t){const n=e(`${t}/depthwise_filter`,4),r=e(`${t}/pointwise_filter`,4),o=e(`${t}/bias`,1);return new $l(n,r,o)}}function it(e,t){return function(n,r,o){const i=e[n];if(!Kn(i,r))throw new Error(`expected weightMap[${n}] to be a Tensor${r}D, instead have ${i}`);return t.push({originalPath:n,paramPath:o||n}),i}}function Ve(e){let t=e;function n(o){const i=t.slice(0,o);return t=t.slice(o),i}function r(){return t}return{extractWeights:n,getRemainingWeights:r}}function rc(e,t){const n=Hr(e,t),r=Yr(e,t);function o(a,s,c,p=!1){const l=p?n(a,s,3,`${c}/conv0`):r(a,s,`${c}/conv0`),h=r(s,s,`${c}/conv1`),d=r(s,s,`${c}/conv2`);return{conv0:l,conv1:h,conv2:d}}function i(a,s,c,p=!1){const{conv0:l,conv1:h,conv2:d}=o(a,s,c,p),g=r(s,s,`${c}/conv3`);return{conv0:l,conv1:h,conv2:d,conv3:g}}return{extractDenseBlock3Params:o,extractDenseBlock4Params:i}}function Gg(e){const t=[],{extractWeights:n,getRemainingWeights:r}=Ve(e),{extractDenseBlock4Params:o}=rc(n,t),i=o(3,32,"dense0",!0),a=o(32,64,"dense1"),s=o(64,128,"dense2"),c=o(128,256,"dense3");if(r().length!==0)throw new Error(`weights remaing after extract: ${r().length}`);return{paramMappings:t,params:{dense0:i,dense1:a,dense2:s,dense3:c}}}function oc(e){return function(t){const n=e(`${t}/filters`,4),r=e(`${t}/bias`,1);return{filters:n,bias:r}}}function ic(e,t){const n=it(e,t),r=oc(n),o=Vr(n);function i(s,c=!1){const p=c?r(`${s}/conv0`):o(`${s}/conv0`),l=o(`${s}/conv1`),h=o(`${s}/conv2`);return{conv0:p,conv1:l,conv2:h}}function a(s,c=!1){const p=c?r(`${s}/conv0`):o(`${s}/conv0`),l=o(`${s}/conv1`),h=o(`${s}/conv2`),d=o(`${s}/conv3`);return{conv0:p,conv1:l,conv2:h,conv3:d}}return{extractDenseBlock3Params:i,extractDenseBlock4Params:a}}function Pg(e){const t=[],{extractDenseBlock4Params:n}=ic(e,t),r={dense0:n("dense0",!0),dense1:n("dense1"),dense2:n("dense2"),dense3:n("dense3")};return Ye(e,t),{params:r,paramMappings:t}}class sc extends We{constructor(){super("FaceFeatureExtractor")}forwardInput(e){const{params:t}=this;if(!t)throw new Error("FaceFeatureExtractor - load model before inference");return O(()=>{const n=e.toBatchTensor(112,!0),r=[122.782,117.001,104.298],o=ht(n,r).div(C(255));let i=ws(o,t.dense0,!0);return i=ws(i,t.dense1),i=ws(i,t.dense2),i=ws(i,t.dense3),i=mt(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 Pg(e)}extractParams(e){return Gg(e)}}function xs(e,t){return O(()=>N(V(e,t.weights),t.bias))}function qg(e,t,n){const r=[],{extractWeights:o,getRemainingWeights:i}=Ve(e),a=nc(o,r),s=a(t,n,"fc");if(i().length!==0)throw new Error(`weights remaing after extract: ${i().length}`);return{paramMappings:r,params:{fc:s}}}function zg(e){const t=[],n=it(e,t);function r(i){const a=n(`${i}/weights`,2),s=n(`${i}/bias`,1);return{weights:a,bias:s}}const o={fc:r("fc")};return Ye(e,t),{params:o,paramMappings:t}}function ac(e){const t={},n={};return Object.keys(e).forEach(r=>{const o=r.startsWith("fc")?n:t;o[r]=e[r]}),{featureExtractorMap:t,classifierMap:n}}class cc extends We{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 O(()=>{const n=e instanceof Vt?this.faceFeatureExtractor.forwardInput(e):e;return xs(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 qg(e,this.getClassifierChannelsIn(),this.getClassifierChannelsOut())}extractParamsFromWeigthMap(e){const{featureExtractorMap:t,classifierMap:n}=ac(e);return this.faceFeatureExtractor.loadFromWeightMap(t),zg(n)}extractParams(e){const t=this.getClassifierChannelsIn(),n=this.getClassifierChannelsOut(),r=n*t+n,o=e.slice(0,e.length-r),i=e.slice(e.length-r);return this.faceFeatureExtractor.extractWeights(o),this.extractClassifierParams(i)}}const Hs=["neutral","happy","sad","angry","fearful","disgusted","surprised"];class hn{constructor(e){if(e.length!==7)throw new Error(`FaceExpressions.constructor - expected probabilities.length to be 7, have: ${e.length}`);Hs.forEach((t,n)=>{this[t]=e[n]})}asSortedArray(){return Hs.map(e=>({expression:e,probability:this[e]})).sort((e,t)=>t.probability-e.probability)}}class Ys extends cc{constructor(e=new sc){super("FaceExpressionNet",e)}forwardInput(e){return O(()=>Ln(this.runNet(e)))}async forward(e){return this.forwardInput(await ue(e))}async predictExpressions(e){const t=await ue(e),n=await this.forwardInput(t),r=await Promise.all(Ae(n).map(async i=>{const a=await i.data();return i.dispose(),a}));n.dispose();const o=r.map(i=>new hn(i));return t.isBatchInput?o:o[0]}getDefaultModelName(){return"face_expression_model"}getClassifierChannelsIn(){return 256}getClassifierChannelsOut(){return 7}}function qs(e){return e.expressions instanceof hn}function io(e,t){const n={expressions:t};return Object.assign({},e,n)}function wT(e,t,n=.1,r){const o=Array.isArray(t)?t:[t];o.forEach(i=>{const a=i instanceof hn?i:qs(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=It(i)?i.detection.box.bottomLeft:r||new J(0,0),l=new zr(c.map(h=>`${h.expression} (${Jn(h.probability)})`),p);l.draw(e)})}function pn(e){return It(e)&&e.landmarks instanceof st&&e.unshiftedLandmarks instanceof st&&e.alignedRect instanceof me}function Tn(e,t){const{box:n}=e.detection,r=t.shiftBy(n.x,n.y),o=r.align(),{imageDims:i}=e.detection,a=new me(e.detection.score,o.rescale(i.reverse()),i),s={landmarks:r,unshiftedLandmarks:t,alignedRect:a};return Object.assign({},e,s)}class Hg{constructor(e={}){const{drawLines:t=!0,drawPoints:n=!0,lineWidth:r,lineColor:o,pointSize:i,pointColor:a}=e;this.drawLines=t,this.drawPoints=n,this.lineWidth=r||1,this.pointSize=i||2,this.lineColor=o||"rgba(0, 255, 255, 1)",this.pointColor=a||"rgba(255, 0, 255, 1)"}}class Yg{constructor(e,t={}){this.faceLandmarks=e,this.options=new Hg(t)}draw(e){const t=Ge(e),{drawLines:n,drawPoints:r,lineWidth:o,lineColor:i,pointSize:a,pointColor:s}=this.options;if(n&&this.faceLandmarks instanceof lr&&(t.strokeStyle=i,t.lineWidth=o,tn(t,this.faceLandmarks.getJawOutline()),tn(t,this.faceLandmarks.getLeftEyeBrow()),tn(t,this.faceLandmarks.getRightEyeBrow()),tn(t,this.faceLandmarks.getNose()),tn(t,this.faceLandmarks.getLeftEye(),!0),tn(t,this.faceLandmarks.getRightEye(),!0),tn(t,this.faceLandmarks.getMouth(),!0)),r){t.strokeStyle=s,t.fillStyle=s;const c=p=>{t.beginPath(),t.arc(p.x,p.y,a,0,2*Math.PI),t.fill()};this.faceLandmarks.positions.forEach(c)}}}function xT(e,t){const n=Array.isArray(t)?t:[t];n.forEach(r=>{const o=r instanceof st?r:pn(r)?r.landmarks:void 0;if(!o)throw new Error("drawFaceLandmarks - expected faceExpressions to be FaceLandmarks | WithFaceLandmarks<WithFaceDetection<{}>> or array thereof");new Yg(o).draw(e)})}const _s={};_e(_s,{AnchorPosition:()=>Yt,DrawBox:()=>Bl,DrawBoxOptions:()=>jg,DrawFaceLandmarks:()=>Yg,DrawFaceLandmarksOptions:()=>Hg,DrawTextField:()=>zr,DrawTextFieldOptions:()=>Qa,drawContour:()=>tn,drawDetections:()=>bT,drawFaceExpressions:()=>wT,drawFaceLandmarks:()=>xT});function yT(e,t){const n=Hr(e,t),r=Yr(e,t);function o(a,s,c){const p=r(a,s,`${c}/separable_conv0`),l=r(s,s,`${c}/separable_conv1`),h=n(a,s,1,`${c}/expansion_conv`);return{separable_conv0:p,separable_conv1:l,expansion_conv:h}}function i(a,s){const c=r(a,a,`${s}/separable_conv0`),p=r(a,a,`${s}/separable_conv1`),l=r(a,a,`${s}/separable_conv2`);return{separable_conv0:c,separable_conv1:p,separable_conv2:l}}return{extractConvParams:n,extractSeparableConvParams:r,extractReductionBlockParams:o,extractMainBlockParams:i}}function Vg(e,t){const n=[],{extractWeights:r,getRemainingWeights:o}=Ve(e),{extractConvParams:i,extractSeparableConvParams:a,extractReductionBlockParams:s,extractMainBlockParams:c}=yT(r,n),p=i(3,32,3,"entry_flow/conv_in"),l=s(32,64,"entry_flow/reduction_block_0"),h=s(64,128,"entry_flow/reduction_block_1"),d={conv_in:p,reduction_block_0:l,reduction_block_1:h},g={};Ht(t,0,1).forEach(S=>{g[`main_block_${S}`]=c(128,`middle_flow/main_block_${S}`)});const x=s(128,256,"exit_flow/reduction_block"),w=a(256,512,"exit_flow/separable_conv"),L={reduction_block:x,separable_conv:w};if(o().length!==0)throw new Error(`weights remaing after extract: ${o().length}`);return{paramMappings:n,params:{entry_flow:d,middle_flow:g,exit_flow:L}}}function LT(e,t){const n=it(e,t),r=oc(n),o=Vr(n);function i(s){const c=o(`${s}/separable_conv0`),p=o(`${s}/separable_conv1`),l=r(`${s}/expansion_conv`);return{separable_conv0:c,separable_conv1:p,expansion_conv:l}}function a(s){const c=o(`${s}/separable_conv0`),p=o(`${s}/separable_conv1`),l=o(`${s}/separable_conv2`);return{separable_conv0:c,separable_conv1:p,separable_conv2:l}}return{extractConvParams:r,extractSeparableConvParams:o,extractReductionBlockParams:i,extractMainBlockParams:a}}function Kg(e,t){const n=[],{extractConvParams:r,extractSeparableConvParams:o,extractReductionBlockParams:i,extractMainBlockParams:a}=LT(e,n),s=r("entry_flow/conv_in"),c=i("entry_flow/reduction_block_0"),p=i("entry_flow/reduction_block_1"),l={conv_in:s,reduction_block_0:c,reduction_block_1:p},h={};Ht(t,0,1).forEach(w=>{h[`main_block_${w}`]=a(`middle_flow/main_block_${w}`)});const d=i("exit_flow/reduction_block"),g=o("exit_flow/separable_conv"),x={reduction_block:d,separable_conv:g};return Ye(e,n),{params:{entry_flow:l,middle_flow:h,exit_flow:x},paramMappings:n}}function Jg(e,t,n){return N(ve(e,t.filters,n,"same"),t.bias)}function jl(e,t,n=!0){let r=n?ie(e):e;return r=tt(r,t.separable_conv0,[1,1]),r=tt(ie(r),t.separable_conv1,[1,1]),r=Re(r,[3,3],[2,2],"same"),r=N(r,Jg(e,t.expansion_conv,[2,2])),r}function vT(e,t){let n=tt(ie(e),t.separable_conv0,[1,1]);return n=tt(ie(n),t.separable_conv1,[1,1]),n=tt(ie(n),t.separable_conv2,[1,1]),n=N(n,e),n}class Xg extends We{constructor(e){super("TinyXception");this._numMainBlocks=e}forwardInput(e){const{params:t}=this;if(!t)throw new Error("TinyXception - load model before inference");return O(()=>{const n=e.toBatchTensor(112,!0),r=[122.782,117.001,104.298],o=ht(n,r).div(C(256));let i=ie(Jg(o,t.entry_flow.conv_in,[2,2]));return i=jl(i,t.entry_flow.reduction_block_0,!1),i=jl(i,t.entry_flow.reduction_block_1),Ht(this._numMainBlocks,0,1).forEach(a=>{i=vT(i,t.middle_flow[`main_block_${a}`])}),i=jl(i,t.exit_flow.reduction_block),i=ie(tt(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 Kg(e,this._numMainBlocks)}extractParams(e){return Vg(e,this._numMainBlocks)}}function Zg(e){const t=[],{extractWeights:n,getRemainingWeights:r}=Ve(e),o=nc(n,t),i=o(512,1,"fc/age"),a=o(512,2,"fc/gender");if(r().length!==0)throw new Error(`weights remaing after extract: ${r().length}`);return{paramMappings:t,params:{fc:{age:i,gender:a}}}}function Qg(e){const t=[],n=it(e,t);function r(i){const a=n(`${i}/weights`,2),s=n(`${i}/bias`,1);return{weights:a,bias:s}}const o={fc:{age:r("fc/age"),gender:r("fc/gender")}};return Ye(e,t),{params:o,paramMappings:t}}var Dt;(function(e){e.FEMALE="female",e.MALE="male"})(Dt||(Dt={}));class ta extends We{constructor(e=new Xg(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 O(()=>{const n=e instanceof Vt?this.faceFeatureExtractor.forwardInput(e):e,r=mt(n,[7,7],[2,2],"valid").as2D(n.shape[0],-1),o=xs(r,t.fc.age).as1D(),i=xs(r,t.fc.gender);return{age:o,gender:i}})}forwardInput(e){return O(()=>{const{age:t,gender:n}=this.runNet(e);return{age:t,gender:Ln(n)}})}async forward(e){return this.forwardInput(await ue(e))}async predictAgeAndGender(e){const t=await ue(e),n=await this.forwardInput(t),r=Ae(n.age),o=Ae(n.gender),i=r.map((s,c)=>({ageTensor:s,genderTensor:o[c]})),a=await Promise.all(i.map(async({ageTensor:s,genderTensor:c})=>{const p=(await s.data())[0],l=(await c.data())[0],h=l>.5,d=h?Dt.MALE:Dt.FEMALE,g=h?l:1-l;return s.dispose(),c.dispose(),{age:p,gender:d,genderProbability:g}}));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 Zg(e)}extractParamsFromWeigthMap(e){const{featureExtractorMap:t,classifierMap:n}=ac(e);return this.faceFeatureExtractor.loadFromWeightMap(t),Qg(n)}extractParams(e){const t=512*1+1+(512*2+2),n=e.slice(0,e.length-t),r=e.slice(e.length-t);return this.faceFeatureExtractor.extractWeights(n),this.extractClassifierParams(r)}}class pc extends cc{postProcess(e,t,n){const r=n.map(({width:i,height:a})=>{const s=t/Math.max(a,i);return{width:i*s,height:a*s}}),o=r.length;return O(()=>{const i=(l,h)=>Fe([qe([68],l),qe([68],h)],1).as2D(1,136).as1D(),a=(l,h)=>{const{width:d,height:g}=r[l];return h(d,g)?Math.abs(d-g)/2:0},s=l=>a(l,(h,d)=>h<d),c=l=>a(l,(h,d)=>d<h),p=e.mul(qe([o,136],t)).sub(Fe(Array.from(Array(o),(l,h)=>i(s(h),c(h))))).div(Fe(Array.from(Array(o),(l,h)=>i(r[h].width,r[h].height))));return p})}forwardInput(e){return O(()=>{const t=this.runNet(e);return this.postProcess(t,e.inputSize,e.inputDimensions.map(([n,r])=>({height:n,width:r})))})}async forward(e){return this.forwardInput(await ue(e))}async detectLandmarks(e){const t=await ue(e),n=O(()=>Ae(this.forwardInput(t))),r=await Promise.all(n.map(async(o,i)=>{const a=Array.from(await o.data()),s=a.filter((p,l)=>Ja(l)),c=a.filter((p,l)=>!Ja(l));return new lr(Array(68).fill(0).map((p,l)=>new J(s[l],c[l])),{height:t.getInputHeight(i),width:t.getInputWidth(i)})}));return n.forEach(o=>o.dispose()),t.isBatchInput?r:r[0]}getClassifierChannelsOut(){return 136}}class sr extends pc{constructor(e=new sc){super("FaceLandmark68Net",e)}getDefaultModelName(){return"face_landmark_68_model"}getClassifierChannelsIn(){return 256}}function eb(e){const t=[],{extractDenseBlock3Params:n}=ic(e,t),r={dense0:n("dense0",!0),dense1:n("dense1"),dense2:n("dense2")};return Ye(e,t),{params:r,paramMappings:t}}function tb(e){const t=[],{extractWeights:n,getRemainingWeights:r}=Ve(e),{extractDenseBlock3Params:o}=rc(n,t),i=o(3,32,"dense0",!0),a=o(32,64,"dense1"),s=o(64,128,"dense2");if(r().length!==0)throw new Error(`weights remaing after extract: ${r().length}`);return{paramMappings:t,params:{dense0:i,dense1:a,dense2:s}}}class nb extends We{constructor(){super("TinyFaceFeatureExtractor")}forwardInput(e){const{params:t}=this;if(!t)throw new Error("TinyFaceFeatureExtractor - load model before inference");return O(()=>{const n=e.toBatchTensor(112,!0),r=[122.782,117.001,104.298],o=ht(n,r).div(C(255));let i=tc(o,t.dense0,!0);return i=tc(i,t.dense1),i=tc(i,t.dense2),i=mt(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 eb(e)}extractParams(e){return tb(e)}}class zs extends pc{constructor(e=new nb){super("FaceLandmark68TinyNet",e)}getDefaultModelName(){return"face_landmark_68_tiny_model"}getClassifierChannelsIn(){return 128}}class $h extends sr{}function rb(e,t){return N(v(e,t.weights),t.biases)}function Gl(e,t,n,r,o="same"){const{filters:i,bias:a}=t.conv;let s=ve(e,i,n,o);return s=N(s,a),s=rb(s,t.scale),r?ie(s):s}function ob(e,t){return Gl(e,t,[1,1],!0)}function Pl(e,t){return Gl(e,t,[1,1],!1)}function lc(e,t){return Gl(e,t,[2,2],!0,"valid")}function ST(e,t){function n(s,c,p){const l=e(s),h=l.length/(c*p*p);if(El(h))throw new Error(`depth has to be an integer: ${h}, weights.length: ${l.length}, numFilters: ${c}, filterSize: ${p}`);return O(()=>K(xt(l,[c,h,p,p]),[2,3,1,0]))}function r(s,c,p,l){const h=n(s,c,p),d=ce(e(c));return t.push({paramPath:`${l}/filters`},{paramPath:`${l}/bias`}),{filters:h,bias:d}}function o(s,c){const p=ce(e(s)),l=ce(e(s));return t.push({paramPath:`${c}/weights`},{paramPath:`${c}/biases`}),{weights:p,biases:l}}function i(s,c,p,l){const h=r(s,c,p,`${l}/conv`),d=o(c,`${l}/scale`);return{conv:h,scale:d}}function a(s,c,p,l,h=!1){const d=i((h?.5:1)*s,c,p,`${l}/conv1`),g=i(s,c,p,`${l}/conv2`);return{conv1:d,conv2:g}}return{extractConvLayerParams:i,extractResidualLayerParams:a}}function ib(e){const{extractWeights:t,getRemainingWeights:n}=Ve(e),r=[],{extractConvLayerParams:o,extractResidualLayerParams:i}=ST(t,r),a=o(4704,32,7,"conv32_down"),s=i(9216,32,3,"conv32_1"),c=i(9216,32,3,"conv32_2"),p=i(9216,32,3,"conv32_3"),l=i(36864,64,3,"conv64_down",!0),h=i(36864,64,3,"conv64_1"),d=i(36864,64,3,"conv64_2"),g=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"),R=i(589824,256,3,"conv256_2"),A=i(589824,256,3,"conv256_down_out"),E=O(()=>K(wt(t(256*128),[128,256]),[1,0]));if(r.push({paramPath:"fc"}),n().length!==0)throw new Error(`weights remaing after extract: ${n().length}`);const F={conv32_down:a,conv32_1:s,conv32_2:c,conv32_3:p,conv64_down:l,conv64_1:h,conv64_2:d,conv64_3:g,conv128_down:x,conv128_1:w,conv128_2:L,conv256_down:S,conv256_1:I,conv256_2:R,conv256_down_out:A,fc:E};return{params:F,paramMappings:r}}function IT(e,t){const n=it(e,t);function r(a){const s=n(`${a}/scale/weights`,1),c=n(`${a}/scale/biases`,1);return{weights:s,biases:c}}function o(a){const s=n(`${a}/conv/filters`,4),c=n(`${a}/conv/bias`,1),p=r(a);return{conv:{filters:s,bias:c},scale:p}}function i(a){return{conv1:o(`${a}/conv1`),conv2:o(`${a}/conv2`)}}return{extractConvLayerParams:o,extractResidualLayerParams:i}}function sb(e){const t=[],{extractConvLayerParams:n,extractResidualLayerParams:r}=IT(e,t),o=n("conv32_down"),i=r("conv32_1"),a=r("conv32_2"),s=r("conv32_3"),c=r("conv64_down"),p=r("conv64_1"),l=r("conv64_2"),h=r("conv64_3"),d=r("conv128_down"),g=r("conv128_1"),x=r("conv128_2"),w=r("conv256_down"),L=r("conv256_1"),S=r("conv256_2"),I=r("conv256_down_out"),R=e.fc;if(t.push({originalPath:"fc",paramPath:"fc"}),!Cl(R))throw new Error(`expected weightMap[fc] to be a Tensor2D, instead have ${R}`);const A={conv32_down:o,conv32_1:i,conv32_2:a,conv32_3:s,conv64_down:c,conv64_1:p,conv64_2:l,conv64_3:h,conv128_down:d,conv128_1:g,conv128_2:x,conv256_down:w,conv256_1:L,conv256_2:S,conv256_down_out:I,fc:R};return Ye(e,t),{params:A,paramMappings:t}}function Ot(e,t){let n=ob(e,t.conv1);return n=Pl(n,t.conv2),n=N(n,e),n=ie(n),n}function ys(e,t){let n=lc(e,t.conv1);n=Pl(n,t.conv2);let r=mt(e,2,2,"valid");const o=Ce(r.shape),i=r.shape[3]!==n.shape[3],a=r.shape[1]!==n.shape[1]||r.shape[2]!==n.shape[2];if(a){const s=[...n.shape];s[1]=1;const c=Ce(s);n=Z([n,c],1);const p=[...n.shape];p[2]=1;const l=Ce(p);n=Z([n,l],2)}return r=i?Z([r,o],3):r,n=N(r,n),n=ie(n),n}class ir extends We{constructor(){super("FaceRecognitionNet")}forwardInput(e){const{params:t}=this;if(!t)throw new Error("FaceRecognitionNet - load model before inference");return O(()=>{const n=_(e.toBatchTensor(150,!0),"float32"),r=[122.782,117.001,104.298],o=ht(n,r).div(C(256));let i=lc(o,t.conv32_down);i=Re(i,3,2,"valid"),i=Ot(i,t.conv32_1),i=Ot(i,t.conv32_2),i=Ot(i,t.conv32_3),i=ys(i,t.conv64_down),i=Ot(i,t.conv64_1),i=Ot(i,t.conv64_2),i=Ot(i,t.conv64_3),i=ys(i,t.conv128_down),i=Ot(i,t.conv128_1),i=Ot(i,t.conv128_2),i=ys(i,t.conv256_down),i=Ot(i,t.conv256_1),i=Ot(i,t.conv256_2),i=ys(i,t.conv256_down_out);const a=i.mean([1,2]),s=V(a,t.fc);return s})}async forward(e){return this.forwardInput(await ue(e))}async computeFaceDescriptor(e){const t=await ue(e),n=O(()=>Ae(this.forwardInput(t))),r=await Promise.all(n.map(o=>o.data()));return n.forEach(o=>o.dispose()),t.isBatchInput?r:r[0]}getDefaultModelName(){return"face_recognition_model"}extractParamsFromWeigthMap(e){return sb(e)}extractParams(e){return ib(e)}}function Bh(e){const t=new ir;return t.extractWeights(e),t}function so(e,t){const n={descriptor:t};return Object.assign({},e,n)}function Wh(e){return typeof e.age=="number"}function ao(e,t){const n={age:t};return Object.assign({},e,n)}function Uh(e){return(e.gender===Dt.MALE||e.gender===Dt.FEMALE)&&qr(e.genderProbability)}function oo(e,t,n){const r={gender:t,genderProbability:n};return Object.assign({},e,r)}function TT(e,t){function n(c,p){const l=xt(e(3*3*c),[3,3,c,1]),h=ce(e(c)),d=ce(e(c)),g=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:g,batch_norm_variance:x}}function r(c,p,l,h,d){const g=xt(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:g,bias:x}}function o(c,p,l,h){const{filters:d,bias:g}=r(c,p,l,h,!0);return{filters:d,batch_norm_offset:g}}function i(c,p,l){const h=n(c,`${l}/depthwise_conv`),d=o(c,p,1,`${l}/pointwise_conv`);return{depthwise_conv:h,pointwise_conv:d}}function a(){const c=o(3,32,3,"mobilenetv1/conv_0"),p=i(32,64,"mobilenetv1/conv_1"),l=i(64,128,"mobilenetv1/conv_2"),h=i(128,128,"mobilenetv1/conv_3"),d=i(128,256,"mobilenetv1/conv_4"),g=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"),R=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:g,conv_6:x,conv_7:w,conv_8:L,conv_9:S,conv_10:I,conv_11:R,conv_12:A,conv_13:E}}function s(){const c=o(1024,256,1,"prediction_layer/conv_0"),p=o(256,512,3,"prediction_layer/conv_1"),l=o(512,128,1,"prediction_layer/conv_2"),h=o(128,256,3,"prediction_layer/conv_3"),d=o(256,128,1,"prediction_layer/conv_4"),g=o(128,256,3,"prediction_layer/conv_5"),x=o(256,64,1,"prediction_layer/conv_6"),w=o(64,128,3,"prediction_layer/conv_7"),L=r(512,12,1,"prediction_layer/box_predictor_0/box_encoding_predictor"),S=r(512,9,1,"prediction_layer/box_predictor_0/class_predictor"),I=r(1024,24,1,"prediction_layer/box_predictor_1/box_encoding_predictor"),R=r(1024,18,1,"prediction_layer/box_predictor_1/class_predictor"),A=r(512,24,1,"prediction_layer/box_predictor_2/box_encoding_predictor"),E=r(512,18,1,"prediction_layer/box_predictor_2/class_predictor"),F=r(256,24,1,"prediction_layer/box_predictor_3/box_encoding_predictor"),M=r(256,18,1,"prediction_layer/box_predictor_3/class_predictor"),j=r(256,24,1,"prediction_layer/box_predictor_4/box_encoding_predictor"),$=r(256,18,1,"prediction_layer/box_predictor_4/class_predictor"),U=r(128,24,1,"prediction_layer/box_predictor_5/box_encoding_predictor"),Q=r(128,18,1,"prediction_layer/box_predictor_5/class_predictor"),ne={box_encoding_predictor:L,class_predictor:S},he={box_encoding_predictor:I,class_predictor:R},xe={box_encoding_predictor:A,class_predictor:E},Ue={box_encoding_predictor:F,class_predictor:M},vt={box_encoding_predictor:j,class_predictor:$},sn={box_encoding_predictor:U,class_predictor:Q};return{conv_0:c,conv_1:p,conv_2:l,conv_3:h,conv_4:d,conv_5:g,conv_6:x,conv_7:w,box_predictor_0:ne,box_predictor_1:he,box_predictor_2:xe,box_predictor_3:Ue,box_predictor_4:vt,box_predictor_5:sn}}return{extractMobilenetV1Params:a,extractPredictionLayerParams:s}}function ab(e){const t=[],{extractWeights:n,getRemainingWeights:r}=Ve(e),{extractMobilenetV1Params:o,extractPredictionLayerParams:i}=TT(n,t),a=o(),s=i(),c=Sr(n(5118*4),[1,5118,4]),p={extra_dim:c};if(t.push({paramPath:"output_layer/extra_dim"}),r().length!==0)throw new Error(`weights remaing after extract: ${r().length}`);return{params:{mobilenetv1:a,prediction_layer:s,output_layer:p},paramMappings:t}}function AT(e,t){const n=it(e,t);function r(p,l,h){const d=n(`${p}/Conv2d_${l}_pointwise/weights`,4,`${h}/filters`),g=n(`${p}/Conv2d_${l}_pointwise/convolution_bn_offset`,1,`${h}/batch_norm_offset`);return{filters:d,batch_norm_offset:g}}function o(p){const l=`mobilenetv1/conv_${p}`,h=`MobilenetV1/Conv2d_${p}_depthwise`,d=`${l}/depthwise_conv`,g=`${l}/pointwise_conv`,x=n(`${h}/depthwise_weights`,4,`${d}/filters`),w=n(`${h}/BatchNorm/gamma`,1,`${d}/batch_norm_scale`),L=n(`${h}/BatchNorm/beta`,1,`${d}/batch_norm_offset`),S=n(`${h}/BatchNorm/moving_mean`,1,`${d}/batch_norm_mean`),I=n(`${h}/BatchNorm/moving_variance`,1,`${d}/batch_norm_variance`);return{depthwise_conv:{filters:x,batch_norm_scale:w,batch_norm_offset:L,batch_norm_mean:S,batch_norm_variance:I},pointwise_conv:r("MobilenetV1",p,g)}}function i(){return{conv_0:r("MobilenetV1",0,"mobilenetv1/conv_0"),conv_1:o(1),conv_2:o(2),conv_3:o(3),conv_4:o(4),conv_5:o(5),conv_6:o(6),conv_7:o(7),conv_8:o(8),conv_9:o(9),conv_10:o(10),conv_11:o(11),conv_12:o(12),conv_13:o(13)}}function a(p,l){const h=n(`${p}/weights`,4,`${l}/filters`),d=n(`${p}/biases`,1,`${l}/bias`);return{filters:h,bias:d}}function s(p){const l=a(`Prediction/BoxPredictor_${p}/BoxEncodingPredictor`,`prediction_layer/box_predictor_${p}/box_encoding_predictor`),h=a(`Prediction/BoxPredictor_${p}/ClassPredictor`,`prediction_layer/box_predictor_${p}/class_predictor`);return{box_encoding_predictor:l,class_predictor:h}}function c(){return{conv_0:r("Prediction",0,"prediction_layer/conv_0"),conv_1:r("Prediction",1,"prediction_layer/conv_1"),conv_2:r("Prediction",2,"prediction_layer/conv_2"),conv_3:r("Prediction",3,"prediction_layer/conv_3"),conv_4:r("Prediction",4,"prediction_layer/conv_4"),conv_5:r("Prediction",5,"prediction_layer/conv_5"),conv_6:r("Prediction",6,"prediction_layer/conv_6"),conv_7:r("Prediction",7,"prediction_layer/conv_7"),box_predictor_0:s(0),box_predictor_1:s(1),box_predictor_2:s(2),box_predictor_3:s(3),box_predictor_4:s(4),box_predictor_5:s(5)}}return{extractMobilenetV1Params:i,extractPredictionLayerParams:c}}function cb(e){const t=[],{extractMobilenetV1Params:n,extractPredictionLayerParams:r}=AT(e,t),o=e["Output/extra_dim"];if(t.push({originalPath:"Output/extra_dim",paramPath:"output_layer/extra_dim"}),!nn(o))throw new Error(`expected weightMap['Output/extra_dim'] to be a Tensor3D, instead have ${o}`);const i={mobilenetv1:n(),prediction_layer:r(),output_layer:{extra_dim:o}};return Ye(e,t),{params:i,paramMappings:t}}function Lt(e,t,n){return O(()=>{let r=ve(e,t.filters,n,"same");return r=N(r,t.batch_norm_offset),Rr(r,0,6)})}const NT=.0010000000474974513;function RT(e,t,n){return O(()=>{let r=wn(e,t.filters,n,"same");return r=jt(r,t.batch_norm_mean,t.batch_norm_variance,t.batch_norm_offset,t.batch_norm_scale,NT),Rr(r,0,6)})}function _T(e){return[2,4,6,12].some(t=>t===e)?[2,2]:[1,1]}function pb(e,t){return O(()=>{let n,r=Lt(e,t.conv_0,[2,2]);const o=[t.conv_1,t.conv_2,t.conv_3,t.conv_4,t.conv_5,t.conv_6,t.conv_7,t.conv_8,t.conv_9,t.conv_10,t.conv_11,t.conv_12,t.conv_13];if(o.forEach((i,a)=>{const s=a+1,c=_T(s);r=RT(r,i.depthwise_conv,c),r=Lt(r,i.pointwise_conv,[1,1]),s===11&&(n=r)}),n===null)throw new Error("mobileNetV1 - output of conv layer 11 is null");return{out:r,conv11:n}})}function lb(e,t,n,r,o){const i=e.shape[0],a=Math.min(n,i),s=t.map((l,h)=>({score:l,boxIndex:h})).filter(l=>l.score>o).sort((l,h)=>h.score-l.score),c=l=>l<=r?1:0,p=[];return s.forEach(l=>{if(p.length>=a)return;const h=l.score;for(let d=p.length-1;d>=0;--d){const g=CT(e,l.boxIndex,p[d]);if(g===0)continue;if(l.score*=c(g),l.score<=o)break}h===l.score&&p.push(l.boxIndex)}),p}function CT(e,t,n){const r=e.arraySync(),o=Math.min(r[t][0],r[t][2]),i=Math.min(r[t][1],r[t][3]),a=Math.max(r[t][0],r[t][2]),s=Math.max(r[t][1],r[t][3]),c=Math.min(r[n][0],r[n][2]),p=Math.min(r[n][1],r[n][3]),l=Math.max(r[n][0],r[n][2]),h=Math.max(r[n][1],r[n][3]),d=(a-o)*(s-i),g=(l-c)*(h-p);if(d<=0||g<=0)return 0;const x=Math.max(o,c),w=Math.max(i,p),L=Math.min(a,l),S=Math.min(s,h),I=Math.max(L-x,0)*Math.max(S-w,0);return I/(d+g-I)}function ET(e){const t=Ae(K(e,[1,0])),n=[k(t[2],t[0]),k(t[3],t[1])],r=[N(t[0],D(n[0],C(2))),N(t[1],D(n[1],C(2)))];return{sizes:n,centers:r}}function OT(e,t){const{sizes:n,centers:r}=ET(e),o=Ae(K(t,[1,0])),i=D(v(Te(D(o[2],C(5))),n[0]),C(2)),a=N(v(D(o[0],C(10)),n[0]),r[0]),s=D(v(Te(D(o[3],C(5))),n[1]),C(2)),c=N(v(D(o[1],C(10)),n[1]),r[1]);return K(Fe([k(a,i),k(c,s),N(a,i),N(c,s)]),[1,0])}function hb(e,t,n){return O(()=>{const r=e.shape[0];let o=OT(y(Gt(n.extra_dim,[r,1,1]),[-1,4]),y(e,[-1,4]));o=y(o,[r,o.shape[0]/r,4]);const i=ft(P(t,[0,0,1],[-1,-1,-1]));let a=P(i,[0,0,0],[-1,-1,1]);a=y(a,[r,a.shape[1]]);const s=Ae(o),c=Ae(a);return{boxes:s,scores:c}})}function Qn(e,t){return O(()=>{const n=e.shape[0],r=y(Zn(e,t.box_encoding_predictor),[n,-1,1,4]),o=y(Zn(e,t.class_predictor),[n,-1,3]);return{boxPredictionEncoding:r,classPrediction:o}})}function ub(e,t,n){return O(()=>{const r=Lt(e,n.conv_0,[1,1]),o=Lt(r,n.conv_1,[2,2]),i=Lt(o,n.conv_2,[1,1]),a=Lt(i,n.conv_3,[2,2]),s=Lt(a,n.conv_4,[1,1]),c=Lt(s,n.conv_5,[2,2]),p=Lt(c,n.conv_6,[1,1]),l=Lt(p,n.conv_7,[2,2]),h=Qn(t,n.box_predictor_0),d=Qn(e,n.box_predictor_1),g=Qn(o,n.box_predictor_2),x=Qn(a,n.box_predictor_3),w=Qn(c,n.box_predictor_4),L=Qn(l,n.box_predictor_5),S=Z([h.boxPredictionEncoding,d.boxPredictionEncoding,g.boxPredictionEncoding,x.boxPredictionEncoding,w.boxPredictionEncoding,L.boxPredictionEncoding],1),I=Z([h.classPrediction,d.classPrediction,g.classPrediction,x.classPrediction,w.classPrediction,L.classPrediction],1);return{boxPredictions:S,classPredictions:I}})}class lt{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 In extends We{constructor(){super("SsdMobilenetv1")}forwardInput(e){const{params:t}=this;if(!t)throw new Error("SsdMobilenetv1 - load model before inference");return O(()=>{const n=_(e.toBatchTensor(512,!1),"float32"),r=k(v(n,C(.007843137718737125)),C(1)),o=pb(r,t.mobilenetv1),{boxPredictions:i,classPredictions:a}=ub(o.out,o.conv11,t.prediction_layer);return hb(i,a,t.output_layer)})}async forward(e){return this.forwardInput(await ue(e))}async locateFaces(e,t={}){const{maxResults:n,minConfidence:r}=new lt(t),o=await ue(e),{boxes:i,scores:a}=this.forwardInput(o),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=lb(s,p,n,l,r),d=o.getReshapedInputDimensions(0),g=o.inputSize,x=g/d.width,w=g/d.height,L=s.arraySync(),S=h.map(I=>{const[R,A]=[Math.max(0,L[I][0]),Math.min(1,L[I][2])].map(M=>M*w),[E,F]=[Math.max(0,L[I][1]),Math.min(1,L[I][3])].map(M=>M*x);return new me(p[I],new pr(E,R,F-E,A-R),{height:o.getInputHeight(0),width:o.getInputWidth(0)})});return s.dispose(),c.dispose(),S}getDefaultModelName(){return"ssd_mobilenetv1_model"}extractParamsFromWeigthMap(e){return cb(e)}extractParams(e){return ab(e)}}function yc(e){const t=new In;return t.extractWeights(e),t}function mh(e){return yc(e)}class fh extends In{}const db=.4,mb=[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)],fb=[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)],gb=[117.001,114.697,97.404],bb="tiny_yolov2_model",wb="tiny_yolov2_separable_conv_model";const hc=e=>typeof e=="number";function Es(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(!hc(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=>hc(t.x)&&hc(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(hc)))throw new Error(`config.meanRgb has to be an array of shape [number, number, number], have: ${JSON.stringify(e.meanRgb)}`)}function Kr(e){return O(()=>{const t=v(e,C(.10000000149011612));return N(ie(k(e,t)),t)})}function rn(e,t){return O(()=>{let n=He(e,[[0,0],[1,1],[1,1],[0,0]]);return n=ve(n,t.conv.filters,[1,1],"valid"),n=k(n,t.bn.sub),n=v(n,t.bn.truediv),n=N(n,t.conv.bias),Kr(n)})}function on(e,t){return O(()=>{let n=He(e,[[0,0],[1,1],[1,1],[0,0]]);return n=Wr(n,t.depthwise_filter,t.pointwise_filter,[1,1],"valid"),n=N(n,t.bias),Kr(n)})}function kT(e,t){const n=Hr(e,t);function r(a,s){const c=ce(e(a)),p=ce(e(a));return t.push({paramPath:`${s}/sub`},{paramPath:`${s}/truediv`}),{sub:c,truediv:p}}function o(a,s,c){const p=n(a,s,3,`${c}/conv`),l=r(s,`${c}/bn`);return{conv:p,bn:l}}const i=Yr(e,t);return{extractConvParams:n,extractConvWithBatchNormParams:o,extractSeparableConvParams:i}}function xb(e,t,n,r){const{extractWeights:o,getRemainingWeights:i}=Ve(e),a=[],{extractConvParams:s,extractConvWithBatchNormParams:c,extractSeparableConvParams:p}=kT(o,a);let l;if(t.withSeparableConvs){const[h,d,g,x,w,L,S,I,R]=r,A=t.isFirstLayerConv2d?s(h,d,3,"conv0"):p(h,d,"conv0"),E=p(d,g,"conv1"),F=p(g,x,"conv2"),M=p(x,w,"conv3"),j=p(w,L,"conv4"),$=p(L,S,"conv5"),U=I?p(S,I,"conv6"):void 0,Q=R?p(I,R,"conv7"):void 0,ne=s(R||I||S,5*n,1,"conv8");l={conv0:A,conv1:E,conv2:F,conv3:M,conv4:j,conv5:$,conv6:U,conv7:Q,conv8:ne}}else{const[h,d,g,x,w,L,S,I,R]=r,A=c(h,d,"conv0"),E=c(d,g,"conv1"),F=c(g,x,"conv2"),M=c(x,w,"conv3"),j=c(w,L,"conv4"),$=c(L,S,"conv5"),U=c(S,I,"conv6"),Q=c(I,R,"conv7"),ne=s(R,5*n,1,"conv8");l={conv0:A,conv1:E,conv2:F,conv3:M,conv4:j,conv5:$,conv6:U,conv7:Q,conv8:ne}}if(i().length!==0)throw new Error(`weights remaing after extract: ${i().length}`);return{params:l,paramMappings:a}}function DT(e,t){const n=it(e,t);function r(s){const c=n(`${s}/sub`,1),p=n(`${s}/truediv`,1);return{sub:c,truediv:p}}function o(s){const c=n(`${s}/filters`,4),p=n(`${s}/bias`,1);return{filters:c,bias:p}}function i(s){const c=o(`${s}/conv`),p=r(`${s}/bn`);return{conv:c,bn:p}}const a=Vr(n);return{extractConvParams:o,extractConvWithBatchNormParams:i,extractSeparableConvParams:a}}function yb(e,t){const n=[],{extractConvParams:r,extractConvWithBatchNormParams:o,extractSeparableConvParams:i}=DT(e,n);let a;if(t.withSeparableConvs){const s=t.filterSizes&&t.filterSizes.length||9;a={conv0:t.isFirstLayerConv2d?r("conv0"):i("conv0"),conv1:i("conv1"),conv2:i("conv2"),conv3:i("conv3"),conv4:i("conv4"),conv5:i("conv5"),conv6:s>7?i("conv6"):void 0,conv7:s>8?i("conv7"):void 0,conv8:r("conv8")}}else a={conv0:o("conv0"),conv1:o("conv1"),conv2:o("conv2"),conv3:o("conv3"),conv4:o("conv4"),conv5:o("conv5"),conv6:o("conv6"),conv7:o("conv7"),conv8:r("conv8")};return Ye(e,n),{params:a,paramMappings:n}}var Os;(function(e){e[e.XS=224]="XS",e[e.SM=320]="SM",e[e.MD=416]="MD",e[e.LG=608]="LG"})(Os||(Os={}));class kt{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 Jr extends We{constructor(e){super("TinyYolov2");Es(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=rn(e,t.conv0);return n=Re(n,[2,2],[2,2],"same"),n=rn(n,t.conv1),n=Re(n,[2,2],[2,2],"same"),n=rn(n,t.conv2),n=Re(n,[2,2],[2,2],"same"),n=rn(n,t.conv3),n=Re(n,[2,2],[2,2],"same"),n=rn(n,t.conv4),n=Re(n,[2,2],[2,2],"same"),n=rn(n,t.conv5),n=Re(n,[2,2],[1,1],"same"),n=rn(n,t.conv6),n=rn(n,t.conv7),Zn(n,t.conv8,"valid",!1)}runMobilenet(e,t){let n=this.config.isFirstLayerConv2d?Kr(Zn(e,t.conv0,"valid",!1)):on(e,t.conv0);return n=Re(n,[2,2],[2,2],"same"),n=on(n,t.conv1),n=Re(n,[2,2],[2,2],"same"),n=on(n,t.conv2),n=Re(n,[2,2],[2,2],"same"),n=on(n,t.conv3),n=Re(n,[2,2],[2,2],"same"),n=on(n,t.conv4),n=Re(n,[2,2],[2,2],"same"),n=on(n,t.conv5),n=Re(n,[2,2],[1,1],"same"),n=t.conv6?on(n,t.conv6):n,n=t.conv7?on(n,t.conv7):n,Zn(n,t.conv8,"valid",!1)}forwardInput(e,t){const{params:n}=this;if(!n)throw new Error("TinyYolov2 - load model before inference");return O(()=>{let r=_(e.toBatchTensor(t,!1),"float32");return r=this.config.meanRgb?ht(r,this.config.meanRgb):r,r=r.div(C(256)),this.config.withSeparableConvs?this.runMobilenet(r,n):this.runTinyYolov2(r,n)})}async forward(e,t){return await this.forwardInput(await ue(e),t)}async detect(e,t={}){const{inputSize:n,scoreThreshold:r}=new kt(t),o=await ue(e),i=await this.forwardInput(o,n),a=O(()=>Ae(i)[0].expandDims()),s={width:o.getInputWidth(0),height:o.getInputHeight(0)},c=await this.extractBoxes(a,o.getReshapedInputDimensions(0),r);i.dispose(),a.dispose();const p=c.map(w=>w.box),l=c.map(w=>w.score),h=c.map(w=>w.classScore),d=c.map(w=>this.config.classes[w.label]),g=Fs(p.map(w=>w.rescale(n)),l,this.config.iouThreshold,!0),x=g.map(w=>new _n(l[w],h[w],d[w],p[w],s));return x}getDefaultModelName(){return""}extractParamsFromWeigthMap(e){return yb(e,this.config)}extractParams(e){const t=this.config.filterSizes||Jr.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 xb(e,this.config,this.boxEncodingSize,t)}async extractBoxes(e,t,n){const{width:r,height:o}=t,i=Math.max(r,o),a=i/r,s=i/o,c=e.shape[1],p=this.config.anchors.length,[l,h,d]=O(()=>{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]),R=this.withClassScores?Ln(L.slice([0,0,0,5],[c,c,p,this.config.classes.length]),3):C(0);return[S,I,R]}),g=[],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 R=or(x[L][S][I][0]);if(!n||R>n){const A=(S+or(w[L][S][I][0]))/c*a,E=(L+or(w[L][S][I][1]))/c*s,F=Math.exp(w[L][S][I][2])*this.config.anchors[I].x/c*a,M=Math.exp(w[L][S][I][3])*this.config.anchors[I].y/c*s,j=A-F/2,$=E-M/2,U={row:L,col:S,anchor:I},{classScore:Q,label:ne}=this.withClassScores?await this.extractPredictedClass(d,U):{classScore:1,label:0};g.push(As({box:new hr(j,$,j+F,$+M),score:R,classScore:R*Q,label:ne},U))}}return l.dispose(),h.dispose(),d.dispose(),g}async extractPredictedClass(e,t){const{row:n,col:r,anchor:o}=t,i=await e.array();return Array(this.config.classes.length).fill(0).map((a,s)=>i[n][r][o][s]).map((a,s)=>({classScore:a,label:s})).reduce((a,s)=>a.classScore>s.classScore?a:s)}}Jr.DEFAULT_FILTER_SIZES=[3,16,32,64,128,256,512,1024,1024];class nr extends Jr{constructor(e=!0){const t=Object.assign({},{withSeparableConvs:e,iouThreshold:db,classes:["face"]},e?{anchors:fb,meanRgb:gb}:{anchors:mb,withClassScores:!0});super(t)}get withSeparableConvs(){return this.config.withSeparableConvs}get anchors(){return this.config.anchors}async locateFaces(e,t){const n=await this.detect(e,t);return n.map(r=>new me(r.score,r.relativeBox,{width:r.imageWidth,height:r.imageHeight}))}getDefaultModelName(){return this.withSeparableConvs?wb:bb}extractParamsFromWeigthMap(e){return super.extractParamsFromWeigthMap(e)}}function uh(e,t=!0){const n=new nr(t);return n.extractWeights(e),n}class ks extends kt{constructor(){super(...arguments);this._name="TinyFaceDetectorOptions"}}class ut{async then(e){return e(await this.run())}async run(){throw new Error("ComposableTask - run is not implemented")}}async function er(e,t,n,r,o=({alignedRect:i})=>i){const i=e.map(c=>pn(c)?o(c):c.detection),a=r||(t instanceof te?await Nn(t,i):await An(t,i)),s=await n(a);return a.forEach(c=>c instanceof te&&c.dispose()),s}async function Xr(e,t,n,r,o){return er([e],t,async i=>n(i[0]),r,o)}const Lb=.4,vb=[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)],Sb=[117.001,114.697,97.404];class rr extends Jr{constructor(){const e={withSeparableConvs:!0,iouThreshold:Lb,classes:["face"],anchors:vb,meanRgb:Sb,isFirstLayerConv2d:!0,filterSizes:[3,16,32,64,128,256,512]};super(e)}get anchors(){return this.config.anchors}async locateFaces(e,t){const n=await this.detect(e,t);return n.map(r=>new me(r.score,r.relativeBox,{width:r.imageWidth,height:r.imageHeight}))}getDefaultModelName(){return"tiny_face_detector_model"}extractParamsFromWeigthMap(e){return super.extractParamsFromWeigthMap(e)}}const oe={ssdMobilenetv1:new In,tinyFaceDetector:new rr,tinyYolov2:new nr,faceLandmark68Net:new sr,faceLandmark68TinyNet:new zs,faceRecognitionNet:new ir,faceExpressionNet:new Ys,ageGenderNet:new ta},vc=(e,t)=>oe.ssdMobilenetv1.locateFaces(e,t),wh=(e,t)=>oe.tinyFaceDetector.locateFaces(e,t),xh=(e,t)=>oe.tinyYolov2.locateFaces(e,t),Sc=e=>oe.faceLandmark68Net.detectLandmarks(e),yh=e=>oe.faceLandmark68TinyNet.detectLandmarks(e),Lh=e=>oe.faceRecognitionNet.computeFaceDescriptor(e),vh=e=>oe.faceExpressionNet.predictExpressions(e),Sh=e=>oe.ageGenderNet.predictAgeAndGender(e),Ic=e=>oe.ssdMobilenetv1.load(e),Ih=e=>oe.tinyFaceDetector.load(e),Th=e=>oe.tinyYolov2.load(e),Ah=e=>oe.faceLandmark68Net.load(e),Nh=e=>oe.faceLandmark68TinyNet.load(e),Rh=e=>oe.faceRecognitionNet.load(e),_h=e=>oe.faceExpressionNet.load(e),Ch=e=>oe.ageGenderNet.load(e),Eh=Ic,Oh=vc,kh=Sc;class Ib extends ut{constructor(e,t,n){super();this.parentTask=e,this.input=t,this.extractedFaces=n}}class Ss extends Ib{async run(){const e=await this.parentTask,t=await er(e,this.input,async n=>await Promise.all(n.map(r=>oe.faceExpressionNet.predictExpressions(r))),this.extractedFaces);return e.map((n,r)=>io(n,t[r]))}withAgeAndGender(){return new Ls(this,this.input)}}class Is extends Ib{async run(){const e=await this.parentTask;if(!e)return;const t=await Xr(e,this.input,n=>oe.faceExpressionNet.predictExpressions(n),this.extractedFaces);return io(e,t)}withAgeAndGender(){return new vs(this,this.input)}}class eo extends Ss{withAgeAndGender(){return new Zr(this,this.input)}withFaceDescriptors(){return new an(this,this.input)}}class to extends Is{withAgeAndGender(){return new Qr(this,this.input)}withFaceDescriptor(){return new cn(this,this.input)}}class Tb extends ut{constructor(e,t,n){super();this.parentTask=e,this.input=t,this.extractedFaces=n}}class Ls extends Tb{async run(){const e=await this.parentTask,t=await er(e,this.input,async n=>await Promise.all(n.map(r=>oe.ageGenderNet.predictAgeAndGender(r))),this.extractedFaces);return e.map((n,r)=>{const{age:o,gender:i,genderProbability:a}=t[r];return ao(oo(n,i,a),o)})}withFaceExpressions(){return new Ss(this,this.input)}}class vs extends Tb{async run(){const e=await this.parentTask;if(!e)return;const{age:t,gender:n,genderProbability:r}=await Xr(e,this.input,o=>oe.ageGenderNet.predictAgeAndGender(o),this.extractedFaces);return ao(oo(e,n,r),t)}withFaceExpressions(){return new Is(this,this.input)}}class Zr extends Ls{withFaceExpressions(){return new eo(this,this.input)}withFaceDescriptors(){return new an(this,this.input)}}class Qr extends vs{withFaceExpressions(){return new to(this,this.input)}withFaceDescriptor(){return new cn(this,this.input)}}class Ps extends ut{constructor(e,t){super();this.parentTask=e,this.input=t}}class an extends Ps{async run(){const e=await this.parentTask,t=await er(e,this.input,n=>Promise.all(n.map(r=>oe.faceRecognitionNet.computeFaceDescriptor(r))),null,n=>n.landmarks.align(null,{useDlibAlignment:!0}));return t.map((n,r)=>so(e[r],n))}withFaceExpressions(){return new eo(this,this.input)}withAgeAndGender(){return new Zr(this,this.input)}}class cn extends Ps{async run(){const e=await this.parentTask;if(!e)return;const t=await Xr(e,this.input,n=>oe.faceRecognitionNet.computeFaceDescriptor(n),null,n=>n.landmarks.align(null,{useDlibAlignment:!0}));return so(e,t)}withFaceExpressions(){return new to(this,this.input)}withAgeAndGender(){return new Qr(this,this.input)}}class $s extends ut{constructor(e,t,n){super();this.parentTask=e,this.input=t,this.useTinyLandmarkNet=n}get landmarkNet(){return this.useTinyLandmarkNet?oe.faceLandmark68TinyNet:oe.faceLandmark68Net}}class js extends $s{async run(){const e=await this.parentTask,t=e.map(o=>o.detection),n=this.input instanceof te?await Nn(this.input,t):await An(this.input,t),r=await Promise.all(n.map(o=>this.landmarkNet.detectLandmarks(o)));return n.forEach(o=>o instanceof te&&o.dispose()),e.map((o,i)=>Tn(o,r[i]))}withFaceExpressions(){return new eo(this,this.input)}withAgeAndGender(){return new Zr(this,this.input)}withFaceDescriptors(){return new an(this,this.input)}}class Gs extends $s{async run(){const e=await this.parentTask;if(!e)return;const{detection:t}=e,n=this.input instanceof te?await Nn(this.input,[t]):await An(this.input,[t]),r=await this.landmarkNet.detectLandmarks(n[0]);return n.forEach(o=>o instanceof te&&o.dispose()),Tn(e,r)}withFaceExpressions(){return new to(this,this.input)}withAgeAndGender(){return new Qr(this,this.input)}withFaceDescriptor(){return new cn(this,this.input)}}class Ws extends ut{constructor(e,t=new lt){super();this.input=e,this.options=t}}class ro extends Ws{async run(){const{input:e,options:t}=this,n=t instanceof ks?r=>oe.tinyFaceDetector.locateFaces(r,t):t instanceof lt?r=>oe.ssdMobilenetv1.locateFaces(r,t):t instanceof kt?r=>oe.tinyYolov2.locateFaces(r,t):null;if(!n)throw new Error("detectFaces - expected options to be instance of TinyFaceDetectorOptions | SsdMobilenetv1Options | MtcnnOptions | TinyYolov2Options");return n(e)}runAndExtendWithFaceDetections(){return new Promise(async e=>{const t=await this.run();return e(t.map(n=>ln({},n)))})}withFaceLandmarks(e=!1){return new js(this.runAndExtendWithFaceDetections(),this.input,e)}withFaceExpressions(){return new Ss(this.runAndExtendWithFaceDetections(),this.input)}withAgeAndGender(){return new Ls(this.runAndExtendWithFaceDetections(),this.input)}}class Bs extends Ws{async run(){const e=await new ro(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?ln({},t):void 0)})}withFaceLandmarks(e=!1){return new Gs(this.runAndExtendWithFaceDetection(),this.input,e)}withFaceExpressions(){return new Is(this.runAndExtendWithFaceDetection(),this.input)}withAgeAndGender(){return new vs(this.runAndExtendWithFaceDetection(),this.input)}}function Dh(e,t=new lt){return new Bs(e,t)}function no(e,t=new lt){return new ro(e,t)}async function Tc(e,t){return console.warn("allFacesSsdMobilenetv1 is deprecated and will be removed soon, use the high level api instead"),await no(e,new lt(t?{minConfidence:t}:{})).withFaceLandmarks().withFaceDescriptors()}async function Fh(e,t={}){return console.warn("allFacesTinyYolov2 is deprecated and will be removed soon, use the high level api instead"),await no(e,new kt(t)).withFaceLandmarks().withFaceDescriptors()}const Mh=Tc;function Vs(e,t){if(e.length!==t.length)throw new Error("euclideanDistance: arr1.length !== arr2.length");const n=Array.from(e),r=Array.from(t);return Math.sqrt(n.map((o,i)=>o-r[i]).reduce((o,i)=>o+Math.pow(i,2),0))}class Ac{constructor(e,t=.6){this._distanceThreshold=t;const n=Array.isArray(e)?e:[e];if(!n.length)throw new Error("FaceRecognizer.constructor - expected atleast one input");let r=1;const o=()=>`person ${r++}`;this._labeledDescriptors=n.map(i=>{if(i instanceof fn)return i;if(i instanceof Float32Array)return new fn(o(),[i]);if(i.descriptor&&i.descriptor instanceof Float32Array)return new fn(o(),[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=>Vs(n,e)).reduce((n,r)=>n+r,0)/(t.length||1)}matchDescriptor(e){return this.labeledDescriptors.map(({descriptors:t,label:n})=>new lo(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 lo("unknown",t.distance)}toJSON(){return{distanceThreshold:this.distanceThreshold,labeledDescriptors:this.labeledDescriptors.map(e=>e.toJSON())}}static fromJSON(e){const t=e.labeledDescriptors.map(n=>fn.fromJSON(n));return new Ac(t,e.distanceThreshold)}}function dh(e){const t=new rr;return t.extractWeights(e),t}function Lc(e,t){const{width:n,height:r}=new Ke(t.width,t.height);if(n<=0||r<=0)throw new Error(`resizeResults - invalid dimensions: ${JSON.stringify({width:n,height:r})}`);if(Array.isArray(e))return e.map(o=>Lc(o,{width:n,height:r}));if(pn(e)){const o=e.detection.forSize(n,r),i=e.unshiftedLandmarks.forSize(o.box.width,o.box.height);return Tn(ln(e,o),i)}return It(e)?ln(e,e.detection.forSize(n,r)):e instanceof st||e instanceof me?e.forSize(n,r):e}var lh="0.5.2";return Hh();})();
/**
* @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