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

100 lines
310 KiB
JavaScript

(()=>{var Fs=Object.defineProperty,$b=Object.prototype.hasOwnProperty,ke=(e,t)=>()=>(t||(t={exports:{}},e(t.exports,t)),t.exports),uu=e=>Fs(e,"__esModule",{value:!0}),me=(e,t)=>{uu(e);for(var n in t)Fs(e,n,{get:t[n],enumerable:!0})},T=(e,t)=>{if(uu(e),typeof t=="object"||typeof t=="function")for(let n in t)!$b.call(e,n)&&n!=="default"&&Fs(e,n,{get:()=>t[n],enumerable:!0});return e},ee=e=>e&&e.__esModule?e:T(Fs({},"default",{value:e,enumerable:!0}),e);var mu=ke((du,Ka)=>{(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})(du,typeof Ka=="object"&&Ka,typeof define=="function"&&define)});var gu=ke((fu,Ja)=>{(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,m=(c.next()>>>0)/4294967296,b=(h+m)/(1<<21);while(b===0);return b},l.int32=c.next,l.quick=l,p&&(typeof p=="object"&&o(p,c),l.state=function(){return o(c,{})}),l}t&&t.exports?t.exports=i:n&&n.amd?n(function(){return i}):this.xor128=i})(fu,typeof Ja=="object"&&Ja,typeof define=="function"&&define)});var wu=ke((bu,Xa)=>{(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,m=(c.next()>>>0)/4294967296,b=(h+m)/(1<<21);while(b===0);return b},l.int32=c.next,l.quick=l,p&&(typeof p=="object"&&o(p,c),l.state=function(){return o(c,{})}),l}t&&t.exports?t.exports=i:n&&n.amd?n(function(){return i}):this.xorwow=i})(bu,typeof Xa=="object"&&Xa,typeof define=="function"&&define)});var xu=ke((yu,Za)=>{(function(e,t,n){function r(a){var s=this;s.next=function(){var p=s.x,l=s.i,h,m,b;return h=p[l],h^=h>>>7,m=h^h<<24,h=p[l+1&7],m^=h^h>>>10,h=p[l+3&7],m^=h^h>>>3,h=p[l+4&7],m^=h^h<<7,h=p[l+7&7],h=h^h<<13,m^=h^h<<9,p[l]=m,s.i=l+1&7,m};function c(p,l){var h,m,b=[];if(l===(l|0))m=b[0]=l;else for(l=""+l,h=0;h<l.length;++h)b[h&7]=b[h&7]<<15^l.charCodeAt(h)+b[h+1&7]<<13;for(;b.length<8;)b.push(0);for(h=0;h<8&&b[h]===0;++h);for(h==8?m=b[7]=-1:m=b[h],p.x=b,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,m=(c.next()>>>0)/4294967296,b=(h+m)/(1<<21);while(b===0);return b},l.int32=c.next,l.quick=l,p&&(p.x&&o(p,c),l.state=function(){return o(c,{})}),l}t&&t.exports?t.exports=i:n&&n.amd?n(function(){return i}):this.xorshift7=i})(yu,typeof Za=="object"&&Za,typeof define=="function"&&define)});var Su=ke((Lu,Qa)=>{(function(e,t,n){function r(a){var s=this;s.next=function(){var p=s.w,l=s.X,h=s.i,m,b;return s.w=p=p+1640531527|0,b=l[h+34&127],m=l[h=h+1&127],b^=b<<13,m^=m<<17,b^=b>>>15,m^=m>>>12,b=l[h]=b^m,s.i=h,b+(p^p>>>16)|0};function c(p,l){var h,m,b,y,w,L=[],v=128;for(l===(l|0)?(m=l,l=null):(l=l+"\0",m=0,v=Math.max(v,l.length)),b=0,y=-32;y<v;++y)l&&(m^=l.charCodeAt((y+32)%l.length)),y===0&&(w=m),m^=m<<10,m^=m>>>15,m^=m<<4,m^=m>>>13,y>=0&&(w=w+1640531527|0,h=L[y&127]^=m+w,b=h==0?b+1:0);for(b>=128&&(L[(l&&l.length||0)&127]=-1),b=127,y=4*128;y>0;--y)m=L[b+34&127],h=L[b=b+1&127],m^=m<<13,h^=h<<17,m^=m>>>15,h^=h>>>12,L[b]=m^h;p.w=w,p.X=L,p.i=b}c(s,a)}function o(a,s){return s.i=a.i,s.w=a.w,s.X=a.X.slice(),s}function i(a,s){a==null&&(a=+new Date());var c=new r(a),p=s&&s.state,l=function(){return(c.next()>>>0)/4294967296};return l.double=function(){do var h=c.next()>>>11,m=(c.next()>>>0)/4294967296,b=(h+m)/(1<<21);while(b===0);return b},l.int32=c.next,l.quick=l,p&&(p.X&&o(p,c),l.state=function(){return o(c,{})}),l}t&&t.exports?t.exports=i:n&&n.amd?n(function(){return i}):this.xor4096=i})(Lu,typeof Qa=="object"&&Qa,typeof define=="function"&&define)});var Iu=ke((vu,ec)=>{(function(e,t,n){function r(a){var s=this,c="";s.next=function(){var l=s.b,h=s.c,m=s.d,b=s.a;return l=l<<25^l>>>7^h,h=h-m|0,m=m<<24^m>>>8^b,b=b-l|0,s.b=l=l<<20^l>>>12^h,s.c=h=h-m|0,s.d=m<<16^h>>>16^b,s.a=b-l|0},s.a=0,s.b=0,s.c=2654435769|0,s.d=1367130551,a===Math.floor(a)?(s.a=a/4294967296|0,s.b=a|0):c+=a;for(var p=0;p<c.length+20;p++)s.b^=c.charCodeAt(p)|0,s.next()}function 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,m=(c.next()>>>0)/4294967296,b=(h+m)/(1<<21);while(b===0);return b},l.int32=c.next,l.quick=l,p&&(typeof p=="object"&&o(p,c),l.state=function(){return o(c,{})}),l}t&&t.exports?t.exports=i:n&&n.amd?n(function(){return i}):this.tychei=i})(vu,typeof ec=="object"&&ec,typeof define=="function"&&define)});var Tu=ke(()=>{});var Au=ke((qT,Ms)=>{(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 m(R,N,O){var M=[];N=N==!0?{entropy:!0}:N||{};var D=L(w(N.entropy?[R,A(e)]:R??v(),3),M),G=new b(M),$=function(){for(var j=G.g(o),oe=s,ie=0;j<c;)j=(j+ie)*r,oe*=r,ie=G.g(1);for(;j>=p;)j/=2,oe/=2,ie>>>=1;return(j+ie)/oe};return $.int32=function(){return G.g(4)|0},$.quick=function(){return G.g(4)/4294967296},$.double=$,L(A(G.S),e),(N.pass||O||function(j,oe,ie,ue){return ue&&(ue.S&&y(ue,G),j.state=function(){return y(G,{})}),ie?(t[a]=j,oe):j})($,D,"global"in N?N.global:this==t,N.state)}t["seed"+a]=m;function b(R){var N,O=R.length,M=this,D=0,G=M.i=M.j=0,$=M.S=[];for(O||(R=[O++]);D<r;)$[D]=D++;for(D=0;D<r;D++)$[D]=$[G=l&G+R[D%O]+(N=$[D])],$[G]=N;(M.g=function(j){for(var oe,ie=0,ue=M.i,Ae=M.j,Pe=M.S;j--;)oe=Pe[ue=l&ue+1],ie=ie*r+Pe[l&(Pe[ue]=Pe[Ae=l&Ae+oe])+(Pe[Ae]=oe)];return M.i=ue,M.j=Ae,ie})(r)}function y(R,N){return N.i=R.i,N.j=R.j,N.S=R.S.slice(),N}function w(R,N){var O=[],M=typeof R,D;if(N&&M=="object")for(D in R)try{O.push(w(R[D],N-1))}catch(G){}return O.length?O:M=="string"?R:R+"\0"}function L(R,N){for(var O=R+"",M,D=0;D<O.length;)N[l&D]=l&(M^=N[l&D]*19)+O.charCodeAt(D++);return A(N)}function v(){try{var R;return h&&(R=h.randomBytes)?R=R(r):(R=new Uint8Array(r),(n.crypto||n.msCrypto).getRandomValues(R)),A(R)}catch(M){var N=n.navigator,O=N&&N.plugins;return[+new Date(),n,O,n.screen,A(e)]}}function A(R){return String.fromCharCode.apply(0,R)}if(L(t.random(),e),typeof Ms=="object"&&Ms.exports){Ms.exports=m;try{h=Tu()}catch(R){}}else typeof define=="function"&&define.amd&&define(function(){return m})})([],Math)});var Ru=ke((HT,Nu)=>{var Gb=mu(),jb=gu(),Pb=wu(),qb=xu(),Hb=Su(),zb=Iu(),bn=Au();bn.alea=Gb;bn.xor128=jb;bn.xorwow=Pb;bn.xorshift7=qb;bn.xor4096=Hb;bn.tychei=zb;Nu.exports=bn});var Eu=ke((Yb,Cu)=>{me(Yb,{isNodejs:()=>Vb});function Vb(){return typeof global=="object"&&!0&&typeof Cu!="undefined"&&typeof process!="undefined"&&!!process.version}});var Ou=ke(()=>{});var qe=ke(Kb=>{me(Kb,{env:()=>Zb});const oc=ee(Eu());T(Kb,ee(Ou()));let _e;function Jb(){if(!_e)throw new Error("getEnv - environment is not defined, check isNodejs() and isBrowser()");return _e}function ic(e){_e=e}function sc(){if(rc())return ic(tc());if(oc.isNodejs())return ic(nc())}function Xb(e){if(_e||sc(),!_e)throw new Error("monkeyPatch - environment is not defined, check isNodejs() and isBrowser()");const{Canvas:t=_e.Canvas,Image:n=_e.Image}=e;_e.Canvas=t,_e.Image=n,_e.createCanvasElement=e.createCanvasElement||(()=>new t()),_e.createImageElement=e.createImageElement||(()=>new n()),_e.ImageData=e.ImageData||_e.ImageData,_e.Video=e.Video||_e.Video,_e.fetch=e.fetch||_e.fetch,_e.readFile=e.readFile||_e.readFile}const Zb={getEnv:Jb,setEnv:ic,initialize:sc,createBrowserEnv:tc,createFileSystem:Us,createNodejsEnv:nc,monkeyPatch:Xb,isBrowser:rc,isNodejs:oc.isNodejs};sc()});var ku=ke(()=>{});var ot=ke(Qb=>{me(Qb,{NetInput:()=>Bs,awaitMediaLoaded:()=>uc,bufferToImage:()=>hc,createCanvas:()=>hr,createCanvasFromMedia:()=>Qr,extractFaceTensors:()=>iw,extractFaces:()=>ow,fetchImage:()=>rw,fetchJson:()=>lc,fetchNetWeights:()=>nw,fetchOrThrow:()=>xn,getContext2dOrThrow:()=>Ze,getMediaDimensions:()=>yn,imageTensorToCanvas:()=>pc,imageToSquare:()=>cc,isMediaElement:()=>Ws,isMediaLoaded:()=>Zr,loadWeightMap:()=>tw,matchDimensions:()=>ew,resolveInput:()=>wn,toNetInput:()=>ac});T(Qb,ee(ku()))});var _u=ke(()=>{});var $s=ke(sw=>{me(sw,{TinyYolov2:()=>dc,TinyYolov2Options:()=>gc,TinyYolov2SizeType:()=>fc,createTinyYolov2:()=>aw,validateConfig:()=>mc});T(sw,ee(_u()));function aw(e,t=!0){const n=new dc(t);return n.extractWeights(e),n}});var Du=ke(()=>{});var Wu=ke(cw=>{me(cw,{ComposableTask:()=>vt,ComputeAllFaceDescriptorsTask:()=>Ln,ComputeFaceDescriptorsTaskBase:()=>Sc,ComputeSingleFaceDescriptorTask:()=>Sn,DetectAllFaceLandmarksTask:()=>xc,DetectAllFacesTask:()=>Gs,DetectFaceLandmarksTaskBase:()=>yc,DetectFacesTaskBase:()=>bc,DetectSingleFaceLandmarksTask:()=>Lc,DetectSingleFaceTask:()=>wc,FaceMatcher:()=>Uu,computeFaceDescriptor:()=>hw,detectAllFaces:()=>Iw,detectFaceLandmarks:()=>Fu,detectFaceLandmarksTiny:()=>lw,detectLandmarks:()=>Sw,detectSingleFace:()=>vw,loadAgeGenderModel:()=>yw,loadFaceDetectionModel:()=>xw,loadFaceExpressionModel:()=>ww,loadFaceLandmarkModel:()=>fw,loadFaceLandmarkTinyModel:()=>gw,loadFaceRecognitionModel:()=>bw,loadTinyFaceDetectorModel:()=>Mu,loadTinyYolov2Model:()=>mw,locateFaces:()=>Lw,nets:()=>le,predictAgeAndGender:()=>dw,recognizeFaceExpressions:()=>uw,tinyFaceDetector:()=>pw});T(cw,ee(Du()))});var Vu=ke(Tw=>{me(Tw,{AgeGenderNet:()=>ta,BoundingBox:()=>gr,Box:()=>he,Dimensions:()=>Qe,FACE_EXPRESSION_LABELS:()=>Xs,FaceDetection:()=>ye,FaceExpressionNet:()=>Zs,FaceExpressions:()=>pn,FaceLandmark68Net:()=>mr,FaceLandmark68TinyNet:()=>Js,FaceLandmarkNet:()=>Hu,FaceLandmarks:()=>ct,FaceLandmarks5:()=>Yu,FaceLandmarks68:()=>fr,FaceMatch:()=>io,FaceRecognitionNet:()=>dr,Gender:()=>Dt,LabeledBox:()=>oo,LabeledFaceDescriptors:()=>ln,NeuralNetwork:()=>He,ObjectDetection:()=>Tn,Point:()=>J,PredictedBox:()=>zu,Rect:()=>ea,TinyFaceDetector:()=>vn,TinyFaceDetectorOptions:()=>sn,createFaceRecognitionNet:()=>qu,createTinyFaceDetector:()=>Bu,draw:()=>Ps,euclideanDistance:()=>Qs,extendWithAge:()=>ro,extendWithFaceDescriptor:()=>no,extendWithFaceDetection:()=>cn,extendWithFaceExpressions:()=>to,extendWithFaceLandmarks:()=>In,extendWithGender:()=>eo,inverseSigmoid:()=>Gu,iou:()=>Vs,isWithAge:()=>Pu,isWithFaceDetection:()=>It,isWithFaceExpressions:()=>Ks,isWithFaceLandmarks:()=>an,isWithGender:()=>ju,minBbox:()=>Ys,nonMaxSuppression:()=>zs,normalize:()=>bt,padToSquare:()=>Hs,resizeResults:()=>vc,shuffleArray:()=>$u,sigmoid:()=>ur,tf:()=>js,utils:()=>qs});T(Tw,ee(ot()));T(Tw,ee(qe()));T(Tw,ee(Wu()));T(Tw,ee($s()))});const Ku="tfjsflags";class Ic{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=Aw(this.global.location.search);if(Ku in e){const t=e[Ku].split(",");t.forEach(n=>{const[r,o]=n.split(":");this.urlFlags[r]=Nw(r,o)})}}}function Aw(e){const t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(n,...r)=>(Rw(t,r[0],r[1]),r.join("="))),t}function Rw(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}function Nw(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 ce(){return Tc}let Tc=null;function Ju(e){Tc=e}let Ac;function Nc(){if(Ac==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");Ac=e}return Ac}function Cw(){const e=Nc();return e._tfGlobals==null&&(e._tfGlobals=new Map()),e._tfGlobals}function Rc(e,t){const n=Cw();if(n.has(e))return n.get(e);{const r=t();return n.set(e,r),n.get(e)}}const so="Abs",ao="Acos",co="Acosh",An="Add",po="AddN",Cc="All",Ec="Any",lo="ArgMax",ho="ArgMin",uo="Asin",mo="Asinh",fo="Atan",go="Atanh",bo="Atan2",wo="AvgPool",Oc="AvgPoolBackprop",yo="AvgPool3D",kc="AvgPool3DBackprop",xo="BatchMatMul",Lo="BatchToSpaceND",So="BroadcastTo",Nn="Cast",vo="Ceil",Io="ClipByValue",_c="Complex",To="Concat",Ao="Conv2D",Dc="Conv2DBackpropFilter",No="Conv2DBackpropInput",Ro="Conv3D",Fc="Conv3DBackpropFilterV2",Mc="Conv3DBackpropInputV2",Co="Cos",Eo="Cosh",Oo="Cumsum",Uc="CropAndResize",Wc="DepthToSpace",ko="DepthwiseConv2dNative",Bc="DepthwiseConv2dNativeBackpropFilter",$c="DepthwiseConv2dNativeBackpropInput",Gc="Diag",_o="Dilation2D",jc="Dilation2DBackpropInput",Pc="Dilation2DBackpropFilter",Do="Div",Fo="Elu",qc="EluGrad",Mo="Erf",Hc="Equal",Uo="Exp",Wo="Expm1",zc="FFT",Yc="Fill",Vc="FlipLeftRight",Bo="Floor",$o="FloorDiv",Go="FusedBatchNorm",jo="GatherV2",Kc="GatherNd",Jc="Greater",Po="GreaterEqual",qo="Identity",Xc="IFFT",Zc="Imag",Ho="IsFinite",zo="IsInf",Yo="IsNan",Qc="Less",ep="LessEqual",tp="LinSpace",Vo="Log",Ko="Log1p",np="LogicalAnd",rp="LogicalNot",op="LogicalOr",Jo="LogSoftmax",Xo="LRN",ip="LRNBackprop",Zo="Max",Qo="Maximum",ei="MaxPool",sp="MaxPoolBackprop",ti="MaxPool3D",ap="MaxPool3DBackprop",cp="MaxPoolWithArgmax",Ew="Mean",ni="Min",ri="Minimum",oi="Mod",ii="Multiply",si="Negate",pp="NotEqual",lp="NonMaxSuppressionV3",hp="NonMaxSuppressionV4",up="NonMaxSuppressionV5",ai="OnesLike",ci="OneHot",pi="PadV2",Ow="Pool",li="Pow",hi="Prelu",dp="Prod",mp="Range",fp="Real",ui="Reciprocal",di="Relu",mi="Reshape",fi="ResizeNearestNeighbor",gp="ResizeNearestNeighborGrad",gi="ResizeBilinear",bp="ResizeBilinearGrad",bi="Relu6",wi="Reverse",yi="Round",xi="Rsqrt",wp="ScatterNd",Li="SelectV2",Si="Selu",vi="Slice",Ii="Sin",Ti="Sinh",Ai="Sign",Ni="Sigmoid",Ri="Softplus",Ci="Sqrt",Ei="Sum",Oi="SpaceToBatchND",ki="SplitV",_i="Softmax",Di="SquaredDifference",yp="Square",Fi="Sub",xp="SparseToDense",Lp="StridedSlice",Mi="Tan",Ui="Tanh",Wi="Tile",Sp="TopK",Bi="Transpose",$i="Unpack",Gi="UnsortedSegmentSum",ji="ZerosLike",Pi="Step",na="FromPixels",vp="RotateWithOffset",ra="_FusedMatMul",oa="FusedConv2D",ia="FusedDepthwiseConv2D";const br=Rc("kernelRegistry",()=>new Map()),qi=Rc("gradRegistry",()=>new Map());function Hi(e,t){const n=Ip(e,t);return br.get(n)}function sa(e){return qi.get(e)}function aa(e){const t=br.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 kw(e){const{kernelName:t,backendName:n}=e,r=Ip(t,n);br.has(r)&&console.warn(`The kernel '${t}' for backend '${n}' is already registered`),br.set(r,e)}function Tp(e){const{kernelName:t}=e;qi.has(t)&&(ce().getBool("DEBUG")&&console.warn(`Overriding the gradient for '${t}'`)),qi.set(t,e)}function _w(e,t){const n=Ip(e,t);if(!br.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);br.delete(n)}function Dw(e){if(!qi.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);qi.delete(e)}function Ip(e,t){return`${t}_${e}`}const Xu={};me(Xu,{arraysEqual:()=>Se,assert:()=>f,assertNonNegativeIntegerDimensions:()=>Vi,assertNonNull:()=>pt,assertShapesMatch:()=>P,bytesFromStringArray:()=>kp,bytesPerElement:()=>Op,checkConversionForErrors:()=>Qu,clamp:()=>wr,computeStrides:()=>Ut,createShuffledIndices:()=>jw,decodeString:()=>pa,distSquared:()=>Ww,encodeString:()=>_p,fetch:()=>zw,flatten:()=>Ft,getArrayFromDType:()=>Rp,getTypedArrayFromDType:()=>yr,hasEncodingLoss:()=>Ep,indexToLoc:()=>Vw,inferDtype:()=>xr,inferFromImplicitShape:()=>Ap,isBoolean:()=>ed,isFunction:()=>Mt,isInt:()=>X,isNumber:()=>td,isScalarShape:()=>Bw,isString:()=>Tt,isTypedArray:()=>Ne,isValidDtype:()=>Cp,locToIndex:()=>Yw,makeOnesTypedArray:()=>Yi,makeZerosNestedTypedArray:()=>Hw,makeZerosTypedArray:()=>Wt,nearestDivisor:()=>Lr,nearestLargerEven:()=>Fw,now:()=>ca,parseAxisParam:()=>z,randUniform:()=>Uw,repeatedTry:()=>Pw,rightPad:()=>Rn,shuffle:()=>Zu,sizeFromShape:()=>te,sizeToSquarishShape:()=>Gw,squeezeShape:()=>Np,sum:()=>Mw,tanh:()=>$w,toNestedArray:()=>Cn,toTypedArray:()=>zi});function Zu(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 wr(e,t,n){return Math.max(e,Math.min(t,n))}function Fw(e){return e%2===0?e:e+1}function Mw(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t}function Uw(e,t){const n=Math.random();return t*n+(1-n)*e}function Ww(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 P(e,t,n=""){f(Se(e,t),()=>n+` Shapes ${e} and ${t} must match`)}function pt(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 te(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 Bw(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 $w(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 Gw(e){const t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function jw(e){const t=new Uint32Array(e);for(let n=0;n<e;++n)t[n]=n;return Zu(t),t}function Rn(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function Pw(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 Ap(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 z(e,t){const n=t.length;return e=e==null?t.map((r,o)=>o):[].concat(e),f(e.every(r=>r>=-n&&r<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 Np(e,t){const n=[],r=[],o=t!=null&&Array.isArray(t)&&t.length===0,i=t==null||o?null:z(t,e).sort();let a=0;for(let s=0;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 yr(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 Rp(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 Qu(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 Cp(e){return e==="bool"||e==="complex64"||e==="float32"||e==="int32"||e==="string"}function Ep(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 Op(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 kp(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 ed(e){return typeof e=="boolean"}function td(e){return typeof e=="number"}function xr(e){return Array.isArray(e)?xr(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array?"int32":td(e)?"float32":Tt(e)?"string":ed(e)?"bool":"float32"}function Mt(e){return!!(e&&e.constructor&&e.call&&e.apply)}function Lr(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 zi(e,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=Ft(e)),ce().getBool("DEBUG")&&Qu(e,t),qw(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 nd(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]=nd(e+s*a,i,n)}return r}function Cn(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 nd(0,e,t)}function qw(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function Yi(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 Hw(e,t){const n=e.reduce((r,o)=>r*o,1);if(t==null||t==="float32")return Cn(e,new Float32Array(n));if(t==="int32")return Cn(e,new Int32Array(n));if(t==="bool")return Cn(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function ca(){return ce().platform.now()}function Vi(e){e.forEach(t=>{f(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function zw(e,t){return ce().platform.fetch(e,t)}function _p(e,t="utf-8"){return t=t||"utf-8",ce().platform.encode(e,t)}function pa(e,t="utf-8"){return t=t||"utf-8",ce().platform.decode(e,t)}function Yw(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 Vw(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 rd{constructor(e,t){this.backendTimer=e,this.logger=t,t==null&&(this.logger=new Jw())}profileKernel(e,t,n){let r;const o=()=>{r=n()},i=this.backendTimer.time(o);r.map(s=>{s.data().then(c=>{Kw(c,s.dtype,e)})});const a={kernelName:e,outputs:r,inputs:t,timeMs:i.then(s=>s.kernelMs),extraInfo:i.then(s=>s.getExtraProfileInfo!=null?s.getExtraProfileInfo():"")};return a}logKernelProfile(e){const{kernelName:t,outputs:n,timeMs:r,inputs:o,extraInfo:i}=e;n.forEach(a=>{Promise.all([a.data(),r,i]).then(s=>{this.logger.logKernelProfile(t,a,s[0],s[1],o,s[2])})})}}function Kw(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 Jw{logKernelProfile(e,t,n,r,o,i){const a=typeof r=="number"?Rn(`${r}ms`,9):r.error,s=Rn(e,25),c=t.rank,p=t.size,l=Rn(t.shape.toString(),14);let h="";for(const m in o){const b=o[m];if(b!=null){const y=b.shape||t.shape,w=y.length;h+=`${m}: ${w}D ${w>0?y:""} `}}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 od(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 m=l[h];let b=!1;for(let y=0;y<t.length;y++)if(r[m.id]){p.outputs.forEach(w=>r[w.id]=!0),b=!0,o[p.id]=!0;break}if(b)break}}const i={};i[n.id]=!0;const a={};for(let c=e.length-1;c>=0;c--){const p=e[c],l=p.inputs;for(let h=0;h<p.outputs.length;h++)if(i[p.outputs[h].id]){for(const m in l)i[l[m].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 m in p.inputs){const b=p.inputs[m];r[b.id]&&(l[m]=b)}const h=Object.assign({},p);h.inputs=l,h.outputs=p.outputs,s.push(h)}}return s}function id(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 sd=20,Ki=3,Dp=7;function ad(e,t,n,r){const o=Ut(t),i=Xw(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 Xw(e,t,n,r){const o=te(t),i=r[r.length-1],a=new Array(i).fill(0),s=t.length,c=n==="complex64"?Xi(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],Ji(c[l+h],0,n).length)}return a}function Ji(e,t,n){let r;return Array.isArray(e)?r=`${parseFloat(e[0].toFixed(Dp))} + ${parseFloat(e[1].toFixed(Dp))}j`:Tt(e)?r=`'${e}'`:n==="bool"?r=cd(e):r=parseFloat(e.toFixed(Dp)).toString(),Rn(r,t)}function cd(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=Xi(e);return[Ji(w[0],0,n)]}return n==="bool"?[cd(e[0])]:[e[0].toString()]}if(c===1){if(s>sd){const L=Ki*a;let v=Array.from(e.slice(0,L)),A=Array.from(e.slice((s-Ki)*a,s*a));return n==="complex64"&&(v=Xi(v),A=Xi(A)),["["+v.map((R,N)=>Ji(R,o[N],n)).join(", ")+", ..., "+A.map((R,N)=>Ji(R,o[s-Ki+N],n)).join(", ")+"]"]}const w=n==="complex64"?Xi(e):Array.from(e);return["["+w.map((L,v)=>Ji(L,o[v],n)).join(", ")+"]"]}const p=t.slice(1),l=r.slice(1),h=r[0]*a,m=[];if(s>sd){for(let w=0;w<Ki;w++){const L=w*h,v=L+h;m.push(...la(e.slice(L,v),p,n,l,o,!1))}m.push("...");for(let w=s-Ki;w<s;w++){const L=w*h,v=L+h;m.push(...la(e.slice(L,v),p,n,l,o,w===s-1))}}else for(let w=0;w<s;w++){const L=w*h,v=L+h;m.push(...la(e.slice(L,v),p,n,l,o,w===s-1))}const b=c===2?",":"";m[0]="["+m[0]+b;for(let w=1;w<m.length-1;w++)m[w]=" "+m[w]+b;let y=`,
`;for(let w=2;w<c;w++)y+=`
`;return m[m.length-1]=" "+m[m.length-1]+"]"+(i?"":y),m}function Xi(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}class Sr{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=te(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||Rp(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,vr=null,Zw=null;function pd(e){Bt=e}function ld(e){vr=e}function hd(e){Zw=e}class ne{constructor(e,t,n,r){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=te(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 vr.buffer(this.shape,this.dtype,e)}bufferSync(){return vr.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return Cn(this.shape,e)}arraySync(){return Cn(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 vr.print(this,e)}clone(){return this.throwIfDisposed(),vr.clone(this)}toString(e=!1){const t=this.dataSync();return ad(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),vr.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Bt().makeVariable(this,e,t,n)}}Object.defineProperty(ne,Symbol.hasInstance,{value:e=>!!e&&e.dataId!=null&&e.shape!=null&&e.dtype!=null});class $t extends ne{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 ne&&e.assign!=null&&e.assign instanceof Function});var Fp;(function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"})(Fp||(Fp={}));var Mp;(function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"})(Mp||(Mp={}));var Up;(function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"})(Up||(Up={}));var Wp;(function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"})(Wp||(Wp={}));var Bp;(function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"})(Bp||(Bp={}));const Qw={float32:Wp,int32:Mp,bool:Up,complex64:Bp};function Ir(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return Qw[e][t]}function ey(e){return Ir(e,"int32")}const ud={};me(ud,{assertTypesMatch:()=>$p,getTensorsInContainer:()=>Zi,isTensorInList:()=>ty,makeTypesMatch:()=>K});function K(e,t){if(e.dtype===t.dtype)return[e,t];const n=Ir(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function $p(e,t){f(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function ty(e,t){return t.some(n=>n.id===e.id)}function Zi(e){const t=[],n=new Set();return dd(e,t,n),t}function dd(e,t,n){if(e==null)return;if(e instanceof ne){t.push(e);return}if(!ny(e))return;const r=e;for(const o in r){const i=r[o];n.has(i)||(n.add(i),dd(i,t,n))}}function ny(e){return Array.isArray(e)||typeof e=="object"}class md{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 Qi{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new md()}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 rd(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 Qi.nextTensorId++}nextVariableId(){return Qi.nextVariableId++}clone(e){const t=this.makeTensorFromDataId(e.dataId,e.shape,e.dtype),n={x:e},r=i=>({x:()=>{const a="float32",s={x:i},c={dtype:a};return g.runKernelFunc(p=>p.cast(i,a),s,null,Nn,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 m;const b=Hi(r,this.backendName);let y;if(b!=null)m=()=>{const L=this.backend.numDataIds();y=b.kernelFunc({inputs:t,attrs:o,backend:this.backend});const v=Array.isArray(y)?y:[y];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(r,L,v);const A=v.map(({dataId:R,shape:N,dtype:O})=>this.makeTensorFromDataId(R,N,O));if(p){let R=this.getTensorsForGradient(r,t,A);if(R==null){a==null&&(a=[]);const N=A.filter((O,M)=>a[M]);R=(i||[]).slice().concat(N)}c=this.saveTensorsForBackwardMode(R)}return A};else{const L=v=>{if(!p)return;c=v.map(A=>this.keep(this.clone(A)))};m=()=>{const v=this.backend.numDataIds();y=this.tidy(()=>e(this.backend,L));const A=Array.isArray(y)?y:[y];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(r,v,A),A}}let w;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?s=m():(w=this.profiler.profileKernel(r,t,()=>m()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(w),s=w.outputs)}),p&&this.addTapeNode(r,t,s,n,c,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(y)?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=>_p(s)));const i=r.write(o,t,n),a=new ne(t,n,i,this.nextTensorId());if(this.incRef(a,r),n==="string"){const s=this.state.tensorInfo.get(i),c=kp(o);this.state.numBytes+=c-s.bytes,s.bytes=c}return a}makeTensorFromDataId(e,t,n,r){n=n||"float32";const o=new ne(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*Op(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],m=Wt(h.size,h.dtype);return this.makeTensor(m,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=Zi(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 ne,()=>"The result y returned by f() must be a tensor.");const i=od(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??ry(o.shape),id(a,i,c=>this.tidy(c),oy);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 ne),()=>"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 ne,()=>"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 ne),()=>"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 md();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}}Qi.nextTensorId=0;Qi.nextVariableId=0;function ry(e){const t=Yi(te(e),"float32");return g.makeTensor(t,e,"float32")}function iy(){const e=Nc();if(e._tfengine==null){const t=new Ic(e);e._tfengine=new Qi(t)}return Ju(e._tfengine.ENV),pd(()=>e._tfengine),e._tfengine}const g=iy();function oy(e,t){const n={a:e,b:t};return g.runKernelFunc((r,o)=>{const i=r.add(e,t);return o([e,t]),i},n,null,An)}const fd={};me(fd,{isBrowser:()=>Gp,isMobile:()=>ay});function sy(){return typeof navigator!="undefined"&&navigator!=null}function ay(){if(sy()){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 Gp(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}const Yt=ce();Yt.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.")});Yt.registerFlag("IS_BROWSER",()=>Gp());Yt.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");Yt.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));Yt.registerFlag("PROD",()=>!1);Yt.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Yt.getBool("DEBUG"));Yt.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);Yt.registerFlag("IS_TEST",()=>!1);function Fe(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)&&ce().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&gd(e,r,[]),r}function gd(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)gd(e[o],r,n.concat(o))}function bd(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 ne)return bd(r,e.dtype,t,n),e;let o=xr(e);if(o!=="string"&&["bool","int32","float32"].indexOf(r)>=0&&(o=r),bd(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=Fe(e,o);!Ne(e)&&!Array.isArray(e)&&(e=[e]);const a=!0,s=o!=="string"?zi(e,o):Ft(e,[],a);return g.makeTensor(s,i,o)}function Vt(e,t,n,r="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);const o=e;return o.map((i,a)=>u(i,`${t}[${a}]`,n),r)}function d(e){const t=Object.keys(e);if(t.length!==1)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${t.length} keys.`);let n=t[0];const r=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1));const o=(...i)=>{g.startScope(n);try{const a=r(...i);return a instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),g.endScope(a),a}catch(a){throw g.endScope(null),a}};return Object.defineProperty(o,"name",{value:n,configurable:!0}),o}function cy(e){const t=u(e,"x","abs"),n={x:t};return g.runKernelFunc((r,o)=>(o([t]),t.dtype==="complex64"?r.complexAbs(t):r.abs(t)),n,null,so)}const Ce=d({abs_:cy});function py(e){const t=u(e,"x","acos"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.acos(t);return o([t]),i},n,null,ao)}const jp=d({acos_:py});function ly(e){const t=u(e,"x","acosh"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.acosh(t);return o([t]),i},n,null,co)}const Pp=d({acosh_:ly});function hy(e,t){let n=u(e,"a","add"),r=u(t,"b","add");[n,r]=K(n,r);const o=(a,s)=>{const c=a.add(n,r);return s([n,r]),c},i={a:n,b:r};return g.runKernelFunc(o,i,null,An)}const C=d({add_:hy});function uy(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 g.runKernelFunc(r,o,null,po)}const qp=d({addN_:uy});function Hp(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function wd(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 zp(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 wd(e,n,t)}function dy(e,t,n){f(Hp(t,n),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`)}function fe(e,t){if(Hp(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 En(e){return e.map((t,n)=>[n,t]).sort((t,n)=>t[1]-n[1]).map(t=>t[0])}function De(e,t){const n=[];for(let r=t-e;r<t;++r)n.push(r);return n}function my(e,t){const n=u(e,"x","reshape",null);t=Ap(t,n.size),f(n.size===te(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 g.runKernelFunc(i,r,null,mi,o)}const x=d({reshape_:my});function fy(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 g.runKernelFunc(i=>i.transpose(n,t),r,null,Bi,o)}const Z=d({transpose_:fy});function gy(e,t=null,n=!1){let r=u(e,"x","all","bool");const o=s=>{const c=z(t,r.shape);let p=c;const l=fe(p,r.rank);l!=null&&(r=Z(r,l),p=De(p.length,r.rank));const h=s.all(r,p);if(n){const m=we(h.shape,c);return x(h,m)}return h},i={x:r},a={axis:t,keepDims:n};return g.runKernelFunc(o,i,null,Cc,a)}const Yp=d({all_:gy});function by(e,t=null,n=!1){let r=u(e,"x","any","bool");const o=s=>{const c=z(t,r.shape);let p=c;const l=fe(p,r.rank);l!=null&&(r=Z(r,l),p=De(p.length,r.rank));const h=s.any(r,p);if(n){const m=we(h.shape,c);return x(h,m)}return h},i={x:r},a={axis:t,keepDims:n};return g.runKernelFunc(o,i,null,Ec,a)}const Vp=d({any_:by});function wy(e,t=0){let n=u(e,"x","argMax");const r=(a,s)=>{s([n]);let c=z(t,n.shape);const p=fe(c,n.rank);return p!=null&&(n=Z(n,p),c=De(c.length,n.rank)),a.argMax(n,c[0])},o={x:n},i={axis:t};return g.runKernelFunc(r,o,null,lo,i)}const Kp=d({argMax_:wy});function yy(e,t=0){let n=u(e,"x","argMin");const r=(a,s)=>{s([n]),t==null&&(t=0);let c=z(t,n.shape);const p=fe(c,n.rank);return p!=null&&(n=Z(n,p),c=De(c.length,n.rank)),a.argMin(n,c[0])},o={x:n},i={axis:t};return g.runKernelFunc(r,o,null,ho,i)}const Jp=d({argMin_:yy});function xy(e){const t=u(e,"x","asin"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.asin(t);return o([t]),i},n,null,uo)}const Xp=d({asin_:xy});function Ly(e){const t=u(e,"x","asinh"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.asinh(t);return o([t]),i},n,null,mo)}const Zp=d({asinh_:Ly});function Sy(e){const t=u(e,"x","atan"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.atan(t);return o([t]),i},n,null,fo)}const Qp=d({atan_:Sy});function vy(e,t){let n=u(e,"a","atan2"),r=u(t,"b","atan2");[n,r]=K(n,r);const o=(a,s)=>{const c=a.atan2(n,r);return s([n,r]),c},i={a:n,b:r};return g.runKernelFunc(o,i,null,bo)}const el=d({atan2_:vy});function Iy(e){const t=u(e,"x","atanh"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.atanh(t);return o([t]),i},n,null,go)}const tl=d({atanh_:Iy});function Ty(e,t){const n=u(e,"x","cast");if(!Cp(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if(t==="string"&&n.dtype!=="string"||t!=="string"&&n.dtype==="string")throw new Error("Only strings can be casted to strings");const r={x:n},o={dtype:t};return g.runKernelFunc(i=>i.cast(n,t),r,null,Nn,o)}const E=d({cast_:Ty});function Ay(e,t,n,r,o="NHWC",i){const a=e[3],s=[...t,a],c=hn(o);return $e(e,s,n,i,r,null,null,c)}function At(e,t,n,r,o,i,a="channelsLast"){const[s,c]=ha(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 $e(e,p,n,r,o,i,!1,a)}function Kt(e,t,n,r,o,i,a="NDHWC"){const[s,c,p]=nl(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 un(e,l,n,r,o,!1,h,i)}function $e(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[m,b,,y]=t,[w,L]=ha(n),[v,A]=ha(r),R=Tr(m,v),N=Tr(b,A),{padInfo:O,outHeight:M,outWidth:D}=Ny(o,p,l,w,L,R,N,i,s),G=a?y*h:y;let $;return s==="channelsFirst"?$=[c,G,M,D]:s==="channelsLast"&&($=[c,M,D,G]),{batchSize:c,dataFormat:s,inHeight:p,inWidth:l,inChannels:h,outHeight:M,outWidth:D,outChannels:G,padInfo:O,strideHeight:w,strideWidth:L,filterHeight:m,filterWidth:b,effectiveFilterHeight:R,effectiveFilterWidth:N,dilationHeight:v,dilationWidth:A,inShape:e,outShape:$,filterShape:t}}function un(e,t,n,r,o,i=!1,a="channelsLast",s){let[c,p,l,h,m]=[-1,-1,-1,-1,-1];if(a==="channelsLast")[c,p,l,h,m]=e;else if(a==="channelsFirst")[c,m,p,l,h]=e;else throw new Error(`Unknown dataFormat ${a}`);const[b,y,w,,L]=t,[v,A,R]=nl(n),[N,O,M]=nl(r),D=Tr(b,N),G=Tr(y,O),$=Tr(w,M),{padInfo:j,outDepth:oe,outHeight:ie,outWidth:ue}=Ry(o,p,l,h,v,A,R,D,G,$,s),Ae=i?L*m:L;let Pe;return a==="channelsFirst"?Pe=[c,Ae,oe,ie,ue]:a==="channelsLast"&&(Pe=[c,oe,ie,ue,Ae]),{batchSize:c,dataFormat:a,inDepth:p,inHeight:l,inWidth:h,inChannels:m,outDepth:oe,outHeight:ie,outWidth:ue,outChannels:Ae,padInfo:j,strideDepth:v,strideHeight:A,strideWidth:R,filterDepth:b,filterHeight:y,filterWidth:w,effectiveFilterDepth:D,effectiveFilterHeight:G,effectiveFilterWidth:$,dilationDepth:N,dilationHeight:O,dilationWidth:M,inShape:e,outShape:Pe,filterShape:t}}function Cy(e,t,n,r,o){r==null&&(r=rl(e,t,n));const i=e[0],a=e[1],s=On((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=On((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 Ey(e,t,n,r,o,i){o==null&&(o=rl(e,t,r));const a=e[0],s=e[1],c=e[2],p=On((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=On((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=On((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 rl(e,t,n,r=1){const o=Tr(t,r);return Math.floor((e[0]*(n-1)-n+o)/2)}function ha(e){return typeof e=="number"?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function nl(e){return typeof e=="number"?[e,e,e]:e}function Tr(e,t){return t<=1?e:e+(e-1)*(t-1)}function Ny(e,t,n,r,o,i,a,s,c){let p,l,h;if(typeof e=="number"){const m=e===0?"VALID":"NUMBER";p={top:e,bottom:e,left:e,right:e,type:m};const b=Cy([t,n],i,r,e,s);l=b[0],h=b[1]}else if(e==="same"){l=Math.ceil(t/r),h=Math.ceil(n/o);const m=Math.max(0,(l-1)*r+i-t),b=Math.max(0,(h-1)*o+a-n),y=Math.floor(m/2),w=m-y,L=Math.floor(b/2),v=b-L;p={top:y,bottom:w,left:L,right:v,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 m=c==="channelsLast"?e[1][0]:e[2][0],b=c==="channelsLast"?e[1][1]:e[2][1],y=c==="channelsLast"?e[2][0]:e[3][0],w=c==="channelsLast"?e[2][1]:e[3][1],L=m===0&&b===0&&y===0&&w===0?"VALID":"EXPLICIT";p={top:m,bottom:b,left:y,right:w,type:L},l=On((t-i+m+b)/r+1,s),h=On((n-a+y+w)/o+1,s)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:p,outHeight:l,outWidth:h}}function Ry(e,t,n,r,o,i,a,s,c,p,l){let h,m,b,y;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=Ey([t,n,r,1],s,1,o,e,l);m=L[0],b=L[1],y=L[2]}else if(e==="same"){m=Math.ceil(t/o),b=Math.ceil(n/i),y=Math.ceil(r/a);const w=(m-1)*o+s-t,L=(b-1)*i+c-n,v=(y-1)*a+p-r,A=Math.floor(w/2),R=w-A,N=Math.floor(L/2),O=L-N,M=Math.floor(v/2),D=v-M;h={top:N,bottom:O,left:M,right:D,front:A,back:R,type:"SAME"}}else if(e==="valid")h={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},m=Math.ceil((t-s+1)/o),b=Math.ceil((n-c+1)/i),y=Math.ceil((r-p+1)/a);else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:h,outDepth:m,outHeight:b,outWidth:y}}function On(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 lt(e){const[t,n,r]=ha(e);return t===1&&n===1&&r===1}function pe(e,t){return lt(e)||lt(t)}function hn(e){if(e==="NHWC")return"channelsLast";if(e==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function Oy(e,t,n,r,o){const i=u(e,"x","avgPool","float32"),a=1;f(pe(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=x(i,[1,i.shape[0],i.shape[1],i.shape[2]])),f(s.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${s.rank}.`),o!=null&&f(X(r),()=>`Error in avgPool: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);const p=(b,y)=>{const w=At(s.shape,t,n,1,r,o);return y([s]),w.filterWidth===1&&w.filterHeight===1&&Se(w.inShape,w.outShape)?s.clone():b.avgPool(s,w)},l={x:s},h={filterSize:t,strides:n,pad:r,dimRoundingMode:o};let m=g.runKernelFunc(p,l,null,wo,h);return m=E(m,i.dtype),c?x(m,[m.shape[1],m.shape[2],m.shape[3]]):m}const ht=d({avgPool_:Oy});function ky(){ce().set("PROD",!0)}function _y(){ce().set("DEBUG",!0)}function Dy(){ce().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function xe(e){ce().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}hd(xe);function Fy(){g.disposeVariables()}function My(){return g}function Uy(){return g.memory()}function Wy(e){return g.profile(e)}function F(e,t){return g.tidy(e,t)}function Le(e){const t=Zi(e);t.forEach(n=>n.dispose())}function ol(e){return g.keep(e)}function By(e){return g.time(e)}function $y(e){return g.setBackend(e)}function Gy(){return g.ready()}function jy(){return g.backendName}function Py(e){g.removeBackend(e)}function qy(e){return g.findBackend(e)}function Hy(e){return g.findBackendFactory(e)}function zy(e,t,n=1){return g.registerBackend(e,t,n)}function Yy(){return g.backend}function Vy(e,t){ce().setPlatform(e,t)}function Ky(e,t,n,r,o,i="NDHWC",a){a==null?a=[1,1,1]:xe("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=x(s,[1,s.shape[0],s.shape[1],s.shape[2],s.shape[3]])),f(c.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${c.rank}.`),f(i==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${i}`),f(pe(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=(y,w)=>{a==null&&(a=[1,1,1]);const L=Kt(c.shape,t,n,a,r,o,i);return w([c]),y.avgPool3d(c,L)},h={x:c},m={filterSize:t,strides:n,pad:r,dimRoundingMode:o,dataFormat:i,dilations:a};let b=g.runKernelFunc(l,h,null,yo,m);return b=E(b,c.dtype),p?x(b,[b.shape[1],b.shape[2],b.shape[3],b.shape[4]]):b}const il=d({avgPool3d_:Ky});function sl(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 al(e,t){const n=e[0].slice();for(let r=1;r<e.length;r++)n[t]+=e[r][t];return n}function ze(e,t,n,r){if(r==null&&(r=xr(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){Vi(t);const o=te(t),i=te(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!==te(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"?zi(e,r):Ft(e,[],!0),g.makeTensor(e,t,r)}function Ye(e,t,n){const r=Fe(e,n);return ze(e,t,r,n)}function Jy(e,t=0){f(e.length>=1,()=>"Pass at least one tensor to concat");let n=Vt(e,"tensors","concat");n[0].dtype==="complex64"&&n.forEach(p=>{if(p.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor
with dtype ${p.dtype}. `)});const r=z(t,n[0].shape)[0],o=al(n.map(p=>p.shape),r);if(te(o)===0)return Ye([],o);if(n=n.filter(p=>p.size>0),n.length===1)return n[0];const i=n.map(p=>p.shape);sl(i,r);const a=(p,l)=>{const h=p.concat(n,r);return l(n),h},s=n,c={axis:t};return g.runKernelFunc(a,s,null,To,c)}const Q=d({concat_:Jy});function Xy(e,t,n=!1,r=!1){let o=u(e,"a","matMul"),i=u(t,"b","matMul");[o,i]=K(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),m=te(l),b=te(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 y=o.shape.slice(0,-2).concat([c,p]),w=n?x(o,[m,a,c]):x(o,[m,c,a]),L=r?x(i,[b,p,s]):x(i,[b,s,p]),v=(O,M)=>(M([w,L]),O.batchMatMul(w,L,n,r)),A={a:w,b:L},R={transposeA:n,transposeB:r},N=g.runKernelFunc(v,A,null,xo,R);return x(N,y)}const Y=d({matMul_:Xy});function Zy(e,t){let n=u(e,"a","mul"),r=u(t,"b","mul");[n,r]=K(n,r);const o=(a,s)=>{const c=a.multiply(n,r);return s([n,r]),c},i={a:n,b:r};return g.runKernelFunc(o,i,null,ii)}const S=d({mul_:Zy});function Qy(e){const t=u(e,"x","sigmoid"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.sigmoid(t);return o([i]),i},n,null,Ni)}const Nt=d({sigmoid_:Qy});const yd={};me(yd,{assertParamsValid:()=>cl,computeFlatOffset:()=>tx,computeOutShape:()=>pl,isSliceContinous:()=>ex,maskToAxes:()=>es,parseSliceParams:()=>ts,startForAxis:()=>ml,startIndicesWithElidedDims:()=>hl,stopForAxis:()=>fl,stopIndicesWithElidedDims:()=>ul,stridesForAxis:()=>dl,stridesWithElidedDims:()=>ll});function cl(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 es(e){const t=[];let n=0;for(;e>0;)e&1&&t.push(n),e/=2,n++;return t}function pl(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 ll(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 xd(e,t,n){return n<=e?n:n-(t-1)}function Ld(e,t){const n=[];for(let r=0;r<e;r++)n.push(t+r);return n}function hl(e,t,n,r,o){const i=[...o],a=Ld(n,t);for(let s=0;s<i.length;s++)if(a.indexOf(s)>-1)i[s]=0;else{const c=xd(t,n,s);let p=r[c];e&1<<c&&(p=0),i[s]=p}return i}function ul(e,t,n,r,o){const i=[...o],a=Ld(n,t);for(let s=0;s<i.length;s++)if(a.indexOf(s)>-1)i[s]=Number.MAX_SAFE_INTEGER;else{const c=xd(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]=wr(0,i[s],o[s])}return i}function dl(e,t,n){let r=e[t];return(n&1<<t||r==null)&&(r=1),r}function ml(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=wr(0,a,c-1),a}function fl(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=wr(0,a,c):a=wr(-1,a,c-1),a}function ex(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 tx(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 ts(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]}function nx(e,t,n){const r=u(e,"x","slice");if(r.rank===0)throw new Error("Slicing scalar is not possible");const[o,i]=ts(r,t,n);cl(r,o,i);const a=(p,l)=>(l([r]),p.slice(r,o,i)),s={x:r},c={begin:t,size:n};return g.runKernelFunc(a,s,null,vi,c)}const V=d({slice_:nx});function rx(e){const t=u(e,"x","tanh"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.tanh(t);return o([i]),i},n,null,Ui)}const Ar=d({tanh_:rx});function ox(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"),m=Q([p,h],1),b=Y(m,s),y=C(b,c),w=y.shape[0],L=y.shape[1]/4,v=[w,L],A=V(y,[0,0],v),R=V(y,[0,L],v),N=V(y,[0,L*2],v),O=V(y,[0,L*3],v),M=C(S(Nt(A),Ar(R)),S(l,Nt(C(a,N)))),D=S(Ar(M),Nt(O));return[M,D]}const gl=d({basicLSTMCell_:ox});function ix(e,t,n){const r=u(e,"x","batchToSpaceND"),o=t.reduce((c,p)=>c*p);f(r.rank>=1+t.length,()=>`input rank is ${r.rank} but should be > than blockShape.length ${t.length}`),f(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),f(r.shape[0]%o===0,()=>`input tensor batch is ${r.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${o}`);const i=c=>c.batchToSpaceND(r,t,n),a={x:r},s={blockShape:t,crops:n};return g.runKernelFunc(i,a,null,Lo,s)}const kn=d({batchToSpaceND_:ix});function Sd(e){let t;return e.rank===0||e.rank===1?t=x(e,[1,1,1,e.size]):e.rank===2?t=x(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=x(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function sx(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=Sd(a),m=(L,v)=>(v([h,s,c,p]),L.batchNorm(h,ua(s),ua(c),ua(l),ua(p),i)),b={x:h,scale:p,offset:l,mean:s,variance:c},y={varianceEpsilon:i},w=g.runKernelFunc(m,b,null,Go,y);return x(w,a.shape)}function ua(e){return e==null?null:e.rank===0?x(e,[e.size]):e.rank===1?e:e.rank===2?x(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?x(e,[1,e.shape[0],e.shape[1],e.shape[2]]):e}const Jt=d({batchNorm_:sx});function ax(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 bl=d({batchNorm2d_:ax});function cx(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 wl=d({batchNorm3d_:cx});function px(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 yl=d({batchNorm4d_:px});function lx(e){const t=u(e,"x","clone",null),n=()=>g.makeTensorFromDataId(t.dataId,t.shape,t.dtype),r={x:t};return g.runKernelFunc(n,r,null,qo)}const Rt=d({clone_:lx});function hx(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=x(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 Rt(n);const s=l=>l.tile(n,i),c={x:n},p={shape:t,inputShape:o};return g.runKernelFunc(s,c,null,So,p)}const Nr=d({broadcastTo_:hx});function Me(e,t="float32",n){return t=t||"float32",Vi(e),new Sr(e,t,n)}function ux(e){const t=u(e,"x","ceil"),n={x:t};return g.runKernelFunc(r=>r.ceil(t),n,null,vo)}const xl=d({ceil_:ux});function dx(e,t,n){const r=u(e,"x","clipByValue");f(t<=n,()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`);const o={x:r},i={clipValueMin:t,clipValueMax:n};return g.runKernelFunc((a,s)=>{const c=a.clip(r,t,n);return s([r]),c},o,null,Io,i)}const Ll=d({clipByValue_:dx});function mx(e,t){const n=u(e,"real","complex"),r=u(t,"imag","complex");P(n.shape,r.shape,`real and imag shapes, ${n.shape} and ${r.shape}, must match in call to tf.complex().`);const o=a=>a.complex(n,r),i={real:n,imag:r};return g.runKernelFunc(o,i,null,_c)}const Ve=d({complex_:mx});function fx(e){return Q(e,0)}const Sl=d({concat1d_:fx});function gx(e,t){return Q(e,t)}const vl=d({concat2d_:gx});function bx(e,t){return Q(e,t)}const Il=d({concat3d_:bx});function wx(e,t){return Q(e,t)}const Tl=d({concat4d_:wx});function yx(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=x(s,[1,s.shape[0],s.shape[1],s.shape[2]])),f(p.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${p.rank}.`),f(c.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${c.rank}.`),a!=null&&f(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(pe(n,i),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'`);const m=(L,v)=>{const A=hn(o),R=$e(p.shape,c.shape,n,i,r,a,!1,A),N=L.conv2d(p,c,R);return v([p,c]),N},b={x:p,filter:c},y={strides:n,pad:r,dataFormat:o,dilations:i,dimRoundingMode:a},w=g.runKernelFunc(m,b,null,Ao,y);return l?x(w,[w.shape[1],w.shape[2],w.shape[3]]):w}const ve=d({conv2d_:yx});function xx(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=x(s,[1,s.shape[0],s.shape[1]])),f(p.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${p.rank}.`),f(c.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${c.rank}.`),a!=null&&f(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(pe(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=x(c,[1,c.shape[0],c.shape[1],c.shape[2]]),m=x(p,[p.shape[0],1,p.shape[1],p.shape[2]]),b=[1,n],y=[1,i],w="NHWC",L=ve(m,h,b,r,w,y,a);return l?x(L,[L.shape[2],L.shape[3]]):x(L,[L.shape[0],L.shape[2],L.shape[3]])}const Al=d({conv1d_:xx});function Lx(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=x(t,[1,t.shape[0],t.shape[1],t.shape[2]]),s=[1,e[0],e[1],e[2]]),f(s.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${s.length}.`),f(c.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${c.rank}`),f(n.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`);const l=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 m=(L,v)=>{const A=1,R=hn(i),N=$e(s,n.shape,r,A,o,a,!1,R),O=L.conv2dDerInput(c,n,N);return v([c,n]),O},b={dy:c,filter:n},y={strides:r,pad:o,dataFormat:i,dimRoundingMode:a,inputShape:s},w=g.runKernelFunc(m,b,null,No,y);return p?x(w,[w.shape[1],w.shape[2],w.shape[3]]):w}const Rr=d({conv2DBackpropInput_:Lx});function Sx(e,t,n,r,o,i){const a=u(e,"x","conv2dTranspose"),s=u(t,"filter","conv2dTranspose");return Rr(n,a,s,r,o,"NHWC",i)}const Nl=d({conv2dTranspose_:Sx});function vx(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=x(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),f(c.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${c.rank}.`),f(s.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${s.rank}.`),f(c.shape[4]===s.shape[3],()=>`Error in conv3d: depth of input (${c.shape[4]}) must match input depth for filter ${s.shape[3]}.`),f(pe(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=(y,w)=>{const L=un(c.shape,s.shape,n,i,r),v=y.conv3d(c,s,L);return w([c,s]),v},h={x:c,filter:s},m={strides:n,pad:r,dataFormat:o,dilations:i},b=g.runKernelFunc(l,h,null,Ro,m);return p?x(b,[b.shape[1],b.shape[2],b.shape[3],b.shape[4]]):b}const Rl=d({conv3d_:vx});function Ix(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=x(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=y=>{const w=1,L=un(i,n.shape,r,w,o);return y.conv3dDerInput(a,n,L)},h={dy:a},m={pad:o},b=g.runKernelFunc(l,h,null,Mc,m);return s?x(b,[b.shape[1],b.shape[2],b.shape[3],b.shape[4]]):b}const da=d({conv3DBackpropInput_:Ix});function Tx(e,t,n,r,o){const i=u(e,"x","conv3dTranspose"),a=u(t,"filter","conv3dTranspose");return da(n,i,a,r,o)}const Cl=d({conv3dTranspose_:Tx});function Ax(e){const t=u(e,"x","cos"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.cos(t);return o([t]),i},n,null,Co)}const _n=d({cos_:Ax});function Nx(e){const t=u(e,"x","cosh"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.cosh(t);return o([t]),i},n,null,Eo)}const ns=d({cosh_:Nx});function Rx(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=Z(o,l));const m=De(1,o.rank)[0];let b=c.cumsum(h,m,n,r);if(p([o]),l!=null){const y=En(l);b=Z(b,y)}return b},a={x:o},s={axis:t,exclusive:n,reverse:r};return g.runKernelFunc(i,a,null,Oo,s)}const rs=d({cumsum_:Rx});function Cx(e,t,n="NHWC"){const r=u(e,"x","depthToSpace"),o=n==="NHWC"?r.shape[1]:r.shape[2],i=n==="NHWC"?r.shape[2]:r.shape[3],a=n==="NHWC"?r.shape[3]:r.shape[1];f(o*t>=0,()=>`Negative dimension size caused by overflow when multiplying
${o} and ${t} for depthToSpace with input shape
${r.shape}`),f(i*t>=0,()=>`Negative dimension size caused by overflow when multiplying
${i} and ${t} for depthToSpace with input shape
${r.shape}`),f(a%(t*t)===0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${a} for depthToSpace with input shape ${r.shape}`);const s=l=>l.depthToSpace(r,t,n),c={x:r},p={blockSize:t,dataFormat:n};return g.runKernelFunc(s,c,null,Wc,p)}const El=d({depthToSpace_:Cx});function Ex(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=x(s,[1,s.shape[0],s.shape[1],s.shape[2]])),f(p.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${p.rank}.`),f(c.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${c.rank}.`),f(p.shape[3]===c.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${p.shape[3]}) must match the inChannels dimension in filter ${c.shape[2]}.`),a!=null&&f(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(pe(n,i),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'`);const v=$e(p.shape,c.shape,n,i,r,a,!0),A=w.depthwiseConv2D(p,c,v);return L([p,c]),A},m={x:p,filter:c},b={strides:n,pad:r,dataFormat:o,dilations:i,dimRoundingMode:a},y=g.runKernelFunc(h,m,null,ko,b);return l?x(y,[y.shape[1],y.shape[2],y.shape[3]]):y}const Dn=d({depthwiseConv2d_:Ex});function Ox(e){const t=u(e,"x","diag"),n=o=>{const i=x(t,[t.size]),a=o.diag(i),s=[...e.shape,...e.shape];return x(a,s)},r={x:t};return g.runKernelFunc(n,r,null,Gc)}const Ol=d({diag_:Ox});function kx(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=x(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},m=g.runKernel(_o,l,h);return p?x(m,[m.shape[1],m.shape[2],m.shape[3]]):m}const kl=d({dilation2d_:kx});function _x(e,t){let n=u(e,"a","floorDiv"),r=u(t,"b","floorDiv");[n,r]=K(n,r);const o=(a,s)=>{const c=a.floorDiv(n,r);return s([n,r]),c},i={a:n,b:r};return g.runKernelFunc(o,i,null,$o)}const os=d({floorDiv_:_x});function Dx(e,t){let n=u(e,"a","div"),r=u(t,"b","div");if([n,r]=K(n,r),n.dtype==="int32"&&r.dtype==="int32")return os(n,r);const o=(s,c)=>{const p=s.realDivide(n,r);return c([n,r]),p},i={a:n,b:r},a={};return g.runKernelFunc(o,i,null,Do,a)}const U=d({div_:Dx});function Fx(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 Mx(e,t){let n=u(e,"a","equal"),r=u(t,"b","equal");[n,r]=K(n,r),q(n.shape,r.shape);const o=a=>a.equal(n,r),i={a:n,b:r};return g.runKernelFunc(o,i,null,Hc)}const Xt=d({equal_:Mx});function Ux(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=Nr(r,a),c=Nr(o,a);i.rank===1&&f(i.shape[0]===r.shape[0],()=>"The first dimension of `a` must match the size of `condition`."),i.rank!==1&&P(i.shape,c.shape,"Error in where: ");const p=(h,m)=>{const b=h.select(i,s,c);return m([i]),b},l={condition:i,t:s,e:c};return g.runKernelFunc(p,l,null,Li)}const Ee=d({where_:Ux});function Wx(e){const t=u(e,"x","zerosLike"),n={x:t};return g.runKernelFunc(r=>r.zerosLike(t),n,null,ji)}const B=d({zerosLike_:Wx});function Bx(e,t){let n=u(e,"a","div"),r=u(t,"b","div");[n,r]=K(n,r);const o=U(n,r),i=B(o),a=Xt(r,i);return Ee(a,i,o)}const _l=d({divNoNan_:Bx});function $x(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=x(n,[1,-1]),s=x(r,[-1,1]),c=Y(a,s);return x(c,[])}else if(n.rank===1&&r.rank===2){const a=x(n,[1,-1]),s=x(r,[r.shape[0],r.shape[1]]),c=Y(a,s);return x(c,[c.size])}else if(n.rank===2&&r.rank===1){const a=x(r,[-1,1]),s=Y(n,a);return x(s,[s.size])}else{const a=x(r,[r.shape[0],r.shape[1]]),s=Y(n,a);return s}}const Dl=d({dot_:$x});function Gx(e){const t=u(e,"x","elu"),n=(o,i)=>{const a=o.elu(t);return i([a]),a},r={x:t};return g.runKernelFunc(n,r,null,Fo)}const is=d({elu_:Gx});function jx(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=E(t,"float32"));const n={x:t};return g.runKernelFunc((r,o)=>{const i=r.erf(t);return o([t]),i},n,null,Mo)}const Fl=d({erf_:jx});function Px(e){const t=u(e,"x","exp"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.exp(t);return o([i]),i},n,null,Uo)}const Oe=d({exp_:Px});function qx(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),x(r,o)}const et=d({expandDims_:qx});function Hx(e){const t=u(e,"x","expm1"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.expm1(t);return o([t]),i},n,null,Wo)}const Ml=d({expm1_:Hx});function zx(e,t){const n=null,r=u(e,"x","tile",n);f(r.rank===t.length,()=>`Error in transpose: rank of input ${r.rank} must match length of reps ${t}.`);const o=(c,p)=>{const l=c.tile(r,t);return p([r]),l},i=[r],a={x:r},s={reps:t};return g.runKernelFunc(o,a,null,Wi,s,i)}const Zt=d({tile_:zx});function Yx(e,t,n,r="float32"){t==null&&(t=e);const o=Me([e,t],r),i=e<=t?e:t;for(let s=0;s<i;++s)o.set(1,s,s);const a=x(o.toTensor(),[e,t]);if(n==null)return a;if(n.length===1)return Zt(et(a,0),[n[0],1,1]);if(n.length===2)return Zt(et(et(a,0),0),[n[0],n[1],1,1]);if(n.length===3)return Zt(et(et(et(a,0),0),0),[n[0],n[1],n[2],1,1]);throw new Error(`eye() currently supports only 1D and 2D batchShapes, but received ${n.length}D.`)}const ss=d({eye_:Yx});function Vx(e){f(e.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);const t={input:e};return g.runKernelFunc(n=>{const r=e.shape[e.shape.length-1],o=e.size/r,i=e.as2D(o,r),a=n.fft(i);return a.reshape(e.shape)},t,null,zc)}const Fn=d({fft_:Vx});function Ge(e,t,n){const r={shape:e,value:t,dtype:n};return g.runKernelFunc(o=>o.fill(e,t,n),{},null,Yc,r)}function Kx(e){const t=u(e,"x","floor"),n={x:t};return g.runKernelFunc(r=>r.floor(t),n,null,Bo)}const Mn=d({floor_:Kx});const ma=30;function Jx(e){return e<=ma?e:Lr(e,Math.floor(Math.sqrt(e)))}const vd={};me(vd,{collectGatherOpShapeInfo:()=>Ul,computeOutShape:()=>Zx,segOpComputeOptimalWindowSize:()=>Xx});function Xx(e,t){let n=!1,r;for(e<=ma?(r=e,n=!0):r=Lr(e,Math.floor(Math.sqrt(e)));!n;)r>t||r===e?n=!0:r=Lr(e,r+1);return r}function Zx(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 Ul(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 Qx(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=z(n,r.shape)[0],h=Ul(r,o,l),m=c.gather(r,x(o,[o.size]),l);return p([r,o]),x(m,h.outputShape)};return g.runKernelFunc(s,i,null,jo,a)}const Un=d({gather_:Qx});function eL(e,t){let n=u(e,"a","greater"),r=u(t,"b","greater");[n,r]=K(n,r),q(n.shape,r.shape);const o=a=>a.greater(n,r),i={a:n,b:r};return g.runKernelFunc(o,i,null,Jc)}const tt=d({greater_:eL});function tL(e,t){let n=u(e,"a","greaterEqual"),r=u(t,"b","greaterEqual");[n,r]=K(n,r),q(n.shape,r.shape);const o=(a,s)=>{const c=a.greaterEqual(n,r);return s([n,r]),c},i={a:n,b:r};return g.runKernelFunc(o,i,null,Po)}const ut=d({greaterEqual_:tL});function nL(e){f(e.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);const t={input:e};return g.runKernelFunc(n=>{const r=e.shape[e.shape.length-1],o=e.size/r,i=x(e,[o,r]),a=n.ifft(i);return x(a,e.shape)},t,null,Xc)}const dn=d({ifft_:nL});function rL(e){const t=u(e,"input","imag"),n=o=>o.imag(t),r={input:t};return g.runKernelFunc(n,r,null,Zc)}const Qt=d({imag_:rL});function oL(e){const t=u(e,"input","real"),n=o=>o.real(t),r={input:t};return g.runKernelFunc(n,r,null,fp)}const Gt=d({real_:oL});function iL(e,t){const n=u(e,"x","reverse"),r=a=>{const s=z(t,n.shape);if(n.rank===0)return Rt(n);const c=a.reverse(n,s);return x(c,n.shape)},o={x:n},i={dims:t};return g.runKernelFunc(r,o,null,wi,i)}const Ke=d({reverse_:iL});function k(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 ze(e,n,r,t)}function sL(e){const t=e.shape[e.shape.length-1],n=e.size/t;let r;if(t<=2){const o=x(e,[n,t]);r=dn(o)}else{const o=[n,2*(t-1)],i=x(Gt(e),[n,t]),a=x(Qt(e),[n,t]),s=Ke(V(i,[0,1],[n,t-2]),1),c=S(Ke(V(a,[0,1],[n,t-2]),1),k(-1)),p=Q([i,s],1),l=Q([a,c],1),h=x(Ve(p,l),[o[0],o[1]]);r=dn(h)}if(r=Gt(r),e.rank===3&&e.shape[0]!==0){const o=r,i=e.shape[0];r=x(r,[i,r.shape[0]/i,r.shape[1]]),o.dispose()}return r}const as=d({irfft_:sL});function aL(e){const t=u(e,"x","isFinite"),n={x:t};return g.runKernelFunc(r=>r.isFinite(t),n,null,Ho)}const Wl=d({isFinite_:aL});function cL(e){const t=u(e,"x","isInf"),n={x:t};return g.runKernelFunc(r=>r.isInf(t),n,null,zo)}const Bl=d({isInf_:cL});function pL(e){const t=u(e,"x","isNaN"),n={x:t};return g.runKernelFunc(r=>r.isNaN(t),n,null,Yo)}const $l=d({isNaN_:pL});function lL(e,t){let n=u(e,"a","maximum"),r=u(t,"b","maximum");[n,r]=K(n,r),n.dtype==="bool"&&(n=E(n,"int32"),r=E(r,"int32")),q(n.shape,r.shape);const o=(a,s)=>{const c=a.maximum(n,r);return s([n,r]),c},i={a:n,b:r};return g.runKernelFunc(o,i,null,Qo)}const Ct=d({maximum_:lL});function hL(e,t=.2){const n=u(e,"x","leakyRelu");return Ct(S(k(t),n),n)}const Gl=d({leakyRelu_:hL});function uL(e,t){let n=u(e,"a","less"),r=u(t,"b","less");[n,r]=K(n,r),q(n.shape,r.shape);const o=a=>a.less(n,r),i={a:n,b:r};return g.runKernelFunc(o,i,null,Qc)}const Wn=d({less_:uL});function dL(e,t){let n=u(e,"a","lessEqual"),r=u(t,"b","lessEqual");[n,r]=K(n,r),q(n.shape,r.shape);const o=(a,s)=>{const c=a.lessEqual(n,r);return s([n,r]),c},i={a:n,b:r};return g.runKernelFunc(o,i,null,ep)}const dt=d({lessEqual_:dL});function jl(e,t,n){if(n<=0)throw new Error("The number of values should be positive.");const r={start:e,stop:t,num:n};return g.runKernelFunc(o=>o.linspace(e,t,n),{},null,tp,r)}function mL(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=x(i,[1,i.shape[0],i.shape[1],i.shape[2]]));const c=(m,b)=>{const y=m.localResponseNormalization4D(a,t,n,r,o);return b([a,y]),y},p={x:a},l={depthRadius:t,bias:n,alpha:r,beta:o},h=g.runKernelFunc(c,p,null,Xo,l);return s?x(h,[h.shape[1],h.shape[2],h.shape[3]]):h}const Pl=d({localResponseNormalization_:mL});function fL(e){const t=u(e,"x","log"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.log(t);return o([t]),i},n,null,Vo)}const wt=d({log_:fL});function gL(e){const t=u(e,"x","log1p"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.log1p(t);return o([t]),i},n,null,Ko)}const cs=d({log1p_:gL});function bL(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 g.tidy(()=>{const{value:i,grads:a}=g.gradients(()=>e(r),[r],o);return o!=null&&P(i.shape,o.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),fa(a),a[0]})}}function wL(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=Vt(t,"args","tf.grads",null),o=n!=null?u(n,"dy","tf.grads"):null;return g.tidy(()=>{const{value:i,grads:a}=g.gradients(()=>e(...r),r,o);return o!=null&&P(i.shape,o.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),fa(a),a})}}function yL(e){return f(Mt(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{f(t instanceof ne,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),f(n==null||n instanceof ne,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");const{grads:r,value:o}=g.gradients(()=>e(t),[t],n);return fa(r),{grad:r[0],value:o}}}function xL(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 ne),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),f(n==null||n instanceof ne,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");const r=g.gradients(()=>e(...t),t,n);return n!=null&&P(r.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),fa(r.grads),r}}function ql(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 g.registeredVariables)t.push(g.registeredVariables[p])}const r=n?t.filter(p=>!p.trainable):null,o=t.length;t=t.filter(p=>p.trainable),f(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${o} variables is trainable.`);const i=!0,{value:a,grads:s}=g.gradients(e,t,null,i);f(s.some(p=>p!=null),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),f(a.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${a.rank} tensor`);const c={};return t.forEach((p,l)=>{s[l]!=null&&(c[p.name]=s[l])}),r!=null&&r.forEach(p=>c[p.name]=null),{value:a,grads:c}}function Je(e){return g.customGrad(e)}function fa(e){const t=e.filter(n=>n==null).length;if(t>0)throw new Error(`Cannot compute gradient of y=f(x) with respect to x. Make sure that
the f you passed encloses all operations that lead from x to y.`)}function LL(e){const t=u(e,"x","neg"),n={x:t};return g.runKernelFunc(r=>r.neg(t),n,null,si)}const re=d({neg_:LL});function SL(e){const t=u(e,"x","softplus"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.softplus(t);return o([t]),i},n,null,Ri)}const ps=d({softplus_:SL});function vL(e){const t=u(e,"x","logSigmoid"),n=Je(r=>{const o=re(ps(re(r))),i=a=>{const s=S(a,Nt(re(r)));return s};return{value:o,gradFunc:i}});return n(t)}const Hl=d({logSigmoid_:vL});function IL(e,t=null,n=!1){const r=u(e,"x","max"),o=(s,c)=>{const p=z(t,r.shape);let l=p;const h=fe(l,r.rank);let m=r;h!=null&&(m=Z(r,h),l=De(l.length,m.rank));const b=s.max(m,l);h!=null&&m.dispose();let y=b;if(n){const w=we(y.shape,z(t,r.shape));y=x(y,w),b.dispose()}return c([r,y]),y},i={x:r},a={reductionIndices:t,keepDims:n};return g.runKernelFunc(o,i,null,Zo,a)}const mt=d({max_:IL});function TL(e,t){let n=u(e,"a","sub"),r=u(t,"b","sub");[n,r]=K(n,r);const o=(a,s)=>{const c=a.subtract(n,r);return s([n,r]),c},i={a:n,b:r};return g.runKernelFunc(o,i,null,Fi)}const _=d({sub_:TL});function AL(e,t=null,n=!1){let r=u(e,"x","sum");r.dtype==="bool"&&(r=E(r,"int32"));const o=(s,c)=>{c([r]);const p=z(t,r.shape),l=fe(p,r.rank);let h=p,m=r;l!=null&&(m=Z(r,l),h=De(h.length,r.rank));let b=s.sum(m,h);if(n){const y=we(b.shape,p);b=x(b,y)}return b},i={x:r},a={axis:t,keepDims:n};return g.runKernelFunc(o,i,null,Ei,a)}const W=d({sum_:AL});function NL(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=mt(e,t,!0),l=_(e,p),h=_(E(l,"float32"),wt(W(Oe(l),t,c)));return s([h]),h},o={logits:n},i={axis:t};return g.runKernelFunc(r,o,null,Jo,i)}const zl=d({logSoftmax_:NL});function RL(e,t=null,n=!1){const r=u(e,"x","logSumExp"),o=z(t,r.shape),i=mt(r,o,!0),a=_(r,i),s=Oe(a),c=W(s,o),p=wt(c),l=C(x(i,p.shape),p);if(n){const h=we(l.shape,o);return x(l,h)}return l}const ls=d({logSumExp_:RL});function CL(e,t){const n=u(e,"a","logicalAnd","bool"),r=u(t,"b","logicalAnd","bool");q(n.shape,r.shape);const o={a:n,b:r};return g.runKernelFunc(i=>i.logicalAnd(n,r),o,null,np)}const yt=d({logicalAnd_:CL});function EL(e){const t=u(e,"x","logicalNot","bool"),n={x:t};return g.runKernelFunc(r=>r.logicalNot(t),n,null,rp)}const Bn=d({logicalNot_:EL});function OL(e,t){const n=u(e,"a","logicalOr","bool"),r=u(t,"b","logicalOr","bool");q(n.shape,r.shape);const o={a:n,b:r};return g.runKernelFunc(i=>i.logicalOr(n,r),o,null,op)}const hs=d({logicalOr_:OL});function kL(e,t){const n=u(e,"a","logicalXor","bool"),r=u(t,"b","logicalXor","bool");return q(n.shape,r.shape),yt(hs(e,t),Bn(yt(e,t)))}const Yl=d({logicalXor_:kL});function _L(e,t,n,r,o){const i=u(e,"x","maxPool"),a=1;let s=i,c=!1;i.rank===3&&(c=!0,s=x(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(pe(n,a),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),o!=null&&f(X(r),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);const p=(b,y)=>{const w=At(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=b.maxPool(s,w),y([s,L]),L},l={x:s},h={filterSize:t,strides:n,pad:r,dimRoundingMode:o},m=g.runKernelFunc(p,l,null,ei,h);return c?x(m,[m.shape[1],m.shape[2],m.shape[3]]):m}const Ie=d({maxPool_:_L});function DL(e,t=[1,1,1],n,r,o,i="NDHWC",a){a==null?a=[1,1,1]:xe("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=x(s,[1,s.shape[0],s.shape[1],s.shape[2],s.shape[3]])),f(c.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${c.rank}.`),f(i==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${i}`),f(pe(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=(y,w)=>{a==null&&(a=[1,1,1]);const L=Kt(c.shape,t,n,a,r,o,i),v=y.maxPool3d(c,L);return w([c,v]),v},h={x:c},m={filterSize:t,strides:n,pad:r,dimRoundingMode:o,dataFormat:i,dilations:a},b=g.runKernelFunc(l,h,null,ti,m);return p?x(b,[b.shape[1],b.shape[2],b.shape[3],b.shape[4]]):b}const Vl=d({maxPool3d_:DL});function FL(e,t,n,r,o=!1){const i=u(e,"x","maxPoolWithArgmax"),a={x:i},s={filterSize:t,strides:n,pad:r,includeBatchInIndex:o},c=g.runKernel(cp,a,s);return{result:c[0],indexes:c[1]}}const Kl=d({maxPoolWithArgmax_:FL});function Re(e,t="float32"){if(t==="complex64"){const r=Re(e,"float32"),o=Re(e,"float32");return Ve(r,o)}const n=Wt(te(e),t);return g.makeTensor(n,e,t)}function xt(e,t="float32"){if(t==="complex64"){const r=xt(e,"float32"),o=Re(e,"float32");return Ve(r,o)}const n=Yi(te(e),t);return g.makeTensor(n,e,t)}function ML(e,t=null,n=!1){const r=u(e,"x","mean"),o=z(t,r.shape),i=zp(r.shape,o),a=i[1],s=te(a),c=Je(p=>{const l=k(s),h=l.dtype===p.dtype?p:E(p,l.dtype),m=U(h,l),b=W(m,t,n),y=w=>{const L=p.shape.slice();o.forEach(R=>{L[R]=1});const v=x(w,L),A=U(S(v,xt(p.shape,"float32")),s);return A};return{value:b,gradFunc:y}});return c(r)}const mn=d({mean_:ML});function UL(e,t=null,n=!1){const r=u(e,"x","min"),o=(s,c)=>{const p=z(t,r.shape);let l=p;const h=fe(l,r.rank);let m=r;h!=null&&(m=Z(r,h),l=De(l.length,r.rank));const b=s.min(m,l);h!=null&&m.dispose();let y=b;if(n){const w=we(y.shape,p);y=x(b,w),b.dispose()}return c([r,y]),y},i={x:r},a={axis:t,keepDims:n};return g.runKernelFunc(o,i,null,ni,a)}const fn=d({min_:UL});function WL(e,t){let n=u(e,"a","minimum"),r=u(t,"b","minimum");[n,r]=K(n,r),n.dtype==="bool"&&(n=E(n,"int32"),r=E(r,"int32")),q(n.shape,r.shape);const o=(a,s)=>{const c=a.minimum(n,r);return s([n,r]),c},i={a:n,b:r};return g.runKernelFunc(o,i,null,ri)}const $n=d({minimum_:WL});function BL(e,t){let n=u(e,"a","mod"),r=u(t,"b","mod");[n,r]=K(n,r);const o=(a,s)=>{const c=a.mod(n,r);return s([n,r]),c},i={a:n,b:r};return g.runKernelFunc(o,i,null,oi)}const us=d({mod_:BL});function $L(e){const t=u(e,"x","square"),n={},r=[t],o=[];return g.runKernelFunc((i,a)=>(a([t]),i.square(t)),{x:t},null,"Square",n,r,o)}const H=d({square_:$L});function GL(e,t=null,n=!1){e=u(e,"x","moments");const r=z(t,e.shape),o=mn(e,r,n);let i=o.shape;n||(i=we(o.shape,r));const a=H(_(E(e,"float32"),x(o,i))),s=mn(a,r,n);return{mean:o,variance:s}}const Jl=d({moments_:GL});function jL(e,t,n,r){const o=u(t,"data","multiRNNCell"),i=Vt(n,"c","multiRNNCell"),a=Vt(r,"h","multiRNNCell");let s=o;const c=[];for(let h=0;h<e.length;h++){const m=e[h](s,i[h],a[h]);c.push(m[0]),c.push(m[1]),s=m[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 Xl=d({multiRNNCell_:jL});function PL(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?x(o,[1,-1]):o,c=g.runKernelFunc(p=>p.multinomial(s,r,t,n),{logits2D:s});return a===1?x(c,[c.size]):c}const Zl=d({multinomial_:PL});function qL(e,t){let n=u(e,"a","notEqual"),r=u(t,"b","notEqual");[n,r]=K(n,r),q(n.shape,r.shape);const o=a=>a.notEqual(n,r),i={a:n,b:r};return g.runKernelFunc(o,i,null,pp)}const Gn=d({notEqual_:qL});function HL(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]),x(p.oneHot(x(o,[o.size]),t,n,r),i)),s={indices:o},c={depth:t,onValue:n,offValue:r};return g.runKernelFunc(a,s,null,ci,c)}const Cr=d({oneHot_:HL});function zL(e){const t=u(e,"x","onesLike"),n=(o,i)=>{if(t.dtype==="complex64"){const a=ga(Gt(t)),s=B(Qt(t));return Ve(a,s)}return o.onesLike(t)},r={x:t};return g.runKernelFunc(n,r,null,ai)}const ga=d({onesLike_:zL});function YL(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=x(n,[-1,1]),i=x(r,[1,-1]);return Y(o,i)}const Ql=d({outerProduct_:YL});function VL(e,t,n=0){const r=u(e,"x","pad");if(r.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");const o=(s,c)=>(c([r]),s.pad(r,t,n)),i={paddings:t,constantValue:n},a={x:r};return g.runKernelFunc(o,a,null,pi,i)}const je=d({pad_:VL});function KL(e,t,n=0){return f(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),je(e,[t],n)}const eh=d({pad1d_:KL});function JL(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."),je(e,t,n)}const th=d({pad2d_:JL});function XL(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."),je(e,t,n)}const nh=d({pad3d_:XL});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."),je(e,t,n)}const rh=d({pad4d_:ZL});function QL(e,t,n){const r=u(e,"x","spaceToBatchND");f(r.rank>=1+t.length,()=>`input rank ${r.rank} should be > than [blockShape] ${t.length}`),f(n.length===t.length,()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`),f(r.shape.reduce((s,c,p)=>p>0&&p<=t.length?s&&(c+n[p-1][0]+n[p-1][1])%t[p-1]===0:s,!0),()=>`input spatial dimensions ${r.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`);const o=s=>s.spaceToBatchND(r,t,n),i={x:r},a={blockShape:t,paddings:n};return g.runKernelFunc(o,i,null,Oi,a)}const jn=d({spaceToBatchND_:QL});function nS(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=x(a,[1,a.shape[0],a.shape[1],a.shape[2]])),f(pe(i,o),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${i} and dilations '${o}'`);const p=At(s.shape,t,i,o,r),l=[p.dilationHeight,p.dilationWidth];let h;r==="same"?h=tS([p.filterHeight,p.filterWidth],l):h=[[0,0],[0,0]];const m=l[0]===1&&l[1]===1,[b,y]=eS([p.inHeight,p.inWidth],l,h),w=m?r:"valid",L=m?s:jn(s,l,b),v=n==="avg"?()=>ht(L,t,i,w):()=>Ie(L,t,i,w),A=v(),R=m?A:kn(A,l,y);return c?x(R,[R.shape[1],R.shape[2],R.shape[3]]):R}function eS(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 tS(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 oh=d({pool_:nS});function rS(e,t){let n=u(e,"base","pow"),r=u(t,"exp","pow");[n,r]=K(n,r);const o={a:n,b:r},i=(a,s)=>{const c=a.pow(n,r);return s([n,r,c]),c};return g.runKernelFunc(i,o,null,li)}const Xe=d({pow_:rS});function oS(e,t){const n=u(e,"x","prelu"),r=u(t,"alpha","prelu"),o=(a,s)=>{const c=a.prelu(n,r);return s([n,r]),c},i={x:n,alpha:r};return g.runKernelFunc(o,i,null,hi)}const ds=d({prelu_:oS});function ih(e,t=!1){console.log(e.toString(t))}function iS(e,t=null,n=!1){let r=u(e,"x","prod");const o=s=>{r.dtype==="bool"&&(r=E(r,"int32"));const c=z(t,r.shape),p=fe(c,r.rank);let l=c,h=r;p!=null&&(h=Z(r,p),l=De(l.length,r.rank));let m=s.prod(h,l);if(n){const b=we(m.shape,c);m=x(m,b)}return m},i={x:r},a={axis:t,keepDims:n};return g.runKernelFunc(o,i,null,dp,a)}const sh=d({prod_:iS});function sS(e,t,n){const r=te(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 g.makeTensor(o,e,n)}const ah=d({rand_:sS});const Id={};me(Id,{TEST_EPSILON_FLOAT16:()=>Td,expectArrayBuffersEqual:()=>dS,expectArraysClose:()=>cS,expectArraysEqual:()=>lS,expectNumbersClose:()=>hS,expectPromiseToFail:()=>pS,expectValuesInRange:()=>uS,testEpsilon:()=>ch});const aS=.001,Td=.1;function cS(e,t,n){return n==null&&(n=ch()),ph(e,t,(r,o)=>lh(r,o,n))}function ch(){return g.backend.floatPrecision()===32?aS:Td}function ph(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=Fe(e),s=Fe(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 pS(e,t){e().then(()=>t.fail(),()=>t())}function lS(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])?ph(e,n,(r,o)=>r==o):ph(e,t,(r,o)=>lh(r,o,0))}function hS(e,t,n){if(n==null&&(n=ch()),!lh(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function lh(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function uS(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 dS(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}const ba=ee(Ru());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=ba.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 Ad{constructor(e,t,n,r){this.alpha=e,this.beta=1/t,this.dtype=n;const o=r||Math.random();this.randu=ba.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 Nd{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=ba.alea(r)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}function mS(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 Ad(t,n,r,o),a=Me(e,r);for(let s=0;s<a.values.length;s++)a.values[s]=i.nextValue();return a.toTensor()}const hh=d({randomGamma_:mS});function fS(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=Me(e,r);for(let s=0;s<a.values.length;s++)a.values[s]=i.nextValue();return a.toTensor()}const uh=d({randomNormal_:fS});function gS(e,t=0,n=1,r="float32",o){const i=Me(e,r),a=new Nd(t,n,null,o);for(let s=0;s<i.values.length;s++)i.values[s]=a.nextValue();return i.toTensor()}const fs=d({randomUniform_:gS});function ge(e,t){pt(e);const n=Fe(e,t);if(n.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");const r=null;return ze(e,r,n,t)}function Er(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 Re([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 ge(l,r)},i={start:e,stop:t,step:n,dtype:r};return g.runKernelFunc(o,{},null,mp,i)}function bS(e){const t=u(e,"x","reciprocal"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.reciprocal(t);return o([t]),i},n,null,ui)}const dh=d({reciprocal_:bS});function wS(e){const t=u(e,"x","relu"),n=(o,i)=>(i([t]),t.dtype==="bool"?E(t,"int32"):o.relu(t)),r={x:t};return g.runKernelFunc(n,r,null,di)}const se=d({relu_:wS});function yS(e){const t=u(e,"x","relu6"),n=(o,i)=>(i([t]),t.dtype==="bool"?E(t,"int32"):o.relu6(t)),r={x:t};return g.runKernelFunc(n,r,null,bi)}const gs=d({relu6_:yS});function xS(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}.`),Ke(t,0)}const mh=d({reverse1d_:xS});function LS(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}.`),Ke(n,t)}const fh=d({reverse2d_:LS});function SS(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}.`),Ke(n,t)}const gh=d({reverse3d_:SS});function vS(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}.`),Ke(n,t)}const bh=d({reverse4d_:vS});function wh(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 IS(e,t,n=0){const r=u(e,"x","split"),o=(s,c)=>{const p=z(n,r.shape)[0],l=wh(r,t,p);return s.split(r,l,p)},i={x:r},a={numOrSizeSplits:t,axis:n};return g.runKernelFunc(o,i,null,ki,a)}const jt=d({split_:IS});function TS(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 y=e.shape.map(L=>0),w=e.shape.map(L=>L);w[e.shape.length-1]=t,o=V(e,y,w),n=t}else if(t!=null&&t>n){const y=e.shape.map(w=>w);y[e.shape.length-1]=t-n,o=Q([e,Re(y)],e.shape.length-1),n=t}else o=e;const i=B(o),a=x(Ve(o,i),[r,n]),s=Fn(a),c=Math.floor(n/2)+1,p=Gt(s),l=Qt(s),h=jt(p,[c,n-c],p.shape.length-1),m=jt(l,[c,n-c],l.shape.length-1),b=o.shape.slice();return b[o.shape.length-1]=c,x(Ve(h[0],m[0]),b)}const Pn=d({rfft_:TS});function AS(e){const t=u(e,"x","round"),n={x:t};return g.runKernelFunc(r=>r.round(t),n,null,yi)}const yh=d({round_:AS});function NS(e){const t=u(e,"x","rsqrt"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.rsqrt(t);return o([t]),i},n,null,xi)}const bs=d({rsqrt_:NS});function RS(e){const t=u(e,"x","selu"),n=(o,i)=>{const a=o.selu(t);return i([t]),a},r={x:t};return g.runKernelFunc(n,r,null,Si)}const xh=d({selu_:RS});function CS(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=x(s,[1,s.shape[0],s.shape[1],s.shape[2]])),a==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");f(l.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${l.rank}.`),f(c.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${c.rank}.`),f(p.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${c.rank}.`),f(p.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${p.shape[0]}.`),f(p.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${p.shape[1]}.`);const m=c.shape[2],b=c.shape[3];f(p.shape[2]===m*b,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${m*b}, but got ${p.shape[2]}.`);const y=Dn(l,c,r,o,a,i),w=1,L=ve(y,p,w,"valid",a);return h?x(L,[L.shape[1],L.shape[2],L.shape[3]]):L}const qn=d({separableConv2d_:CS});async function ES(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 Sr([s],n.dtype),p=new Sr([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 Lh=ES;function OS(e){const t=u(e,"x","sign"),n={x:t};return g.runKernelFunc(r=>r.sign(t),n,null,Ai)}const Sh=d({sign_:OS});function kS(e){const t=u(e,"x","sin"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.sin(t);return o([t]),i},n,null,Ii)}const ws=d({sin_:kS});function _S(e){const t=u(e,"x","sinh"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.sinh(t);return o([t]),i},n,null,Ti)}const ys=d({sinh_:_S});function DS(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`),V(r,[t],[n])}const vh=d({slice1d_:DS});function FS(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`),V(r,t,n)}const Ih=d({slice2d_:FS});function MS(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`),V(r,t,n)}const xs=d({slice3d_:MS});function US(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`),V(r,t,n)}const Th=d({slice4d_:US});function WS(e,t=-1){const n=u(e,"logits","softmax","float32");if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and dim was ${t}`);const r={logits:n},o={dim:t};return g.runKernelFunc((i,a)=>{const s=i.softmax(n,t);return a([s]),s},r,null,_i,o)}const en=d({softmax_:WS});function BS(e){const t=u(e,"x","sqrt"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.sqrt(t);return o([t]),i},n,null,Ci)}const de=d({sqrt_:BS});function $S(e,t){let n=u(e,"a","squaredDifference"),r=u(t,"b","squaredDifference");[n,r]=K(n,r),q(n.shape,r.shape);const o=(s,c)=>{const p=s.squaredDifference(n,r);return c([n,r]),p},i={a:n,b:r},a={};return g.runKernelFunc(o,i,null,Di,a)}const Hn=d({squaredDifference_:$S});function GS(e,t){const n=u(e,"x","squeeze");return x(n,Np(n.shape,t).newShape)}const zn=d({squeeze_:GS});function jS(e,t=0){const n=Vt(e,"tensors","stack");if(f(n.length>=1,()=>"Pass at least one tensor to tf.stack"),n.length===1)return et(n[0],t);const r=n[0].rank,o=n[0].shape,i=n[0].dtype;f(t<=r,()=>"Axis must be <= rank of the tensor"),n.forEach(s=>{P(o,s.shape,"All tensors passed to stack must have matching shapes"),f(i===s.dtype,()=>"All tensors passed to stack must have matching dtypes")});const a=n.map(s=>et(s,t));return Q(a,t)}const Ue=d({stack_:jS});function PS(e,t=0){const n=u(e,"x","step"),r={x:n},o={alpha:t};return g.runKernelFunc(i=>i.step(n,t),r,null,Pi,o)}const Et=d({step_:PS});function qS(e,t,n,r,o=0,i=0,a=0,s=0,c=0){r==null&&(r=new Array(t.length));let p=u(e,"x","stridedSlice");const l=b=>{const y=es(a);if(y.length>1)throw new Error("Multiple ellipses in slice is not allowed.");if(a!==0&&s!==0)throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");if(a!==0&&c!==0)throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");const w=p.rank-t.length,L=es(s),v=p.shape.slice();if(L.forEach(D=>{t[D]=0,n[D]=1,v.splice(D,0,1)}),p=x(p,v),y.length&&w>0){const D=y[0],G=w+1;t=hl(o,D,G,t,p.shape),n=ul(i,D,G,n,p.shape),r=ll(r,D,G,p.shape)}else for(let D=0;D<p.rank;D++)t[D]=ml(o,t,r,p.shape,D,a),n[D]=fl(i,n,r,p.shape,D,a),r[D]=dl(r,D,a);const A=es(c);A.forEach(D=>{n[D]=t[D]+1,r[D]=1});const R=pl(t,n,r),N=R.filter((D,G)=>A.indexOf(G)===-1),O=r.every(D=>D===1);if(O)return x(V(p,t,R),N);const M=b.stridedSlice(p,t,n,r);return x(M,N)},h={x:p},m={begin:t,end:n,strides:r,beginMask:o,endMask:i,ellipsisMask:a,newAxisMask:s,shrinkAxisMask:c};return g.runKernelFunc(l,h,null,Lp,m)}const Ah=d({stridedSlice_:qS});function HS(e){const t=u(e,"x","tan"),n={x:t};return g.runKernelFunc((r,o)=>{const i=r.tan(t);return o([t]),i},n,null,Mi)}const Nh=d({tan_:HS});function ft(e,t,n){if(pt(e),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");const r=Fe(e,n);if(r.length!==2&&r.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(r.length===1&&t==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return ze(e,t,r,n)}function Ls(e,t,n){if(pt(e),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");const r=Fe(e,n);if(r.length!==3&&r.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(r.length===1&&t==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return ze(e,t,r,n)}function Pt(e,t,n){if(pt(e),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");const r=Fe(e,n);if(r.length!==4&&r.length!==1)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(r.length===1&&t==null)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return ze(e,t,r,n)}function Rh(e,t,n){if(pt(e),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");const r=Fe(e,n);if(r.length!==5&&r.length!==1)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(r.length===1&&t==null)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return ze(e,t,r,n)}function Ch(e,t,n){if(pt(e),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");const r=Fe(e,n);if(r.length!==6&&r.length!==1)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(r.length===1&&t==null)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return t=t||r,ze(e,t,r,n)}function zS(e,t=1,n=!0){const r=u(e,"x","topk");if(r.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");const o=r.shape[r.shape.length-1];if(t>o)throw new Error(`'k' passed to topk() must be <= the last dimension (${o}) but got ${t}`);const i={x:r},a={k:t,sorted:n},[s,c]=g.runKernelFunc(p=>p.topk(r,t,n),i,null,Sp,a);return{values:s,indices:c}}const Eh=d({topk_:zS});function YS(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=Me(e,r);for(let s=0;s<a.values.length;s++)a.values[s]=i.nextValue();return a.toTensor()}const Oh=d({truncatedNormal_:YS});function VS(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 g.runKernelFunc(s,i,null,Gi,a)}const Ss=d({unsortedSegmentSum_:VS});function KS(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 g.runKernelFunc(i,r,null,$i,o)}const We=d({unstack_:KS});function kh(e,t=!0,n,r){return g.makeVariable(e,t,n,r)}function wa(e,t){const n=[];for(let i=0;i<t.length;i++)t[i]&&n.push(i);const r=Me(e,"int32"),o=Me([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 JS(e){const t=u(e,"condition","whereAsync","bool"),n=await t.data(),r=wa(t.shape,n);return e!==t&&t.dispose(),r}const vs=JS;async function XS(e,t,n){const r=u(e,"tensor","boolMask"),o=u(t,"mask","boolMask","bool"),i=n??0,a=o.rank,s=r.shape;f(a>0,()=>"mask cannot be scalar"),P(s.slice(i,i+a),o.shape,"mask's shape must match the first K dimensions of tensor's shape,");let c=1;for(let w=i;w<i+a;w++)c*=s[w];const p=s.slice(0,i).concat([c],s.slice(i+a)),l=x(r,p),h=x(o,[-1]),m=await vs(h),b=zn(m,[1]),y=Un(l,b,i);return e!==r&&r.dispose(),t!==o&&o.dispose(),b.dispose(),l.dispose(),h.dispose(),m.dispose(),y}const Rd=XS;function ZS(e,t){xe("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 P(n.shape,r.shape,"Error in notEqualStrict: "),Gn(n,r)}function QS(e,t){xe("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 P(n.shape,r.shape,"Error in lessStrict: "),Wn(n,r)}function ev(e,t){xe("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 P(n.shape,r.shape,"Error in equalStrict: "),Xt(n,r)}function tv(e,t){xe("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 P(n.shape,r.shape,"Error in lessEqualStrict: "),dt(n,r)}function nv(e,t){xe("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 P(n.shape,r.shape,"Error in greaterStrict: "),tt(n,r)}function rv(e,t){xe("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 P(n.shape,r.shape,"Error in greaterEqualStrict: "),ut(n,r)}const Cd=d({equalStrict_:ev}),Ed=d({greaterEqualStrict_:rv}),Od=d({greaterStrict_:nv}),kd=d({lessEqualStrict_:tv}),_d=d({lessStrict_:QS}),Dd=d({notEqualStrict_:ZS});function ov(e,t){xe("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 P(n.shape,r.shape,"Error in addStrict: "),C(n,r)}function iv(e,t){xe("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 P(n.shape,r.shape,"Error in subStrict: "),_(n,r)}function sv(e,t){return xe("strict variants of ops have been deprecated and will be removed in future"),P(e.shape,t.shape,"Error in powStrict: "),Xe(e,t)}function av(e,t){xe("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 P(n.shape,r.shape,"Error in multiplyStrict: "),S(n,r)}function cv(e,t){xe("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 P(n.shape,r.shape,"Error in divideStrict: "),U(n,r)}function pv(e,t){xe("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 P(n.shape,r.shape,"Error in modStrict: "),us(n,r)}function lv(e,t){xe("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 P(n.shape,r.shape,"Error in minimumStrict: "),$n(n,r)}function hv(e,t){xe("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 P(n.shape,r.shape,"Error in maximumStrict: "),Ct(n,r)}function uv(e,t){xe("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 P(n.shape,r.shape,"Error in squaredDifferenceStrict: "),Hn(n,r)}const Fd=d({addStrict_:ov}),Md=d({divStrict_:cv}),Ud=d({maximumStrict_:hv}),Wd=d({minimumStrict_:lv}),Bd=d({modStrict_:pv}),$d=d({mulStrict_:av}),Gd=d({powStrict_:sv}),jd=d({squaredDifferenceStrict_:uv}),Pd=d({subStrict_:iv});function dv(e,t="euclidean",n=null,r=!1){e=u(e,"x","norm");const o=qd(e,t,n);let i=o.shape;if(r){const a=z(n,e.shape);i=we(o.shape,a)}return x(o,i)}function qd(e,t,n=null){if(e.rank===0)return Ce(e);if(e.rank!==1&&n===null)return qd(x(e,[-1]),t,n);if(e.rank===1||typeof n=="number"||Array.isArray(n)&&n.length===1){if(t===1)return W(Ce(e),n);if(t===Infinity)return mt(Ce(e),n);if(t===-Infinity)return fn(Ce(e),n);if(t==="euclidean"||t===2)return de(W(Xe(Ce(e),k(2,"int32")),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(n)&&n.length===2){if(t===1)return mt(W(Ce(e),n[0]),n[1]-1);if(t===Infinity)return mt(W(Ce(e),n[1]),n[0]);if(t===-Infinity)return fn(W(Ce(e),n[1]),n[0]);if(t==="fro"||t==="euclidean")return de(W(H(e),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${n}`)}const Or=d({norm_:dv});function mv(e,t,n,r,o=!0){const i=u(e,"v","movingAverage"),a=u(t,"x","movingAverage"),s=u(n,"decay","movingAverage");$p(i,a),f(Se(i.shape,a.shape),()=>"Shape mismatch in v and x");const c=k(1),p=_(c,s);let l=S(_(a,i),p);if(o){f(r!=null,()=>"When using zeroDebias: true, step is required.");const h=u(r,"step","movingAverage");l=U(l,_(c,Xe(s,h)))}return C(i,l)}const Hd=d({movingAverage_:mv});const zd={};me(zd,{calculateShapes:()=>Yd,validateInput:()=>ya,validateUpdateShape:()=>_h});function _h(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 ya(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}`)}_h(n,t,e)}function Yd(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=te(t.shape)/s,p=[...Ut(n.slice(0,o)),1],l=te(n);return{sliceRank:o,numUpdates:c,sliceSize:a,strides:p,outputSize:l}}function fv(e,t,n){const r=u(e,"indices","scatterND","int32"),o=u(t,"updates","scatterND");ya(o,r,n);const i=c=>c.scatterND(r,o,n),a={indices:r,updates:o},s={shape:n};return g.runKernelFunc(i,a,null,wp,s)}const Vd=d({scatterND_:fv});function Kd(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 gv(e,t,n,r=0){const o=u(e,"sparseIndices","sparseToDense","int32"),i=u(t,"sparseValues","sparseToDense"),a=u(r,"defaultValue","sparseToDense",i.dtype);Kd(o,i,n,a);const s={sparseIndices:o,sparseValues:i,defaultValue:a},c={outputShape:n};return g.runKernelFunc(p=>p.sparseToDense(o,i,n,a),s,null,xp,c)}const Jd=d({sparseToDense_:gv});function bv(e,t){const n=u(t,"indices","gatherND","int32"),r=u(e,"x","gatherND"),o=a=>a.gatherND(r,n),i={params:r,indices:n};return g.runKernelFunc(o,i,null,Kc)}const Xd=d({gatherND_:bv});function Zd(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 wv(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 ne?o.clone():o;const i=Zd(o,n),a=1-t,s=U(Mn(C(fs(i,0,1,"float32",r),a)),a);return S(o,s)}const Qd=d({dropout_:wv});function xa(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function kr(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 ge(o,"float32")}async function yv(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}`),P(r.shape.slice(0,r.shape.length-1),o.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");const i=r.shape[r.shape.length-1];f(n>0&&n<=i,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${i}), but got ${n}`);const a=await r.data(),s=await o.data(),[c,p]=[a.length/i,i],l=yr("bool",c);for(let h=0;h<c;h++){const m=h*p,b=a.subarray(m,m+p),y=[];for(let w=0;w<b.length;w++)y.push({value:b[w],index:w});y.sort((w,L)=>L.value-w.value),l[h]=0;for(let w=0;w<n;w++)if(y[w].index===s[h]){l[h]=1;break}}return e!==r&&r.dispose(),t!==o&&o.dispose(),Ye(l,o.shape,"bool")}const em=yv;function xv(e,t,n,r,o,i="NHWC",a){let s=e;e.rank===3&&(s=x(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let c=t;c.rank===3&&(c=x(t,[1,t.shape[0],t.shape[1],t.shape[2]])),f(s.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${s.shape}.`),f(c.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${c.shape}.`),f(n.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`);const p=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=y=>{const w=1,L=hn(i),v=$e(s.shape,n,r,w,o,a,!1,L);return y.conv2dDerFilter(s,c,v)},m={x:s,dy:c},b={strides:r,pad:o,dataFormat:i,dimRoundingMode:a};return g.runKernelFunc(h,m,null,Dc,b)}const _r=d({conv2DBackpropFilter_:xv});function Yn(e,t,n){if(n==null||n==="linear")return e;if(n==="relu")return S(e,Et(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function Vn(e,t){let n=t;const r=ae(e.shape,t.shape);return r.length>0&&(n=W(n,r)),x(n,e.shape)}function Kn(e,t,n){if(t==="linear")return e;if(t==="relu")return se(e);if(t==="elu")return is(e);if(t==="relu6")return gs(e);if(t==="prelu")return ds(e,n);throw new Error(`Unknown fused activation ${t}.`)}const Jn=(e,t)=>{const n=e>0;return!n||t==="linear"};function Lv({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",Jn(g.state.gradientDepth,c)===!1){let O=ve(e,t,n,r,o,i,a);return s!=null&&(O=C(O,s)),Kn(O,c,p)}const l=u(e,"x","conv2d"),h=u(t,"filter","conv2d");let m=l,b=!1;l.rank===3&&(b=!0,m=x(l,[1,l.shape[0],l.shape[1],l.shape[2]])),f(m.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${m.rank}.`),f(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(m.shape[3]===h.shape[2],()=>`Error in conv2d: depth of input (${m.shape[3]}) must match input depth for filter ${h.shape[2]}.`),f(pe(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 y=$e(m.shape,h.shape,n,i,r,a);let w;s!=null&&(w=u(s,"bias","fused conv2d"),[w]=K(w,l),q(y.outShape,w.shape));let L;p!=null&&(L=u(p,"prelu weights","fused conv2d"));const v=(O,M)=>{const[D,G,$,j]=M,oe=Yn(O,$,c);f(lt(i),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${i}'`);const ie=Rr(G.shape,oe,D,n,r),ue=_r(G,oe,D.shape,n,r),Ae=[ie,ue];if(j!=null){const Pe=Vn(j,oe);Ae.push(Pe)}return Ae},A=O=>{const M=O.fusedConv2d({input:m,filter:h,convInfo:y,bias:w,activation:c,preluActivationWeights:L});return M},R={x:m,filter:h,bias:w,preluActivationWeights:L},N={strides:n,pad:r,dataFormat:o,dilations:i,dimRoundingMode:a,activation:c};if(s==null){const O=Je((M,D,G)=>{let $=g.runKernelFunc(A,R,null,oa,N);return G([D,M,$]),b&&($=x($,[$.shape[1],$.shape[2],$.shape[3]])),{value:$,gradFunc:v}});return O(m,h)}else{const O=Je((M,D,G,$)=>{let j=g.runKernelFunc(A,R,null,oa,N);return $([D,M,j,G]),b&&(j=x(j,[j.shape[1],j.shape[2],j.shape[3]])),{value:j,gradFunc:v}});return O(m,h,w)}}const Sv=d({fusedConv2d_:Lv});function vv(e,t,n,r){let o=e;e.rank===3&&(o=x(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let i=t;i.rank===3&&(i=x(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const a=c=>c.depthwiseConv2DDerFilter(o,i,r),s={x:o,dy:i};return g.runKernelFunc(a,s,null,Bc)}const La=d({depthwiseConv2dNativeBackpropFilter_:vv});function Iv(e,t,n,r){let o=t,i=!1;t.rank===3&&(i=!0,o=x(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const a=p=>p.depthwiseConv2DDerInput(o,n,r),s={dy:o},c=g.runKernelFunc(a,s,null,$c);return i?x(c,[c.shape[1],c.shape[2],c.shape[3]]):c}const Sa=d({depthwiseConv2dNativeBackpropInput_:Iv});function Tv({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(Jn(g.state.gradientDepth,c)===!1){let O=Dn(e,t,n,r,o,i,a);return s!=null&&(O=C(O,s)),Kn(O,c,p)}const l=u(e,"x","depthwiseConv2d"),h=u(t,"filter","depthwiseConv2d");let m=l,b=!1;l.rank===3&&(b=!0,m=x(l,[1,l.shape[0],l.shape[1],l.shape[2]])),f(m.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${m.rank}.`),f(h.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${h.rank}.`),f(m.shape[3]===h.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${m.shape[3]}) must match the inChannels dimension in filter ${h.shape[2]}.`),i==null&&(i=[1,1]),f(pe(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 y=$e(m.shape,h.shape,n,i,r,a,!0);let w;s!=null&&(w=u(s,"bias","fused conv2d"),[w]=K(w,l),q(y.outShape,w.shape));let L;p!=null&&(L=u(p,"prelu weights","fused depthwiseConv2d"));const v=(O,M)=>{f(lt(i),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${i}'`);const[D,G,$,j]=M,oe=Yn(O,$,c),ie=Sa(G.shape,oe,D,y),ue=La(G,oe,D.shape,y);if(j!=null){const Ae=Vn(w,oe);return[ie,ue,Ae]}return[ie,ue]},A=O=>{const M=O.fusedDepthwiseConv2D({input:m,filter:h,convInfo:y,bias:w,activation:c,preluActivationWeights:L});return M},R={x:m,filter:h,bias:w,preluActivationWeights:L},N={strides:n,pad:r,dataFormat:o,dilations:i,dimRoundingMode:a,activation:c};if(s==null){const O=Je((M,D,G)=>{let $=g.runKernelFunc(A,R,null,ia,N);return G([D,M,$]),b&&($=x($,[$.shape[1],$.shape[2],$.shape[3]])),{value:$,gradFunc:v}});return O(m,h)}else{const O=Je((M,D,G,$)=>{let j=g.runKernelFunc(A,R,null,ia,N);return $([D,M,j,G]),b&&(j=x(j,[j.shape[1],j.shape[2],j.shape[3]])),{value:j,gradFunc:v}});return O(m,h,w)}}const Av=d({fusedDepthwiseConv2d_:Tv});function Nv({a:e,b:t,transposeA:n=!1,transposeB:r=!1,bias:o,activation:i="linear",preluActivationWeights:a}){if(Jn(g.state.gradientDepth,i)===!1){let j=Y(e,t,n,r);return o!=null&&(j=C(j,o)),Kn(j,i,a)}let s=u(e,"a","fused matMul"),c=u(t,"b","fused matMul");[s,c]=K(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],m=r?c.shape[c.rank-2]:c.shape[c.rank-1],b=s.shape.slice(0,-2),y=c.shape.slice(0,-2),w=te(b),L=te(y);f(s.rank>=2&&c.rank>=2&&s.rank===c.rank,()=>`Error in fused matMul: inputs must have the same rank of at least 2, got ranks ${s.rank} and ${c.rank}.`),f(Se(b,y),()=>`Error in fused matMul: outer dimensions (${b}) and (${y}) of Tensors with shapes ${s.shape} and ${c.shape} must match.`),f(p===l,()=>`Error in fused matMul: inner shapes (${p}) and (${l}) of Tensors with shapes ${s.shape} and ${c.shape} and transposeA=${n} and transposeB=${r} must match.`);const v=s.shape.slice(0,-2).concat([h,m]),A=n?x(s,[w,p,h]):x(s,[w,h,p]),R=r?x(c,[L,m,l]):x(c,[L,l,m]);let N;o!=null&&(N=u(o,"bias","fused matMul"),[N]=K(N,s),q(v,N.shape));let O;a!=null&&(O=u(a,"prelu weights","fused matMul"));const M=(j,oe)=>{const[ie,ue,Ae,Pe]=oe,zt=Yn(x(j,Ae.shape),Ae,i);let pr,lr;if(!n&&!r?(pr=Y(zt,ue,!1,!0),lr=Y(ie,zt,!0,!1)):!n&&r?(pr=Y(zt,ue,!1,!1),lr=Y(zt,ie,!0,!1)):n&&!r?(pr=Y(ue,zt,!1,!0),lr=Y(ie,zt,!1,!1)):(pr=Y(ue,zt,!0,!0),lr=Y(zt,ie,!0,!0)),o!=null){const Bb=Vn(Pe,zt);return[pr,lr,Bb]}else return[pr,lr]},D=j=>{const oe=j.fusedBatchMatMul({a:A,b:R,transposeA:n,transposeB:r,bias:N,activation:i,preluActivationWeights:O});return oe},G={a:A,b:R,bias:N,preluActivationWeights:O},$={transposeA:n,transposeB:r,activation:i};if(o==null){const j=Je((oe,ie,ue)=>{const Ae=g.runKernelFunc(D,G,null,ra,$);return ue([oe,ie,Ae]),{value:x(Ae,v),gradFunc:M}});return j(A,R)}else{const j=Je((oe,ie,ue,Ae)=>{const Pe=g.runKernelFunc(D,G,null,ra,$);return Ae([oe,ie,Pe,ue]),{value:x(Pe,v),gradFunc:M}});return j(A,R,N)}}const Rv=d({fusedMatMul_:Nv});const Dh={};me(Dh,{conv2d:()=>Sv,depthwiseConv2d:()=>Av,matMul:()=>Rv});function Cv(e){return kr(e,.54,.46)}const tm=d({hammingWindow_:Cv});function Ev(e){return kr(e,.5,.5)}const va=d({hannWindow_:Ev});function Ov(e,t,n,r=!1,o=0){let i=0;const a=[];for(;i+t<=e.size;)a.push(V(e,i,t)),i+=n;if(r)for(;i<e.size;){const s=i+t-e.size,c=Q([V(e,i,t-s),Ge([s],o)]);a.push(c),i+=n}return a.length===0?ft([],[0,t]):x(Q(a),[a.length,t])}const Ia=d({frame_:Ov});function kv(e,t,n,r,o=va){r==null&&(r=xa(t));const i=Ia(e,t,n),a=S(i,o(t)),s=[];for(let c=0;c<i.shape[0];c++)s.push(Pn(V(a,[c,0],[1,t]),r));return Q(s)}const nm=d({stft_:kv});function _v(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=y=>y.cropAndResize(a,s,c,r,o,i),h={image:a,boxes:s,boxInd:c},m={method:o,extrapolationValue:i,cropSize:r},b=g.runKernelFunc(l,h,null,Uc,m);return b}const rm=d({cropAndResize_:_v});function Dv(e){const t=u(e,"image","flipLeftRight","float32");f(t.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);const n={image:t},r=g.runKernel(Vc,n,{});return r}const om=d({flipLeftRight_:Dv});function Fv(e,t,n=0,r=.5){const o=u(e,"image","rotateWithOffset","float32");f(o.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${o.rank}.`);const i={image:o},a={radians:t,fillValue:n,center:r},s=g.runKernel(vp,i,a);return s}const im=d({rotateWithOffset_:Fv});function Lt(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 Mv(e,t,n,r=.5,o=Number.NEGATIVE_INFINITY){const i=u(e,"boxes","nonMaxSuppression"),a=u(t,"scores","nonMaxSuppression"),s=Lt(i,a,n,r,o);n=s.maxOutputSize,r=s.iouThreshold,o=s.scoreThreshold;const c={maxOutputSize:n,iouThreshold:r,scoreThreshold:o};return g.runKernelFunc(p=>p.nonMaxSuppression(i,a,n,r,o),{boxes:i,scores:a},null,lp,c)}const sm=d({nonMaxSuppression_:Mv});function am(e,t,n){const r=Uv(e,t,n),o=r<0?-(r+1):r;e.splice(o,0,t)}function Uv(e,t,n){return Bv(e,t,n||Wv)}function Wv(e,t){return e>t?1:e<t?-1:0}function Bv(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 Ta(e,t,n,r,o){return Fh(e,t,n,r,o,0).selectedIndices}function Aa(e,t,n,r,o,i){return Fh(e,t,n,r,o,0,!1,i,!0)}function Na(e,t,n,r,o,i){return Fh(e,t,n,r,o,i,!0)}function Fh(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(cm);const l=i>0?-.5/i:0,h=[],m=[];for(;h.length<n&&p.length>0;){const L=p.pop(),{score:v,boxIndex:A,suppressBeginIndex:R}=L;if(v<o)break;let N=!1;for(let O=h.length-1;O>=R;--O){const M=$v(e,A,h[O]);if(M>=r){N=!0;break}if(L.score=L.score*Gv(r,l,M),L.score<=o)break}L.suppressBeginIndex=h.length,N||(L.score===v?(h.push(A),m.push(L.score)):L.score>o&&am(p,L,cm))}const b=h.length,y=n-b;s&&y>0&&(h.push(...new Array(y).fill(0)),m.push(...new Array(y).fill(0)));const w={selectedIndices:ge(h,"int32")};return a&&(w.selectedScores=ge(m,"float32")),c&&(w.validOutputs=k(b,"int32")),w}function $v(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]),m=Math.max(o[1],o[3]),b=(s-i)*(c-a),y=(h-p)*(m-l);if(b<=0||y<=0)return 0;const w=Math.max(i,p),L=Math.max(a,l),v=Math.min(s,h),A=Math.min(c,m),R=Math.max(v-w,0)*Math.max(A-L,0);return R/(b+y-R)}function Gv(e,t,n){const r=Math.exp(t*n*n);return n<=e?r:0}function cm(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function jv(e,t,n,r=.5,o=Number.NEGATIVE_INFINITY){const i=u(e,"boxes","nonMaxSuppressionAsync"),a=u(t,"scores","nonMaxSuppressionAsync"),s=Lt(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=Ta(p,l,n,r,o);return i!==e&&i.dispose(),a!==t&&a.dispose(),h}const pm=jv;function Pv(e,t,n,r=.5,o=Number.NEGATIVE_INFINITY,i=0){const a=u(e,"boxes","nonMaxSuppression"),s=u(t,"scores","nonMaxSuppression"),c=Lt(a,s,n,r,o,i);n=c.maxOutputSize,r=c.iouThreshold,o=c.scoreThreshold,i=c.softNmsSigma;const p={boxes:a,scores:s},l={maxOutputSize:n,iouThreshold:r,scoreThreshold:o,softNmsSigma:i},h=g.runKernel(up,p,l);return{selectedIndices:h[0],selectedScores:h[1]}}const lm=d({nonMaxSuppressionWithScore_:Pv});async function qv(e,t,n,r=.5,o=Number.NEGATIVE_INFINITY,i=0){const a=u(e,"boxes","nonMaxSuppressionAsync"),s=u(t,"scores","nonMaxSuppressionAsync"),c=Lt(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],m=Na(l,h,n,r,o,i);return a!==e&&a.dispose(),s!==t&&s.dispose(),m}const hm=qv;function Hv(e,t,n,r=.5,o=Number.NEGATIVE_INFINITY,i=!1){const a=u(e,"boxes","nonMaxSuppression"),s=u(t,"scores","nonMaxSuppression"),c=Lt(a,s,n,r,o,null),p=c.maxOutputSize,l=c.iouThreshold,h=c.scoreThreshold,m={boxes:a,scores:s},b={maxOutputSize:p,iouThreshold:l,scoreThreshold:h,padToMaxOutputSize:i},y=g.runKernel(hp,m,b);return{selectedIndices:y[0],validOutputs:y[1]}}const um=d({nonMaxSuppressionPadded_:Hv});async function zv(e,t,n,r=.5,o=Number.NEGATIVE_INFINITY,i=!1){const a=u(e,"boxes","nonMaxSuppressionAsync"),s=u(t,"scores","nonMaxSuppressionAsync"),c=Lt(a,s,n,r,o,null),p=c.maxOutputSize,l=c.iouThreshold,h=c.scoreThreshold,[m,b]=await Promise.all([a.data(),s.data()]),y=Aa(m,b,p,l,h,i);return a!==e&&a.dispose(),s!==t&&s.dispose(),y}const dm=zv;function Yv(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=x(r,[1,r.shape[0],r.shape[1],r.shape[2]]));const[a,s]=t,c=(m,b)=>(b([o]),m.resizeBilinear(o,a,s,n)),p={images:o},l={alignCorners:n,size:t},h=g.runKernelFunc(c,p,null,gi,l);return i?x(h,[h.shape[1],h.shape[2],h.shape[3]]):h}const mm=d({resizeBilinear_:Yv});function Vv(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=x(r,[1,r.shape[0],r.shape[1],r.shape[2]]));const[a,s]=t,c={images:o},p={alignCorners:n,size:t},l=(m,b)=>(b([o]),m.resizeNearestNeighbor(o,a,s,n)),h=g.runKernelFunc(l,c,null,fi,p);return i?x(h,[h.shape[1],h.shape[2],h.shape[3]]):h}const fm=d({resizeNearestNeighbor_:Vv});function Kv(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=x(Er(0,i,1,"int32"),[-1,1]),c=Er(0,a,1,"int32"),p=_(s,c),l=yt(dt(p,k(+t,"int32")),ut(p,k(-n,"int32"))),h=Re([i,a],r.dtype);return x(Ue(We(x(r,[-1,i,a])).map(m=>Ee(l,m,h))),o)}const gm=d({bandPart_:Kv});function Jv(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=jt(e,e.shape[0],0).map(o=>zn(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(g.tidy(()=>{let i=r[o];if(o>0)for(let a=0;a<o;++a){const s=S(W(S(n[a],i)),n[a]);i=_(i,s)}return U(i,Or(i,"euclidean"))}));return t?Ue(n,0):n}const bm=d({gramSchmidt_:Jv});function Xv(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 wm(e,t);{const n=e.shape.slice(0,e.shape.length-2).reduce((c,p)=>c*p),r=We(x(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),o=[],i=[];r.forEach(c=>{const[p,l]=wm(c,t);o.push(p),i.push(l)});const a=x(Ue(o,0),e.shape),s=x(Ue(i,0),e.shape);return[a,s]}}function wm(e,t=!1){return g.tidy(()=>{f(e.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`);const n=e.shape[0],r=e.shape[1];let o=ss(n),i=Rt(e);const a=ft([[1]],[1,1]);let s=Rt(a);const c=n>=r?r:n;for(let p=0;p<c;++p){const l=i,h=s,m=o;[s,i,o]=g.tidy(()=>{const b=V(i,[p,p],[n-p,1]),y=Or(b),w=V(i,[p,p],[1,1]),L=Ee(tt(w,0),ft([[-1]]),ft([[1]])),v=_(w,S(L,y)),A=U(b,v);A.shape[0]===1?s=Rt(a):s=Q([a,V(A,[1,0],[A.shape[0]-1,A.shape[1]])],0);const R=re(U(Y(L,v),y)),N=V(i,[p,0],[n-p,r]),O=S(R,s),M=Z(s);if(p===0)i=_(N,Y(O,Y(M,N)));else{const $=_(N,Y(O,Y(M,N)));i=Q([V(i,[0,0],[p,r]),$],0)}const D=Z(O),G=V(o,[0,p],[n,o.shape[1]-p]);if(p===0)o=_(G,Y(Y(G,s),D));else{const $=_(G,Y(Y(G,s),D));o=Q([V(o,[0,0],[n,p]),$],1)}return[s,i,o]}),Le([l,h,m])}return!t&&n>r&&(o=V(o,[0,0],[n,r]),i=V(i,[0,0],[r,r])),[o,i]})}const ym=d({qr_:Xv});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 Zv(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:S(r,o);if(n===be.NONE)return i;if(n===be.SUM)return W(i);if(n===be.MEAN){if(o==null)return mn(i);{const a=r.size/o.size,s=U(W(i),W(o));return a>1?U(s,k(a)):s}}if(n===be.SUM_BY_NONZERO_WEIGHTS){if(o==null)return U(W(i),k(r.size));{const a=S(o,xt(r.shape)),s=E(W(Gn(a,k(0))),"float32");return U(W(i),s)}}throw Error(`Unknown reduction: ${n}`)}const Be=d({computeWeightedLoss_:Zv});function Qv(e,t,n,r=be.SUM_BY_NONZERO_WEIGHTS){const o=u(e,"labels","absoluteDifference"),i=u(t,"predictions","absoluteDifference");let a=null;n!=null&&(a=u(n,"weights","absoluteDifference")),P(o.shape,i.shape,"Error in absoluteDifference: ");const s=Ce(_(o,i));return Be(s,a,r)}const xm=d({absoluteDifference_:Qv});function eI(e,t,n,r,o=be.SUM_BY_NONZERO_WEIGHTS){const i=u(e,"labels","cosineDistance"),a=u(t,"predictions","cosineDistance");let s=null;r!=null&&(s=u(r,"weights","cosineDistance")),P(i.shape,a.shape,"Error in cosineDistance: ");const c=k(1),p=_(c,W(S(i,a),n,!0));return Be(p,s,o)}const Lm=d({cosineDistance_:eI});function tI(e,t,n,r=be.SUM_BY_NONZERO_WEIGHTS){let o=u(e,"labels","hingeLoss");const i=u(t,"predictions","hingeLoss");let a=null;n!=null&&(a=u(n,"weights","hingeLoss")),P(o.shape,i.shape,"Error in hingeLoss: ");const s=k(1);o=_(S(k(2),o),s);const c=se(_(s,S(o,i)));return Be(c,a,r)}const Sm=d({hingeLoss_:tI});function nI(e,t,n,r=1,o=be.SUM_BY_NONZERO_WEIGHTS){const i=u(e,"labels","huberLoss"),a=u(t,"predictions","huberLoss");let s=null;n!=null&&(s=u(n,"weights","huberLoss")),P(i.shape,a.shape,"Error in huberLoss: ");const c=k(r),p=Ce(_(a,i)),l=$n(p,c),h=_(p,l),m=C(S(k(.5),H(l)),S(c,h));return Be(m,s,o)}const vm=d({huberLoss_:nI});function rI(e,t,n,r=1e-7,o=be.SUM_BY_NONZERO_WEIGHTS){const i=u(e,"labels","logLoss"),a=u(t,"predictions","logLoss");let s=null;n!=null&&(s=u(n,"weights","logLoss")),P(i.shape,a.shape,"Error in logLoss: ");const c=k(1),p=k(r),l=re(S(i,wt(C(a,p)))),h=S(_(c,i),wt(C(_(c,a),p))),m=_(l,h);return Be(m,s,o)}const Im=d({logLoss_:rI});function oI(e,t,n,r=be.SUM_BY_NONZERO_WEIGHTS){const o=u(e,"labels","meanSquaredError"),i=u(t,"predictions","meanSquaredError");let a=null;n!=null&&(a=u(n,"weights","meanSquaredError")),P(o.shape,i.shape,"Error in meanSquaredError: ");const s=Hn(o,i);return Be(s,a,r)}const Tm=d({meanSquaredError_:oI});function iI(e,t){const n=u(e,"labels","sigmoidCrossEntropyWithLogits"),r=u(t,"logits","sigmoidCrossEntropyWithLogits");P(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");const o=se(r),i=S(r,n),a=cs(Oe(re(Ce(r))));return C(_(o,i),a)}function sI(e,t,n,r=0,o=be.SUM_BY_NONZERO_WEIGHTS){let i=u(e,"multiClassLabels","sigmoidCrossEntropy");const a=u(t,"logits","sigmoidCrossEntropy");let s=null;if(n!=null&&(s=u(n,"weights","sigmoidCrossEntropy")),P(i.shape,a.shape,"Error in sigmoidCrossEntropy: "),r>0){const p=k(r),l=k(1),h=k(.5);i=C(S(i,_(l,p)),S(h,p))}const c=iI(i,a);return Be(c,s,o)}const Am=d({sigmoidCrossEntropy_:sI});function aI(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=Je((o,i,a)=>{const s=!0,c=ls(i,[n],s),p=_(E(i,"float32"),c);a([o,p]);const l=re(S(p,o)),h=W(l,[n]),m=(b,y)=>{const[w,L]=y,v=we(b.shape,[n]);return[S(x(b,v),_(E(w,"float32"),Oe(L))),S(x(b,v),_(Oe(L),E(w,"float32")))]};return{value:h,gradFunc:m}});return r(e,t)}function cI(e,t,n,r=0,o=be.SUM_BY_NONZERO_WEIGHTS){let i=u(e,"onehotLabels","softmaxCrossEntropy");const a=u(t,"logits","softmaxCrossEntropy");let s=null;if(n!=null&&(s=u(n,"weights","softmaxCrossEntropy")),P(i.shape,a.shape,"Error in softmaxCrossEntropy: "),r>0){const p=k(r),l=k(1),h=k(i.shape[1]);i=C(S(i,_(l,p)),U(p,h))}const c=aI(i,a);return Be(c,s,o)}const Nm=d({softmaxCrossEntropy_:cI});const Mh={};me(Mh,{abs:()=>Ce,acos:()=>jp,acosh:()=>Pp,add:()=>C,addN:()=>qp,addStrict:()=>Fd,all:()=>Yp,any:()=>Vp,argMax:()=>Kp,argMin:()=>Jp,asin:()=>Xp,asinh:()=>Zp,atan:()=>Qp,atan2:()=>el,atanh:()=>tl,avgPool:()=>ht,avgPool3d:()=>il,basicLSTMCell:()=>gl,batchNorm:()=>Jt,batchNorm2d:()=>bl,batchNorm3d:()=>wl,batchNorm4d:()=>yl,batchToSpaceND:()=>kn,booleanMaskAsync:()=>Rd,broadcastTo:()=>Nr,buffer:()=>Me,cast:()=>E,ceil:()=>xl,clipByValue:()=>Ll,clone:()=>Rt,complex:()=>Ve,concat:()=>Q,concat1d:()=>Sl,concat2d:()=>vl,concat3d:()=>Il,concat4d:()=>Tl,conv1d:()=>Al,conv2d:()=>ve,conv2dTranspose:()=>Nl,conv3d:()=>Rl,conv3dTranspose:()=>Cl,cos:()=>_n,cosh:()=>ns,cosineWindow:()=>kr,cumsum:()=>rs,depthToSpace:()=>El,depthwiseConv2d:()=>Dn,diag:()=>Ol,dilation2d:()=>kl,div:()=>U,divNoNan:()=>_l,divStrict:()=>Md,dot:()=>Dl,dropout:()=>Qd,elu:()=>is,enclosingPowerOfTwo:()=>xa,equal:()=>Xt,equalStrict:()=>Cd,erf:()=>Fl,exp:()=>Oe,expandDims:()=>et,expm1:()=>Ml,eye:()=>ss,fft:()=>Fn,fill:()=>Ge,floor:()=>Mn,floorDiv:()=>os,fused:()=>Dh,gather:()=>Un,gatherND:()=>Xd,greater:()=>tt,greaterEqual:()=>ut,greaterEqualStrict:()=>Ed,greaterStrict:()=>Od,ifft:()=>dn,imag:()=>Qt,image:()=>Ra,inTopKAsync:()=>em,irfft:()=>as,isFinite:()=>Wl,isInf:()=>Bl,isNaN:()=>$l,leakyRelu:()=>Gl,less:()=>Wn,lessEqual:()=>dt,lessEqualStrict:()=>kd,lessStrict:()=>_d,linalg:()=>Em,linspace:()=>jl,localResponseNormalization:()=>Pl,log:()=>wt,log1p:()=>cs,logSigmoid:()=>Hl,logSoftmax:()=>zl,logSumExp:()=>ls,logicalAnd:()=>yt,logicalNot:()=>Bn,logicalOr:()=>hs,logicalXor:()=>Yl,losses:()=>Om,matMul:()=>Y,max:()=>mt,maxPool:()=>Ie,maxPool3d:()=>Vl,maxPoolWithArgmax:()=>Kl,maximum:()=>Ct,maximumStrict:()=>Ud,mean:()=>mn,min:()=>fn,minimum:()=>$n,minimumStrict:()=>Wd,mod:()=>us,modStrict:()=>Bd,moments:()=>Jl,movingAverage:()=>Hd,mul:()=>S,mulStrict:()=>$d,multiRNNCell:()=>Xl,multinomial:()=>Zl,neg:()=>re,norm:()=>Or,notEqual:()=>Gn,notEqualStrict:()=>Dd,oneHot:()=>Cr,ones:()=>xt,onesLike:()=>ga,op:()=>d,outerProduct:()=>Ql,pad:()=>je,pad1d:()=>eh,pad2d:()=>th,pad3d:()=>nh,pad4d:()=>rh,pool:()=>oh,pow:()=>Xe,powStrict:()=>Gd,prelu:()=>ds,print:()=>ih,prod:()=>sh,rand:()=>ah,randomGamma:()=>hh,randomNormal:()=>uh,randomUniform:()=>fs,range:()=>Er,real:()=>Gt,reciprocal:()=>dh,relu:()=>se,relu6:()=>gs,reshape:()=>x,reverse:()=>Ke,reverse1d:()=>mh,reverse2d:()=>fh,reverse3d:()=>gh,reverse4d:()=>bh,rfft:()=>Pn,round:()=>yh,rsqrt:()=>bs,scalar:()=>k,scatterND:()=>Vd,selu:()=>xh,separableConv2d:()=>qn,setdiff1dAsync:()=>Lh,sigmoid:()=>Nt,sign:()=>Sh,signal:()=>Cm,sin:()=>ws,sinh:()=>ys,slice:()=>V,slice1d:()=>vh,slice2d:()=>Ih,slice3d:()=>xs,slice4d:()=>Th,softmax:()=>en,softplus:()=>ps,spaceToBatchND:()=>jn,sparseToDense:()=>Jd,spectral:()=>Rm,split:()=>jt,sqrt:()=>de,square:()=>H,squaredDifference:()=>Hn,squaredDifferenceStrict:()=>jd,squeeze:()=>zn,stack:()=>Ue,step:()=>Et,stridedSlice:()=>Ah,sub:()=>_,subStrict:()=>Pd,sum:()=>W,tan:()=>Nh,tanh:()=>Ar,tensor:()=>Ye,tensor1d:()=>ge,tensor2d:()=>ft,tensor3d:()=>Ls,tensor4d:()=>Pt,tensor5d:()=>Rh,tensor6d:()=>Ch,tile:()=>Zt,topk:()=>Eh,transpose:()=>Z,truncatedNormal:()=>Oh,unsortedSegmentSum:()=>Ss,unstack:()=>We,variable:()=>kh,where:()=>Ee,whereAsync:()=>vs,zeros:()=>Re,zerosLike:()=>B});const Rm={fft:Fn,ifft:dn,rfft:Pn,irfft:as},Cm={hammingWindow:tm,hannWindow:va,frame:Ia,stft:nm},Ra={flipLeftRight:om,resizeNearestNeighbor:fm,resizeBilinear:mm,rotateWithOffset:im,cropAndResize:rm,nonMaxSuppression:sm,nonMaxSuppressionAsync:pm,nonMaxSuppressionWithScore:lm,nonMaxSuppressionWithScoreAsync:hm,nonMaxSuppressionPadded:um,nonMaxSuppressionPaddedAsync:dm},Em={bandPart:gm,gramSchmidt:bm,qr:ym},Om={absoluteDifference:xm,computeWeightedLoss:Be,cosineDistance:Lm,hingeLoss:Sm,huberLoss:vm,logLoss:Im,meanSquaredError:Tm,sigmoidCrossEntropy:Am,softmaxCrossEntropy:Nm};ld(Mh);const Is={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};const Ca=4;async function lI(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 m=await c.bytes(),b=m.reduce((L,v)=>L+v.length,0)+Ca*m.length,y=new Uint8Array(b);let w=0;for(let L=0;L<m.length;L++){const v=m[L],A=new Uint8Array(new Uint32Array([v.length]).buffer);y.set(A,w),w+=Ca,y.set(v,w),w+=v.length}h(y)});r.push(l)}else r.push(c.data());t!=null&&(p.group=t),n.push(p)}const i=await Promise.all(r);return{data:pI(i),specs:n}}function Uh(e,t){const n={};let r,o=0;for(const i of t){const a=i.name,s=i.dtype,c=i.shape,p=te(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 m=Is[h.dtype],b=e.slice(o,o+p*m),y=h.dtype==="uint8"?new Uint8Array(b):new Uint16Array(b);if(s==="float32")if(h.dtype==="uint8"||h.dtype==="uint16"){l=new Float32Array(y.length);for(let w=0;w<y.length;w++){const L=y[w];l[w]=L*h.scale+h.min}}else if(h.dtype==="float16")r===void 0&&(r=hI()),l=r(y);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(y.length);for(let w=0;w<y.length;w++){const L=y[w];l[w]=Math.round(L*h.scale+h.min)}}else throw new Error(`Unsupported dtype in weight '${a}': ${s}`);o+=p*m}else if(s==="string"){const h=te(i.shape);l=[];for(let m=0;m<h;m++){const b=new Uint32Array(e.slice(o,o+Ca))[0];o+=Ca;const y=new Uint8Array(e.slice(o,o+b));l.push(y),o+=b}}else{const h=Is[s],m=e.slice(o,o+p*h);if(s==="float32")l=new Float32Array(m);else if(s==="int32")l=new Int32Array(m);else if(s==="bool")l=new Uint8Array(m);else if(s==="complex64"){l=new Float32Array(m);const b=new Float32Array(l.length/2),y=new Float32Array(l.length/2);for(let v=0;v<b.length;v++)b[v]=l[v*2],y[v]=l[v*2+1];const w=Ye(b,c,"float32"),L=Ye(y,c,"float32");n[a]=Ve(w,L)}else throw new Error(`Unsupported dtype in weight '${a}': ${s}`);o+=p*h}s!=="complex64"&&(n[a]=Ye(l,c,s))}return n}function pI(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 uI=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function km(e){return uI?Buffer.byteLength(e):new Blob([e]).size}function Ts(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 Wh(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:km(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:km(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:e.weightData.byteLength}}function dI(){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 mI(){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 fI(){const e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function hI(){const e=dI(),t=mI(),n=fI();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 Te{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return Te.instance==null&&(Te.instance=new Te()),Te.instance}static registerSaveRouter(e){Te.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Te.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Te.getHandlers(e,"save")}static getLoadHandlers(e,t){return Te.getHandlers(e,"load",t)}static getHandlers(e,t,n){const r=[],o=t==="load"?Te.getInstance().loadRouters:Te.getInstance().saveRouters;return o.forEach(i=>{const a=i(e,n);a!==null&&r.push(a)}),r}}const gI=e=>Te.registerSaveRouter(e),bI=e=>Te.registerLoadRouter(e),wI=e=>Te.getSaveHandlers(e),yI=(e,t)=>Te.getLoadHandlers(e,t);const Dr="://";class Ot{constructor(){this.managers={}}static getInstance(){return Ot.instance==null&&(Ot.instance=new Ot()),Ot.instance}static registerManager(e,t){f(e!=null,()=>"scheme must not be undefined or null."),e.endsWith(Dr)&&(e=e.slice(0,e.indexOf(Dr))),f(e.length>0,()=>"scheme must not be an empty string.");const n=Ot.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 Ea(e){if(e.indexOf(Dr)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Ot.getSchemes().join(",")}`);return{scheme:e.split(Dr)[0],path:e.split(Dr)[1]}}async function _m(e,t,n=!1){f(e!==t,()=>`Old path and new path are the same: '${e}'`);const r=Te.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=Te.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=Ea(e).scheme,c=Ea(e).path,p=s===Ea(e).scheme,l=await o.load();n&&p&&await Ot.getManager(s).removeModel(c);const h=await a.save(l);return n&&!p&&await Ot.getManager(s).removeModel(c),h.modelArtifactsInfo}async function Dm(){const e=Ot.getSchemes(),t={};for(const n of e){const r=await Ot.getManager(n).listModels();for(const o in r){const i=n+Dr+o;t[i]=r[o]}}return t}async function Fm(e){const t=Ea(e),n=Ot.getManager(t.scheme);return n.removeModel(t.path)}async function Mm(e,t){const n=!1;return _m(e,t,n)}async function Um(e,t){const n=!0;return _m(e,t,n)}const xI="model",LI=".json",SI=".weights.bin";function Wm(e){return new Promise(t=>setTimeout(t)).then(e)}class Fr{constructor(e){if(!ce().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(Fr.URL_SCHEME)&&(e=e.slice(Fr.URL_SCHEME.length)),(e==null||e.length===0)&&(e=xI),this.modelTopologyFileName=e+LI,this.weightDataFileName=e+SI}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 Wm(()=>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 Wm(()=>a.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:As(e)}}}}Fr.URL_SCHEME="downloads://";class vI{constructor(e){if(e==null||e.length<1)throw new Error(`When calling browserFiles, at least 1 file is required, but received ${e}`);this.files=e}async load(){const e=this.files[0],t=this.files.slice(1);return new Promise((n,r)=>{const o=new FileReader();o.onload=i=>{const a=JSON.parse(i.target.result),s=a.modelTopology;if(s==null){r(new Error(`modelTopology field is missing from file ${e.name}`));return}t.length===0&&n({modelTopology:s});const c=a.weightsManifest;if(c==null){r(new Error(`weightManifest field is missing from file ${e.name}`));return}let p;try{p=this.checkManifestAndWeightFiles(c,t)}catch(b){r(b);return}const l=[],h=[],m=[];c.forEach(b=>{b.paths.forEach(y=>{h.push(y),m.push(null)}),l.push(...b.weights)}),c.forEach(b=>{b.paths.forEach(y=>{const w=new FileReader();w.onload=L=>{const v=L.target.result,A=h.indexOf(y);m[A]=v,m.indexOf(null)===-1&&n({modelTopology:s,weightSpecs:l,weightData:Ts(m),format:a.format,generatedBy:a.generatedBy,convertedBy:a.convertedBy,userDefinedMetadata:a.userDefinedMetadata})},w.onerror=L=>r(`Failed to weights data from file of path '${y}'.`),w.readAsArrayBuffer(p[y])})})},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=>Wh(i.name)),o={};for(const i of e)i.paths.forEach(a=>{const s=Wh(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 TI=e=>ce().getBool("IS_BROWSER")&&(!Array.isArray(e)&&e.startsWith(Fr.URL_SCHEME))?II(e.slice(Fr.URL_SCHEME.length)):null;Te.registerSaveRouter(TI);function II(e="model"){return new Fr(e)}function AI(e){return new vI(e)}function Bh(e,t,n,r){a(e),n=n??0,r=r??1,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 $h(e,t){t==null&&(t={});const n=t.fetchFunc==null?ce().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 Bh(r,t.onProgress,o,i),s=a.map(h=>h.arrayBuffer()),c=.5,p=1,l=t.onProgress==null?await Promise.all(s):await Bh(s,t.onProgress,c,p);return l}async function NI(e,t="",n,r){const o=a=>$h(a,{requestInit:r}),i=Bm(o);return i(e,t,n)}function Bm(e){return async(t,n="",r)=>{const o=t.map(()=>!1),i={},a=r!=null?r.map(()=>!1):[],s=[];if(t.forEach((b,y)=>{let w=0;b.weights.forEach(L=>{const v="quantization"in L?L.quantization.dtype:L.dtype,A=Is[v]*te(L.shape),R=()=>{o[y]=!0,i[y]==null&&(i[y]=[]),i[y].push({manifestEntry:L,groupOffset:w,sizeBytes:A})};r!=null?r.forEach((N,O)=>{N===L.name&&(R(),a[O]=!0)}):R(),s.push(L.name),w+=A})}),!a.every(b=>b)){const b=r.filter((y,w)=>!a[w]);throw new Error(`Could not find weights in manifest with names: ${b.join(", ")}.
Manifest JSON has weights with names: ${s.join(", ")}.`)}const c=o.reduce((b,y,w)=>(y&&b.push(w),b),[]),p=[];c.forEach(b=>{t[b].paths.forEach(y=>{const w=n+(n.endsWith("/")?"":"/")+y;p.push(w)})});const l=await e(p),h={};let m=0;return c.forEach(b=>{const y=t[b].paths.length;let w=0;for(let N=0;N<y;N++)w+=l[m+N].byteLength;const L=new ArrayBuffer(w),v=new Uint8Array(L);let A=0;for(let N=0;N<y;N++){const O=new Uint8Array(l[m+N]);v.set(O,A),A+=O.byteLength}const R=i[b];R.forEach(N=>{const O=L.slice(N.groupOffset,N.groupOffset+N.sizeBytes),M=Uh(O,[N.manifestEntry]);for(const D in M)h[D]=M[D]}),m+=y}),h}}const RI="application/octet-stream",CI="application/json";class Gh{constructor(e,t){if(this.DEFAULT_METHOD="POST",t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,t.fetchFunc!=null?(f(typeof t.fetchFunc=="function",()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"),this.fetch=t.fetchFunc):this.fetch=ce().platform.fetch,f(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&f(e.length===2,()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`),this.path=e,t.requestInit!=null&&t.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");const t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData();const n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],r={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,userDefinedMetadata:e.userDefinedMetadata,weightsManifest:n};t.body.append("model.json",new Blob([JSON.stringify(r)],{type:CI}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:RI}),"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]=EI(t),o=this.weightPathPrefix||n,i=[];for(const c of e)i.push(...c.weights);const a=[];e.forEach(c=>{c.paths.forEach(p=>{a.push(o+p+r)})});const s=await $h(a,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[i,Ts(s)]}}Gh.URL_SCHEME_REGEX=/^https?:\/\//;function EI(e){const t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),r=e.substring(0,t),o=n>t?e.substring(n):"";return[r+"/",o]}function jh(e){return e.match(Gh.URL_SCHEME_REGEX)!=null}const $m=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let n=!0;if(Array.isArray(e)?n=e.every(r=>jh(r)):n=jh(e),n)return Ph(e,t)}return null};Te.registerSaveRouter($m);Te.registerLoadRouter($m);function Ph(e,t){return new Gh(e,t)}function OI(e,t){return Ph(e,t)}class qh{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}}class kI{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}}function _I(e,t,n,r){if(arguments.length===1){const o=e.modelTopology!=null||e.weightSpecs!=null;return o?new qh(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 qh({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 qh({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:r})}function DI(e){return new kI(e)}const Mr={};me(Mr,{browserFiles:()=>AI,browserHTTPRequest:()=>OI,concatenateArrayBuffers:()=>Ts,copyModel:()=>Mm,decodeWeights:()=>Uh,encodeWeights:()=>lI,fromMemory:()=>_I,getLoadHandlers:()=>yI,getModelArtifactsInfoForJSON:()=>As,getSaveHandlers:()=>wI,http:()=>Ph,isHTTPScheme:()=>jh,listModels:()=>Dm,loadWeights:()=>NI,moveModel:()=>Um,registerLoadRouter:()=>bI,registerSaveRouter:()=>gI,removeModel:()=>Fm,weightsLoaderFactory:()=>Bm,withSaveHandler:()=>DI});function FI(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=Cr(E(r,"int32"),n),a=Cr(E(o,"int32"),n),s=Z(i);return E(Y(s,a),"int32")}const MI=d({confusionMatrix_:FI});const Gm={};me(Gm,{confusionMatrix:()=>MI});const Ur={};me(Ur,{fromPixels:()=>BI,toPixels:()=>WI});let Wr;function UI(e,t=3){if(t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(e==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let n=!1,r=!1,o=!1,i=!1,a=!1;if(e.data instanceof Uint8Array)n=!0;else if(typeof ImageData!="undefined"&&e instanceof ImageData)r=!0;else if(typeof HTMLVideoElement!="undefined"&&e instanceof HTMLVideoElement)o=!0;else if(typeof HTMLImageElement!="undefined"&&e instanceof HTMLImageElement)i=!0;else if(e.getContext!=null)a=!0;else throw new Error(`pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was ${e.constructor.name}`);if(o){const b=2;if(o&&e.readyState<b)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.")}const s=Hi(na,g.backendName);if(s!=null){const b={pixels:e},y={numChannels:t};return g.runKernel(na,b,y)}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)&&(Wr==null&&(Wr=document.createElement("canvas").getContext("2d")),Wr.canvas.width=c,Wr.canvas.height=p,Wr.drawImage(e,0,0,c,p),l=Wr.getImageData(0,0,c,p).data);let h;if(t===4)h=new Int32Array(l);else{const b=c*p;h=new Int32Array(b*t);for(let y=0;y<b;y++)for(let w=0;w<t;++w)h[y*t+w]=l[y*4+w]}const m=[p,c,t];return Ls(h,m,"int32")}async function WI(e,t){let n=u(e,"img","toPixels");if(!(e instanceof ne)){const L=n;n=E(L,"int32"),L.dispose()}if(n.rank!==2&&n.rank!==3)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${n.rank}.`);const[r,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}`);const a=await n.data(),s=fn(n),c=mt(n),p=await Promise.all([s.data(),c.data()]),l=p[0],h=p[1],m=l[0],b=h[0];if(s.dispose(),c.dispose(),n.dtype==="float32"){if(m<0||b>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but got range [${m} - ${b}].`)}else if(n.dtype==="int32"){if(m<0||b>255)throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but got range [${m} - ${b}].`)}else throw new Error(`Unsupported type for toPixels: ${n.dtype}. Please use float32 or int32 tensors.`);const y=n.dtype==="float32"?255:1,w=new Uint8ClampedArray(o*r*4);for(let L=0;L<r*o;++L){let v,A,R,N;i===1?(v=a[L]*y,A=a[L]*y,R=a[L]*y,N=255):i===3?(v=a[L*3]*y,A=a[L*3+1]*y,R=a[L*3+2]*y,N=255):i===4&&(v=a[L*4]*y,A=a[L*4+1]*y,R=a[L*4+2]*y,N=a[L*4+3]*y);const O=L*4;w[O+0]=Math.round(v),w[O+1]=Math.round(A),w[O+2]=Math.round(R),w[O+3]=Math.round(N)}if(t!=null){t.width=o,t.height=r;const L=t.getContext("2d"),v=new ImageData(w,o,r);L.putImageData(v,0,0)}return n!==e&&n.dispose(),w}const BI=d({fromPixels_:UI});const jm={};me(jm,{prepareAndValidate:()=>Pm});function Pm(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 qm={};me(qm,{Serializable:()=>Hh,SerializationMap:()=>Xn,registerClass:()=>nt});class Hh{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}}class Xn{constructor(){this.classNameMap={}}static getMap(){return Xn.instance==null&&(Xn.instance=new Xn()),Xn.instance}static register(e){Xn.getMap().classNameMap[e.className]=[e,e.fromConfig]}}function nt(e){f(e.className!=null,()=>"Class being registered does not have the static className property defined."),f(typeof e.className=="string",()=>"className is required to be a string, but got type "+typeof e.className),f(e.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),Xn.register(e)}const $I="2.3.0";class it extends Hh{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 ql(e,t)}dispose(){this.iterations_!=null&&Le(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:k(this.iterations_,"int32")}}async getWeights(){throw new Error("getWeights() is not implemented for this optimizer yet.")}async setWeights(e){throw new Error(`setWeights() is not implemented for this optimizer class ${this.getClassName()}`)}async extractIterations(e){return this.iterations_=(await e[0].tensor.data())[0],e.slice(1)}}Object.defineProperty(it,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});class Zn extends it{constructor(e,t,n=null){super();this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],n==null&&(this.epsilon=g.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);t.forEach((n,r)=>{const o=g.registeredVariables[n],i=!1;this.accumulatedGrads[r]==null&&(this.accumulatedGrads[r]={originalName:`${n}/accum_grad`,variable:F(()=>B(o).variable(i))}),this.accumulatedUpdates[r]==null&&(this.accumulatedUpdates[r]={originalName:`${n}/accum_var`,variable:F(()=>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;F(()=>{const p=C(S(s,this.rho),S(H(a),1-this.rho)),l=S(U(de(C(c,this.epsilon)),de(C(s,this.epsilon))),a),h=C(S(c,this.rho),S(H(l),1-this.rho));s.assign(p),c.assign(h);const m=C(S(l,-this.learningRate),o);o.assign(m)})}),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)}}Zn.className="Adadelta";nt(Zn);class Qn extends it{constructor(e,t=.1){super();this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);t.forEach((n,r)=>{const o=g.registeredVariables[n];if(this.accumulatedGrads[r]==null){const s=!1;this.accumulatedGrads[r]={originalName:`${n}/accumulator`,variable:F(()=>Ge(o.shape,this.initialAccumulatorValue).variable(s))}}const i=Array.isArray(e)?e[r].tensor:e[n];if(i==null)return;const a=this.accumulatedGrads[r].variable;F(()=>{const s=C(a,H(i));a.assign(s);const c=C(S(U(i,de(C(s,g.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";nt(Qn);class er extends it{constructor(e,t,n,r=null){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=r,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],F(()=>{this.accBeta1=k(t).variable(),this.accBeta2=k(n).variable()}),r==null&&(this.epsilon=g.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);F(()=>{const n=_(1,this.accBeta1),r=_(1,this.accBeta2);t.forEach((o,i)=>{const a=g.registeredVariables[o],s=!1;this.accumulatedFirstMoment[i]==null&&(this.accumulatedFirstMoment[i]={originalName:`${o}/m`,variable:F(()=>B(a).variable(s))}),this.accumulatedSecondMoment[i]==null&&(this.accumulatedSecondMoment[i]={originalName:`${o}/v`,variable:F(()=>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=C(S(p,this.beta1),S(c,1-this.beta1)),m=C(S(l,this.beta2),S(H(c),1-this.beta2)),b=U(h,n),y=U(m,r);p.assign(h),l.assign(m);const w=C(S(U(b,C(de(y),this.epsilon)),-this.learningRate),a);a.assign(w)}),this.accBeta1.assign(S(this.accBeta1,this.beta1)),this.accBeta2.assign(S(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),F(()=>{this.accBeta1.assign(Xe(this.beta1,this.iterations_+1)),this.accBeta2.assign(Xe(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)}}er.className="Adam";nt(er);class tr extends it{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=[],F(()=>{this.iteration=k(0).variable(),this.accBeta1=k(t).variable()}),r==null&&(this.epsilon=g.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);F(()=>{const n=_(1,this.accBeta1),r=U(-this.learningRate,C(S(this.iteration,this.decay),1));t.forEach((o,i)=>{const a=g.registeredVariables[o],s=!1;this.accumulatedFirstMoment[i]==null&&(this.accumulatedFirstMoment[i]={originalName:`${o}/m`,variable: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=C(S(p,this.beta1),S(c,1-this.beta1)),m=S(l,this.beta2),b=Ce(c),y=Ct(m,b);p.assign(h),l.assign(y);const w=C(S(U(r,n),U(h,C(y,this.epsilon))),a);a.assign(w)}),this.iteration.assign(C(this.iteration,1)),this.accBeta1.assign(S(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)}}tr.className="Adamax";nt(tr);class tn extends it{constructor(e){super();this.learningRate=e,this.setLearningRate(e)}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);t.forEach((n,r)=>{const o=Array.isArray(e)?e[r].tensor:e[n];if(o==null)return;const i=g.registeredVariables[n];F(()=>{const a=C(S(this.c,o),i);i.assign(a)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=ol(k(-e))}dispose(){this.c.dispose()}async getWeights(){return[await this.saveIterations()]}async setWeights(e){if(e=await this.extractIterations(e),e.length!==0)throw new Error("SGD optimizer does not have settable weights.")}getConfig(){return{learningRate:this.learningRate}}static fromConfig(e,t){return new e(t.learningRate)}}tn.className="SGD";nt(tn);class nr extends tn{constructor(e,t,n=!1){super(e);this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=k(this.momentum)}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);t.forEach((n,r)=>{const o=g.registeredVariables[n];if(this.accumulations[r]==null){const s=!1;this.accumulations[r]={originalName:`${n}/momentum`,variable:F(()=>B(o).variable(s))}}const i=this.accumulations[r].variable,a=Array.isArray(e)?e[r].tensor:e[n];if(a==null)return;F(()=>{let s;const c=C(S(this.m,i),a);this.useNesterov?s=C(S(this.c,C(a,S(c,this.m))),o):s=C(S(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)}}nr.className="Momentum";nt(nr);class rr extends it{constructor(e,t=.9,n=0,r=null,o=!1){super();if(this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=r,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=o,r==null&&(this.epsilon=g.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);t.forEach((n,r)=>{const o=g.registeredVariables[n],i=!1;this.accumulatedMeanSquares[r]==null&&(this.accumulatedMeanSquares[r]={originalName:`${n}/rms`,variable:F(()=>B(o).variable(i))}),this.accumulatedMoments[r]==null&&(this.accumulatedMoments[r]={originalName:`${n}/momentum`,variable:F(()=>B(o).variable(i))}),this.accumulatedMeanGrads[r]==null&&this.centered&&(this.accumulatedMeanGrads[r]={originalName:`${n}/mg`,variable:F(()=>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;F(()=>{const p=C(S(s,this.decay),S(H(a),1-this.decay));if(this.centered){const l=this.accumulatedMeanGrads[r].variable,h=C(S(l,this.decay),S(a,1-this.decay)),m=U(S(a,this.learningRate),de(_(p,C(H(h),this.epsilon)))),b=C(S(c,this.momentum),m);s.assign(p),l.assign(h),c.assign(b);const y=_(o,b);o.assign(y)}else{const l=C(S(s,this.decay),S(H(a),1-this.decay)),h=C(S(c,this.momentum),U(S(a,this.learningRate),de(C(l,this.epsilon))));s.assign(l),c.assign(h);const m=_(o,h);o.assign(m)}})}),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)}}rr.className="RMSProp";nt(rr);class gn{static sgd(e){return new tn(e)}static momentum(e,t,n=!1){return new nr(e,t,n)}static rmsprop(e,t=.9,n=0,r=null,o=!1){return new rr(e,t,n,r,o)}static adam(e=.001,t=.9,n=.999,r=null){return new er(e,t,n,r)}static adadelta(e=.001,t=.95,n=null){return new Zn(e,t,n)}static adamax(e=.002,t=.9,n=.999,r=null,o=0){return new tr(e,t,n,r,o)}static adagrad(e,t=.1){return new Qn(e,t)}}nr,tn,Zn,Qn,rr,tr,er;const GI={sgd:gn.sgd,momentum:gn.momentum,adadelta:gn.adadelta,adagrad:gn.adagrad,rmsprop:gn.rmsprop,adamax:gn.adamax,adam:gn.adam};const jI=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:e=>e())();function PI(){return new Promise(e=>jI(()=>e()))}function qI(e,t,n){const r=n*(typeof e=="number"?e:e[0]),o=t*(typeof e=="number"?e:e[1]);return[r,o]}function HI(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 zI(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 YI(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 VI(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 zh=1.7580993408473768,Yh=1.0507009873554805;const JI=.3275911,XI=.254829592,ZI=-.284496736,QI=1.421413741,eT=-1.453152027,tT=1.061405429;function nT(...e){ce().getBool("IS_TEST")||console.warn(...e)}function rT(...e){ce().getBool("IS_TEST")||console.log(...e)}function oT(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 iT(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 sT(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 aT(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 cT(e,t){const n=e[t*2],r=e[t*2+1];return{real:n,imag:r}}function pT(e,t,n,r){e[r*2]=t,e[r*2+1]=n}function lT(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 hT(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 Hm={};me(Hm,{ERF_A1:()=>XI,ERF_A2:()=>ZI,ERF_A3:()=>QI,ERF_A4:()=>eT,ERF_A5:()=>tT,ERF_P:()=>JI,PARALLELIZE_THRESHOLD:()=>ma,SELU_SCALE:()=>Yh,SELU_SCALEALPHA:()=>zh,applyActivation:()=>Kn,assertAndGetBroadcastShape:()=>q,assertAxesAreInnerMostDims:()=>dy,assertParamsConsistent:()=>sl,assignToTypedArray:()=>pT,axesAreInnerMostDims:()=>Hp,calculateShapes:()=>Yd,castTensor:()=>uT,combineLocations:()=>wd,complexWithEvenIndex:()=>sT,complexWithOddIndex:()=>aT,computeConv2DInfo:()=>$e,computeConv3DInfo:()=>un,computeDefaultPad:()=>rl,computeDilation2DInfo:()=>Ay,computeOptimalWindowSize:()=>Jx,computeOutAndReduceShapes:()=>zp,computeOutShape:()=>al,computePool2DInfo:()=>At,computePool3DInfo:()=>Kt,convertConv2DDataFormat:()=>hn,eitherStridesOrDilationsAreOne:()=>pe,expandShapeToKeepDim:()=>we,exponent:()=>hT,exponents:()=>lT,getAxesPermutation:()=>fe,getBroadcastDims:()=>Fx,getComplexWithIndex:()=>cT,getFusedBiasGradient:()=>Vn,getFusedDyActivation:()=>Yn,getImageCenter:()=>qI,getInnerMostAxes:()=>De,getPermuted:()=>zI,getReductionAxes:()=>ae,getReshaped:()=>HI,getReshapedPermuted:()=>YI,getSliceBeginCoords:()=>VI,getSliceSize:()=>KI,getUndoAxesPermutation:()=>En,linspaceImpl:()=>mT,log:()=>rT,mergeRealAndImagArrays:()=>oT,prepareAndValidate:()=>Pm,prepareSplitSize:()=>wh,reshapeTensor:()=>dT,segment_util:()=>vd,shouldFuse:()=>Jn,splitRealAndImagArrays:()=>iT,tupleValuesAreOne:()=>lt,upcastType:()=>Ir,validateInput:()=>ya,validateUpdateShape:()=>_h,warn:()=>nT});function uT(e,t,n){if(t==="complex64"){if(e.dtype==="complex64")return e.clone();const r=Re(e.shape),o=E(e,"float32"),i=n.complex(o,r);return r.dispose(),o.dispose(),i}if(!Ep(e.dtype,t))return g.makeTensorFromDataId(e.dataId,e.shape,t);if(e.dtype==="complex64"){const r=n.real(e),o=E(r,t);return r.dispose(),o}if(t==="int32")return n.int(e);if(t==="bool"){const r=k(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 dT(e,t){return g.makeTensorFromDataId(e.dataId,t,e.dtype)}function mT(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 ge(o,"float32")}function zm(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=V(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=Me(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=yr(n,a*r),p=yr("int32",a*r);for(let h=0;h<a;h++){const m=h*s,b=e.subarray(m,m+s),y=[];for(let A=0;A<b.length;A++)y.push({value:b[A],index:A});y.sort((A,R)=>R.value-A.value);const w=h*r,L=c.subarray(w,w+r),v=p.subarray(w,w+r);for(let A=0;A<r;A++)L[A]=y[A].value,v[A]=y[A].index}const l=t.slice();return l[l.length-1]=r,[Ye(c,l,n),Ye(p,l,"int32")]}const Km={};me(Km,{nonMaxSuppressionV3Impl:()=>Ta,nonMaxSuppressionV4Impl:()=>Aa,nonMaxSuppressionV5Impl:()=>Na,split:()=>zm,tile:()=>Ym,topkImpl:()=>Vm,whereImpl:()=>wa});const fT=1e-7,gT=1e-4;class bT{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 wT{time(e){return I("time")}read(e){return I("read")}readSync(e){return I("readSync")}numDataIds(){return I("numDataIds")}disposeData(e){return I("disposeData")}write(e,t,n){return I("write")}move(e,t,n,r){return I("move")}memory(){return I("memory")}floatPrecision(){return I("floatPrecision")}epsilon(){return this.floatPrecision()===32?fT:gT}batchMatMul(e,t,n,r){return I("batchMatMul")}fusedBatchMatMul({a:e,b:t,transposeA:n,transposeB:r,bias:o,activation:i,preluActivationWeights:a}){return I("fusedBatchMatMul")}slice(e,t,n){return I("slice")}stridedSlice(e,t,n,r){return I("stridedSlice")}unstack(e,t){return I("unstack")}reverse(e,t){return I("reverse")}concat(e,t){return I("concat")}neg(e){return I("neg")}add(e,t){return I("add")}addN(e){return I("addN")}subtract(e,t){return I("subtract")}multiply(e,t){return I("multiply")}realDivide(e,t){return I("realDivide")}floorDiv(e,t){return I("floorDiv")}sum(e,t){return I("sum")}prod(e,t){return I("prod")}unsortedSegmentSum(e,t,n){return I("unsortedSegmentSum")}argMin(e,t){return I("argMin")}argMax(e,t){return I("argMax")}equal(e,t){return I("equal")}notEqual(e,t){return I("notEqual")}less(e,t){return I("less")}lessEqual(e,t){return I("lessEqual")}greater(e,t){return I("greater")}greaterEqual(e,t){return I("greaterEqual")}logicalNot(e){return I("logicalNot")}logicalAnd(e,t){return I("logicalAnd")}logicalOr(e,t){return I("logicalOr")}where(e){return I("where")}select(e,t,n){return I("select")}topk(e,t,n){return I("topk")}min(e,t){return I("min")}minimum(e,t){return I("minimum")}mod(e,t){return I("mod")}max(e,t){return I("max")}maximum(e,t){return I("maximum")}all(e,t){return I("all")}any(e,t){return I("any")}squaredDifference(e,t){return I("squaredDifference")}ceil(e){return I("ceil")}floor(e){return I("floor")}round(e){return I("round")}sign(e){return I("sign")}isNaN(e){return I("isNaN")}isInf(e){return I("isInf")}isFinite(e){return I("isFinite")}pow(e,t){return I("pow")}exp(e){return I("exp")}expm1(e){return I("expm1")}softmax(e,t){return I("softmax")}log(e){return I("log")}log1p(e){return I("log1p")}sqrt(e){return I("sqrt")}rsqrt(e){return I("rsqrt")}square(e){return I("square")}reciprocal(e){return I("reciprocal")}relu(e){return I("relu")}relu6(e){return I("relu6")}prelu(e,t){return I("prelu")}elu(e){return I("elu")}eluDer(e,t){return I("eluDer")}selu(e){return I("selu")}int(e){return I("int")}clip(e,t,n){return I("clip")}abs(e){return I("abs")}complexAbs(e){return I("complexAbs")}sigmoid(e){return I("sigmoid")}softplus(e){return I("softplus")}sin(e){return I("sin")}cos(e){return I("cos")}tan(e){return I("tan")}asin(e){return I("asin")}acos(e){return I("acos")}atan(e){return I("atan")}atan2(e,t){return I("atan2")}sinh(e){return I("sinh")}cosh(e){return I("cosh")}tanh(e){return I("tanh")}asinh(e){return I("asinh")}acosh(e){return I("acosh")}atanh(e){return I("atanh")}erf(e){return I("erf")}step(e,t){return I("step")}fusedConv2d({input:e,filter:t,convInfo:n,bias:r,activation:o,preluActivationWeights:i}){return I("fusedConv2d")}conv2d(e,t,n){return I("conv2d")}conv2dDerInput(e,t,n){return I("conv2dDerInput")}conv2dDerFilter(e,t,n){return I("conv2dDerFilter")}fusedDepthwiseConv2D({input:e,filter:t,convInfo:n,bias:r,activation:o,preluActivationWeights:i}){return I("fusedDepthwiseConv2D")}depthwiseConv2D(e,t,n){return I("depthwiseConv2D")}depthwiseConv2DDerInput(e,t,n){return I("depthwiseConv2DDerInput")}depthwiseConv2DDerFilter(e,t,n){return I("depthwiseConv2DDerFilter")}conv3d(e,t,n){return I("conv3d")}conv3dDerInput(e,t,n){return I("conv3dDerInput")}conv3dDerFilter(e,t,n){return I("conv3dDerFilter")}maxPool(e,t){return I("maxPool")}maxPoolBackprop(e,t,n,r){return I("maxPoolBackprop")}avgPool(e,t){return I("avgPool")}avgPoolBackprop(e,t,n){return I("avgPoolBackprop")}avgPool3d(e,t){return I("avgPool3d")}avgPool3dBackprop(e,t,n){return I("avgPool3dBackprop")}maxPool3d(e,t){return I("maxPool3d")}maxPool3dBackprop(e,t,n,r){return I("maxPool3dBackprop")}reshape(e,t){return I("reshape")}cast(e,t){return I("cast")}tile(e,t){return I("tile")}pad(e,t,n){return I("pad")}transpose(e,t){return I("transpose")}gather(e,t,n){return I("gather")}gatherND(e,t){return I("gatherND")}scatterND(e,t,n){return I("scatterND")}batchToSpaceND(e,t,n){return I("batchToSpaceND")}spaceToBatchND(e,t,n){return I("spaceToBatchND")}resizeBilinear(e,t,n,r){return I("resizeBilinear")}resizeBilinearBackprop(e,t,n){return I("resizeBilinearBackprop")}resizeNearestNeighbor(e,t,n,r){return I("resizeNearestNeighbor")}resizeNearestNeighborBackprop(e,t,n){return I("resizeNearestNeighborBackprop")}batchNorm(e,t,n,r,o,i){return I("batchNorm")}localResponseNormalization4D(e,t,n,r,o){return I("localResponseNormalization4D")}LRNGrad(e,t,n,r,o,i,a){return I("LRNGrad")}multinomial(e,t,n,r){return I("multinomial")}oneHot(e,t,n,r){return I("oneHot")}cumsum(e,t,n,r){return I("cumsum")}nonMaxSuppression(e,t,n,r,o){return I("nonMaxSuppression")}fft(e){return I("fft")}ifft(e){return I("ifft")}complex(e,t){return I("complex")}real(e){return I("real")}imag(e){return I("imag")}cropAndResize(e,t,n,r,o,i){return I("cropAndResize")}depthToSpace(e,t,n){return I("depthToSpace")}split(e,t,n){return I("split")}sparseToDense(e,t,n,r){return I("sparseToDense")}diag(e){return I("diag")}fill(e,t,n){return I("fill")}onesLike(e){return I("onesLike")}zerosLike(e){return I("zerosLike")}linspace(e,t,n){return I("linspace")}dispose(){return I("dispose")}}function I(e){throw new Error(`'${e}' not yet implemented or not found in the registry. Did you forget to import the kernel?`)}const Jm={kernelName:so,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>S(e,Et(E(n,"float32"),-1))}}};const Xm={kernelName:ao,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const r=H(E(n,"float32")),o=de(_(k(1),r));return re(U(e,o))}}}};const Zm={kernelName:co,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const r=de(_(H(E(n,"float32")),1));return U(e,r)}}}};const Qm={kernelName:An,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)),x(s,n.shape)},a=()=>{let s=e;const c=ae(r.shape,o);return c.length>0&&(s=W(s,c)),x(s,r.shape)};return{a:i,b:a}}};const ef={kernelName:po,saveAllInputs:!0,gradFunc:(e,t)=>{const n={};return t.forEach((r,o)=>{n[o]=()=>e.clone()}),n}};const tf={kernelName:lo,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>B(n)}}};const nf={kernelName:ho,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>B(n)}}};const rf={kernelName:uo,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>U(e,de(_(k(1),H(E(n,"float32")))))}}};const of={kernelName:mo,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const r=de(C(k(1),H(E(n,"float32"))));return U(e,r)}}}};const sf={kernelName:bo,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,o=q(n.shape,r.shape),i=()=>{const s=C(H(n),H(r));let c=S(e,U(r,s));const p=ae(n.shape,o);return p.length>0&&(c=W(c,p)),x(c,n.shape)},a=()=>{const s=C(H(n),H(r));let c=re(S(e,U(n,s)));const p=ae(r.shape,o);return p.length>0&&(c=W(c,p)),x(c,r.shape)};return{a:i,b:a}}};const af={kernelName:fo,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>U(e,C(H(E(n,"float32")),1))}}};const cf={kernelName:go,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>U(e,_(k(1),H(E(n,"float32"))))}}};function yT(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=x(s,[1,s.shape[0],s.shape[1],s.shape[2],s.shape[3]]),l=x(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]])),f(p.rank===5,()=>`Error in avgPool3dBackprop: dy must be rank 5 but got rank ${p.rank}.`),f(l.rank===5,()=>`Error in avgPool3dBackprop: input must be rank 5 but got rank ${l.rank}.`),f(pe(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 m=L=>{const v=Kt(l.shape,n,r,o,i,a);return L.avgPool3dBackprop(p,l,v)},b={dy:p,input:l},y={filterSize:n,strides:r,dilations:o,pad:i,dimRoundingMode:a},w=g.runKernelFunc(m,b,null,kc,y);return h?x(w,[w.shape[1],w.shape[2],w.shape[3],w.shape[4]]):w}const pf=d({avgPool3dBackprop_:yT});const lf={kernelName:yo,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{filterSize:o,strides:i,dilations:a,pad:s,dimRoundingMode:c}=n,p=a??[1,1,1];return{x:()=>pf(e,r,o,i,p,s,c)}}};function xT(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=x(a,[1,a.shape[0],a.shape[1],a.shape[2]]),c=x(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=y=>{const w=At(s.shape,n,r,1,o);return y.avgPoolBackprop(c,s,w)},h={dy:c,input:s},m={filterSize:n,strides:r,pad:o},b=g.runKernelFunc(l,h,null,Oc,m);return p?x(b,[b.shape[1],b.shape[2],b.shape[3]]):b}const hf=d({avgPoolBackprop_:xT});const uf={kernelName:wo,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:xo,inputsToSave:["a","b"],gradFunc:(e,t,n)=>{const[r,o]=t,{transposeA:i,transposeB:a}=n;return!i&&!a?{a:()=>Y(e,o,!1,!0),b:()=>Y(r,e,!0,!1)}:!i&&a?{a:()=>Y(e,o,!1,!1),b:()=>Y(e,r,!0,!1)}:i&&!a?{a:()=>Y(o,e,!1,!0),b:()=>Y(r,e,!1,!1)}:{a:()=>Y(o,e,!0,!0),b:()=>Y(e,r,!0,!0)}}};const mf={kernelName:Lo,gradFunc:(e,t,n)=>{const{blockShape:r,crops:o}=n;return{x:()=>jn(e,r,o)}}};const ff={kernelName:So,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:Nn,gradFunc:e=>({x:()=>e.clone()})};const bf={kernelName:vo,gradFunc:e=>({x:()=>B(e)})};const wf={kernelName:Io,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{clipValueMin:o,clipValueMax:i}=n;return{x:()=>Ee(yt(ut(r,o),dt(r,i)),e,B(e))}}};const yf={kernelName:To,saveAllInputs:!0,gradFunc:(e,t,n)=>{const r=t.map(c=>c.shape),{axis:o}=n,i=z(o,t[0].shape)[0],a=r.map(c=>c[i]),s=jt(e,a,i);return s.map(c=>()=>c)}};const xf={kernelName:Ao,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[r,o]=t,{dilations:i,strides:a,pad:s,dataFormat:c}=n;return f(lt(i),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${i}'`),{x:()=>Rr(r.shape,e,o,a,s,c),filter:()=>_r(r,e,o.shape,a,s,c)}}};const Lf={kernelName:No,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:()=>_r(e,r,o.shape,i,a,s,c)}}};function LT(e,t,n,r,o){let i=e;e.rank===4&&(i=x(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let a=t;a.rank===4&&(a=x(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),f(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,m=un(i.shape,n,r,h,o);return l.conv3dDerFilter(i,a,m)},c={x:i,y:a},p={strides:r,pad:o};return g.runKernelFunc(s,c,null,Fc,p)}const Sf=d({conv3DBackpropFilter_:LT});const vf={kernelName:Ro,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:r,strides:o,pad:i}=n;f(lt(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:()=>da(a.shape,e,s,o,i),filter:()=>Sf(a,e,s.shape,o,i)}}};const If={kernelName:Co,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>S(re(ws(E(n,"float32"))),e)}}};const Tf={kernelName:Eo,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>S(ys(E(n,"float32")),e)}}};const Af={kernelName:Oo,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=rs(e,o,i,!a);return s!=null&&(c=Z(c,s)),c}}}};const Nf={kernelName:ko,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:r,strides:o,pad:i,dimRoundingMode:a}=n,s=r??[1,1];f(lt(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(pe(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=$e(c.shape,p.shape,o,s,i,a,!0);return{x:()=>Sa(c.shape,e,p,l),filter:()=>La(c,e,p.shape,l)}}};const Rf={kernelName:_o,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[r,o]=t,i={x:r,filter:o,dy:e},a={x:r,filter:o,dy:e};return{x:()=>g.runKernel(jc,i,n),filter:()=>g.runKernel(Pc,a,n)}}};const Cf={kernelName:Do,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,o=q(n.shape,r.shape),i=()=>{const s=U(e,E(r,"float32")),c=ae(n.shape,o);return c.length>0?x(W(s,c),n.shape):s},a=()=>{let s=S(e,E(n,"float32"));const c=ae(r.shape,o);c.length>0&&(s=x(W(s,c),r.shape));const p=H(r);return re(U(s,E(p,"float32")))};return{a:i,b:a}}};const Ef={kernelName:Fo,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t,r=i=>i.eluDer(e,n),o={dy:e,y:n};return{x:()=>g.runKernelFunc(r,o,null,qc)}}};const Of={kernelName:Mo,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,r=S(Oe(re(H(n))),2/Math.sqrt(Math.PI));return{x:()=>S(e,r)}}};const kf={kernelName:Uo,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>S(e,n)}}};const _f={kernelName:Wo,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>S(e,Oe(n))}}};const Df={kernelName:Bo,gradFunc:e=>({x:()=>B(e)})};const Ff={kernelName:$o,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,o=q(n.shape,r.shape),i=()=>{const s=U(e,E(r,"float32")),c=ae(n.shape,o);return c.length>0?x(W(s,c),n.shape):s},a=()=>{let s=S(e,E(n,"float32"));const c=ae(r.shape,o);c.length>0&&(s=x(W(s,c),r.shape));const p=H(r);return re(U(s,E(p,"float32")))};return{a:i,b:a}}};const Mf={kernelName:Go,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{const{varianceEpsilon:r}=n,[o,i,a,s]=t,c=s??k(1),p=ae(i.shape,o.shape),l=[];if(i.rank===1){for(let N=0;N<o.shape.length-1;++N)l.push(o.shape[N]);l.push(1)}const h=_(o,i),m=S(e,c),b=bs(C(a,k(r))),y=S(S(S(b,b),b),k(-.5)),w=()=>i.rank===1?x(S(S(e,Zt(x(b,[1,1,1,i.shape[0]]),l)),c),o.shape):x(S(S(e,b),c),o.shape),L=()=>{let N=S(S(b,k(-1)),m);return i.rank===1&&(N=W(N,p)),x(N,i.shape)},v=()=>{let N=S(S(y,h),m);return i.rank===1&&(N=W(N,p)),x(N,i.shape)},A=()=>{const N=S(h,b);let O=S(e,N);return i.rank===1&&(O=W(O,p)),x(O,i.shape)},R=()=>{let N=e;return i.rank===1&&(N=W(N,p)),x(N,i.shape)};return{x:w,mean:L,variance:v,scale:A,offset:R}}};const Bf={kernelName:jo,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{const[r,o]=t,{axis:i}=n,a=z(i,r.shape)[0],s=()=>{const c=r.shape,p=o.size,l=c.slice(0,a),h=l.length,m=c.slice(i,c.length).slice(1),b=m.length,y=Uf(0,h),w=Uf(h+1,h+1+b),L=Wf([l,[p],m]),v=x(e,L),A=x(o,[p]),R=Wf([[h],y,w]),N=Z(v,R);let O=Ss(N,A,r.shape[a]);const M=En(R);return O=Z(O,M),O};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:Po,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t;return{a:()=>B(n),b:()=>B(r)}}};const Gf={kernelName:qo,gradFunc:e=>({x:()=>E(e,"float32")})};const jf={kernelName:Ho,gradFunc:e=>({x:()=>B(e)})};const Pf={kernelName:zo,gradFunc:e=>({x:()=>B(e)})};const qf={kernelName:Yo,gradFunc:e=>({x:()=>B(e)})};const Hf={kernelName:Ko,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>U(e,C(n,1))}}};const zf={kernelName:Vo,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>U(e,E(n,"float32"))}}};const Yf={kernelName:Jo,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r]=t,{axis:o}=n;return{logits:()=>{const i=!0,a=Oe(r);return _(e,S(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 g.runKernelFunc(s,c,null,ip,p)}const Vf=d({localResponseNormalizationBackprop_:ST});const Kf={kernelName:Xo,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 Oa(e,t,n,r,o){return t.rank<n.rank&&(t=x(t,we(t.shape,r))),e.rank<n.rank&&(e=x(e,we(e.shape,r))),{x:()=>{const i=S(e,E(Xt(n,t),e.dtype));return o==null?i:Z(i,o)}}}const Vh={kernelName:Zo,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const r=n,{reductionIndices:o}=r,[i,a]=t,s=z(o,i.shape),c=fe(s,i.rank),p=Oa(e,a,i,s,c);return{x:()=>{let l=p.x();return c!=null&&(l=Z(l)),l}}}};const Jf={kernelName:Qo,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,o=()=>S(e,E(ut(n,r),"float32")),i=()=>S(e,E(Wn(n,r),"float32"));return{a:o,b:i}}};function vT(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,m=p,b=l,y=!1;p.rank===4&&(y=!0,h=x(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]]),m=x(p,[1,p.shape[0],p.shape[1],p.shape[2],p.shape[3]]),b=x(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]])),f(h.rank===5,()=>`Error in maxPool3dBackprop: dy must be rank 5 but got rank ${h.rank}.`),f(m.rank===5,()=>`Error in maxPool3dBackprop: input must be rank 5 but got rank ${m.rank}.`),f(b.rank===5,()=>`Error in maxPool3dBackprop: output must be rank 5 but got rank ${b.rank}.`),f(pe(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 N=Kt(m.shape,r,o,i,a,s);return R.maxPool3dBackprop(h,m,b,N)},L={dy:h,input:m,output:b},v={filterSize:r,strides:o,dilations:i,pad:a,dimRoundingMode:s},A=g.runKernelFunc(w,L,null,ap,v);return y?x(A,[A.shape[1],A.shape[2],A.shape[3],A.shape[4]]):A}const Xf=d({maxPool3dBackprop_:vT});const Zf={kernelName:ti,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??[1,1,1];return{x:()=>Xf(e,r,o,i,a,l,c,p)}}};function IT(e,t,n,r,o,i,a){const s=u(e,"dy","maxPoolBackprop"),c=u(t,"input","maxPoolBackprop"),p=u(n,"output","maxPoolBackprop");f(c.rank===s.rank,()=>`Rank of input (${c.rank}) does not match rank of dy (${s.rank})`),f(s.rank===4,()=>`Error in maxPoolBackprop: dy must be rank 4 but got rank ${s.rank}.`),f(c.rank===4,()=>`Error in maxPoolBackprop: input must be rank 4 but got rank ${c.rank}.`),a!=null&&f(X(i),()=>`Error in maxPoolBackprop: pad must be an integer when using, dimRoundingMode ${a} but got pad ${i}.`);const l=b=>{const y=At(c.shape,r,o,1,i,a);return b.maxPoolBackprop(s,c,p,y)},h={dy:s,input:c,output:p},m={filterSize:r,strides:o,pad:i,dimRoundingMode:a};return g.runKernelFunc(l,h,null,sp,m)}const Qf=d({maxPoolBackprop_:IT});const eg={kernelName:ei,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:ni,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const r=n,{axis:o}=r,[i,a]=t,s=z(o,i.shape),c=fe(s,i.rank),p=Oa(e,a,i,s,c);return{x:()=>{let l=p.x();return c!=null&&(l=Z(l)),l}}}};const ng={kernelName:ri,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,o=()=>S(e,E(dt(n,r),"float32")),i=()=>S(e,E(tt(n,r),"float32"));return{a:o,b:i}}};const rg={kernelName:oi,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?x(W(e,s),n.shape):e},a=()=>{const s=S(e,re(Mn(U(n,r)))),c=ae(r.shape,o);return c.length>0?x(W(s,c),r.shape):s};return{a:i,b:a}}};const og={kernelName:ii,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,o=q(n.shape,r.shape),i=()=>{const s=S(e,E(r,"float32")),c=ae(n.shape,o);return c.length>0?x(W(s,c),n.shape):s},a=()=>{const s=S(e,E(n,"float32")),c=ae(r.shape,o);return c.length>0?x(W(s,c),r.shape):s};return{a:i,b:a}}};const ig={kernelName:si,gradFunc:e=>({x:()=>re(e)})};const sg={kernelName:ci,inputsToSave:["indices"],gradFunc:(e,t)=>{const n=t[0];return{indices:()=>Re(n.shape,"float32")}}};const ag={kernelName:ai,gradFunc:e=>({x:()=>B(e)})};const Kh={kernelName:pi,inputsToSave:["x"],gradFunc:(e,t,n)=>{const r=t[0],{paddings:o}=n,i=o.map(a=>a[0]);return{x:()=>V(e,i,r.shape)}}};const cg={kernelName:li,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=E(a,"float32");let h=S(e,S(l,Xe(i,_(l,k(1)))));const m=ae(i.shape,s);return m.length>0&&(h=W(h,m)),x(h,i.shape)},p=()=>{const l=tt(i,0),h=Ee(l,wt(i),B(i));let m=S(e,S(o,h));const b=ae(a.shape,s);return b.length>0&&(m=W(m,b)),x(m,a.shape)};return{a:c,b:p}}};const pg={kernelName:hi,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{const[n,r]=t,o=tt(n,0);return{x:()=>Ee(o,e,S(e,r)),alpha:()=>{let i=Ee(o,B(e),S(e,n));const a=ae(r.shape,e.shape);return a.length>0&&(i=W(i,a)),x(i,r.shape)}}}};const lg={kernelName:ui,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>U(e,re(H(n)))}}};const hg={kernelName:bi,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,r=S(dt(n,6),Et(n));return{x:()=>S(e,E(r,"float32"))}}};const ug={kernelName:di,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>S(e,E(Et(n),"float32"))}}};const dg={kernelName:mi,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>x(e,n.shape)}}};const mg={kernelName:gi,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[r]=t,o=s=>{const{alignCorners:c}=n;return s.resizeBilinearBackprop(e,r,c)},i={images:r},a=()=>g.runKernelFunc(o,i,null,bp,n);return{images:a}}};const fg={kernelName:fi,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[r]=t,o=s=>{const{alignCorners:c}=n;return s.resizeNearestNeighborBackprop(e,r,c)},i={images:r},a=()=>g.runKernelFunc(o,i,null,gp,n);return{images:a}}};const gg={kernelName:wi,gradFunc:(e,t,n)=>{const{dims:r}=n,o=z(r,e.shape);return{x:()=>Ke(e,o)}}};const bg={kernelName:yi,gradFunc:e=>({x:()=>B(e)})};const wg={kernelName:xi,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>re(U(e,S(Xe(n,1.5),2)))}}};const yg={kernelName:Li,inputsToSave:["condition"],gradFunc:(e,t)=>{const[n]=t;return{condition:()=>E(B(n),"float32"),t:()=>S(e,E(n,e.dtype)),e:()=>S(e,E(Bn(n),e.dtype))}}};const xg={kernelName:Si,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const r=tt(n,k(0)),o=k(zh),i=k(Yh),a=S(e,i),s=S(S(e,o),Oe(E(n,"float32")));return Ee(r,a,s)}}}};const Lg={kernelName:Ni,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>S(e,S(n,_(k(1),n)))}}};const Sg={kernelName:Ai,gradFunc:e=>({x:()=>B(e)})};const vg={kernelName:Ii,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>S(_n(E(n,"float32")),e)}}};const Ig={kernelName:Ti,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>S(ns(E(n,"float32")),e)}}};const Tg={kernelName:vi,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{begin:o,size:i}=n,a=r.shape,[s,c]=ts(r,o,i),p=[];for(let l=0;l<e.rank;l++)p.push([s[l],a[l]-s[l]-c[l]]);return{x:()=>je(e,p)}}};const Ag={kernelName:_i,outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r]=t,{dim:o}=n,i=!0,a=S(e,r);return{logits:()=>_(a,S(W(a,[o],i),r))}}};const Ng={kernelName:Ri,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>S(e,Nt(n))}}};const Jh={kernelName:Oi,gradFunc:(e,t,n)=>{const{blockShape:r,paddings:o}=n;return{x:()=>kn(e,r,o)}}};const Xh={kernelName:ki,gradFunc:(e,t,n)=>{const{axis:r}=n;return{x:()=>Q(e,r)}}};const Rg={kernelName:Ci,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>U(e,S(de(E(n,"float32")),2))}}};const Cg={kernelName:yp,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>S(e,S(E(n,"float32"),2))}}};const Eg={kernelName:Di,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,o=k(2),i=()=>S(e,S(o,_(n,r))),a=()=>S(e,S(o,_(r,n)));return{a:i,b:a}}};const Og={kernelName:Pi,gradFunc:e=>({x:()=>B(e)})};const kg={kernelName:Fi,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)),x(s,n.shape)},a=()=>{let s=e;const c=ae(r.shape,o);return c.length>0&&(s=W(s,c)),x(re(s),r.shape)};return{a:i,b:a}}};const _g={kernelName:Ei,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,o=r.shape.slice(),{axis:i}=n,a=z(i,r.shape);a.forEach(p=>{o[p]=1});const s=x(e,o),c=S(s,xt(r.shape,"float32"));return{x:()=>c}}};const Dg={kernelName:Mi,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>U(e,H(_n(n)))}}};const Fg={kernelName:Ui,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>S(_(k(1),H(n)),e)}}};const Mg={kernelName:Wi,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=C(a,V(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=C(a,V(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=C(a,V(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=C(a,V(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:Bi,gradFunc:(e,t,n)=>{const r=n,{perm:o}=r,i=En(o);return{x:()=>Z(e,i)}}};const Wg={kernelName:$i,gradFunc:(e,t,n)=>{const r=n,{axis:o}=r;return{value:()=>Ue(e,o)}}};const Bg={kernelName:Gi,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{const[n]=t,r=()=>TT(e,n);return{x:r}}};function TT(e,t){const n=Ct(t,B(t)),r=Un(e,n);let o=ut(t,k(0,"int32"));const i=r.rank-o.rank;for(let s=0;s<i;++s)o=et(o,s+1);o=yt(o,xt(r.shape,"bool"));const a=B(r);return Ee(o,r,a)}const $g={kernelName:ji,gradFunc:e=>({x:()=>B(e)})};const AT=[Jm,Xm,Zm,Qm,ef,tf,nf,rf,of,sf,af,cf,lf,uf,df,mf,ff,gf,bf,wf,yf,Lf,xf,vf,If,Tf,Af,Nf,Rf,Cf,Ef,Of,kf,_f,Ff,Df,Mf,Bf,$f,Gf,jf,Pf,qf,Hf,zf,Yf,Kf,Vh,Vh,Jf,Zf,eg,tg,ng,rg,og,ig,sg,ag,Kh,Kh,cg,pg,lg,hg,ug,dg,mg,fg,gg,bg,wg,yg,xg,Lg,Sg,vg,Ig,Tg,Ag,Ng,Jh,Jh,Xh,Xh,Rg,Eg,Cg,Og,kg,_g,Dg,Fg,Mg,Ug,Wg,Bg,$g];for(const e of AT)Tp(e);const js={};me(js,{Abs:()=>so,Acos:()=>ao,Acosh:()=>co,AdadeltaOptimizer:()=>Zn,AdagradOptimizer:()=>Qn,AdamOptimizer:()=>er,AdamaxOptimizer:()=>tr,Add:()=>An,AddN:()=>po,All:()=>Cc,Any:()=>Ec,ArgMax:()=>lo,ArgMin:()=>ho,Asin:()=>uo,Asinh:()=>mo,Atan:()=>fo,Atan2:()=>bo,Atanh:()=>go,AvgPool:()=>wo,AvgPool3D:()=>yo,AvgPool3DBackprop:()=>kc,AvgPoolBackprop:()=>Oc,BatchMatMul:()=>xo,BatchToSpaceND:()=>Lo,BroadcastTo:()=>So,Cast:()=>Nn,Ceil:()=>vo,ClipByValue:()=>Io,Complex:()=>_c,Concat:()=>To,Conv2D:()=>Ao,Conv2DBackpropFilter:()=>Dc,Conv2DBackpropInput:()=>No,Conv3D:()=>Ro,Conv3DBackpropFilterV2:()=>Fc,Conv3DBackpropInputV2:()=>Mc,Cos:()=>Co,Cosh:()=>Eo,CropAndResize:()=>Uc,Cumsum:()=>Oo,DataStorage:()=>bT,DepthToSpace:()=>Wc,DepthwiseConv2dNative:()=>ko,DepthwiseConv2dNativeBackpropFilter:()=>Bc,DepthwiseConv2dNativeBackpropInput:()=>$c,Diag:()=>Gc,Dilation2D:()=>_o,Dilation2DBackpropFilter:()=>Pc,Dilation2DBackpropInput:()=>jc,Div:()=>Do,ENV:()=>Tc,Elu:()=>Fo,EluGrad:()=>qc,Environment:()=>Ic,Equal:()=>Hc,Erf:()=>Mo,Exp:()=>Uo,Expm1:()=>Wo,FFT:()=>zc,Fill:()=>Yc,FlipLeftRight:()=>Vc,Floor:()=>Bo,FloorDiv:()=>$o,FromPixels:()=>na,FusedBatchNorm:()=>Go,FusedConv2D:()=>oa,FusedDepthwiseConv2D:()=>ia,GatherNd:()=>Kc,GatherV2:()=>jo,Greater:()=>Jc,GreaterEqual:()=>Po,IFFT:()=>Xc,Identity:()=>qo,Imag:()=>Zc,IsFinite:()=>Ho,IsInf:()=>zo,IsNan:()=>Yo,KernelBackend:()=>wT,LRN:()=>Xo,LRNBackprop:()=>ip,Less:()=>Qc,LessEqual:()=>ep,LinSpace:()=>tp,Log:()=>Vo,Log1p:()=>Ko,LogSoftmax:()=>Jo,LogicalAnd:()=>np,LogicalNot:()=>rp,LogicalOr:()=>op,Max:()=>Zo,MaxPool:()=>ei,MaxPool3D:()=>ti,MaxPool3DBackprop:()=>ap,MaxPoolBackprop:()=>sp,MaxPoolWithArgmax:()=>cp,Maximum:()=>Qo,Mean:()=>Ew,Min:()=>ni,Minimum:()=>ri,Mod:()=>oi,MomentumOptimizer:()=>nr,Multiply:()=>ii,Negate:()=>si,NonMaxSuppressionV3:()=>lp,NonMaxSuppressionV4:()=>hp,NonMaxSuppressionV5:()=>up,NotEqual:()=>pp,OneHot:()=>ci,OnesLike:()=>ai,Optimizer:()=>it,PadV2:()=>pi,Pool:()=>Ow,Pow:()=>li,Prelu:()=>hi,Prod:()=>dp,RMSPropOptimizer:()=>rr,Range:()=>mp,Rank:()=>Fp,Real:()=>fp,Reciprocal:()=>ui,Reduction:()=>be,Relu:()=>di,Relu6:()=>bi,Reshape:()=>mi,ResizeBilinear:()=>gi,ResizeBilinearGrad:()=>bp,ResizeNearestNeighbor:()=>fi,ResizeNearestNeighborGrad:()=>gp,Reverse:()=>wi,RotateWithOffset:()=>vp,Round:()=>yi,Rsqrt:()=>xi,SGDOptimizer:()=>tn,ScatterNd:()=>wp,SelectV2:()=>Li,Selu:()=>Si,Sigmoid:()=>Ni,Sign:()=>Ai,Sin:()=>Ii,Sinh:()=>Ti,Slice:()=>vi,Softmax:()=>_i,Softplus:()=>Ri,SpaceToBatchND:()=>Oi,SparseToDense:()=>xp,SplitV:()=>ki,Sqrt:()=>Ci,Square:()=>yp,SquaredDifference:()=>Di,Step:()=>Pi,StridedSlice:()=>Lp,Sub:()=>Fi,Sum:()=>Ei,Tan:()=>Mi,Tanh:()=>Ui,Tensor:()=>ne,TensorBuffer:()=>Sr,Tile:()=>Wi,TopK:()=>Sp,Transpose:()=>Bi,Unpack:()=>$i,UnsortedSegmentSum:()=>Gi,Variable:()=>$t,ZerosLike:()=>ji,_FusedMatMul:()=>ra,abs:()=>Ce,acos:()=>jp,acosh:()=>Pp,add:()=>C,addN:()=>qp,addStrict:()=>Fd,all:()=>Yp,any:()=>Vp,argMax:()=>Kp,argMin:()=>Jp,asin:()=>Xp,asinh:()=>Zp,atan:()=>Qp,atan2:()=>el,atanh:()=>tl,avgPool:()=>ht,avgPool3d:()=>il,backend:()=>Yy,backend_util:()=>Hm,basicLSTMCell:()=>gl,batchNorm:()=>Jt,batchNorm2d:()=>bl,batchNorm3d:()=>wl,batchNorm4d:()=>yl,batchToSpaceND:()=>kn,booleanMaskAsync:()=>Rd,broadcastTo:()=>Nr,browser:()=>Ur,buffer:()=>Me,cast:()=>E,ceil:()=>xl,clipByValue:()=>Ll,clone:()=>Rt,complex:()=>Ve,concat:()=>Q,concat1d:()=>Sl,concat2d:()=>vl,concat3d:()=>Il,concat4d:()=>Tl,conv1d:()=>Al,conv2d:()=>ve,conv2dTranspose:()=>Nl,conv3d:()=>Rl,conv3dTranspose:()=>Cl,cos:()=>_n,cosh:()=>ns,cosineWindow:()=>kr,cumsum:()=>rs,customGrad:()=>Je,deprecationWarn:()=>xe,depthToSpace:()=>El,depthwiseConv2d:()=>Dn,device_util:()=>fd,diag:()=>Ol,dilation2d:()=>kl,disableDeprecationWarnings:()=>Dy,dispose:()=>Le,disposeVariables:()=>Fy,div:()=>U,divNoNan:()=>_l,divStrict:()=>Md,dot:()=>Dl,dropout:()=>Qd,elu:()=>is,enableDebugMode:()=>_y,enableProdMode:()=>ky,enclosingPowerOfTwo:()=>xa,engine:()=>My,env:()=>ce,equal:()=>Xt,equalStrict:()=>Cd,erf:()=>Fl,exp:()=>Oe,expandDims:()=>et,expm1:()=>Ml,eye:()=>ss,fft:()=>Fn,fill:()=>Ge,findBackend:()=>qy,findBackendFactory:()=>Hy,floor:()=>Mn,floorDiv:()=>os,fused:()=>Dh,gather:()=>Un,gatherND:()=>Xd,gather_util:()=>jm,getBackend:()=>jy,getGradient:()=>sa,getKernel:()=>Hi,getKernelsForBackend:()=>aa,grad:()=>bL,grads:()=>wL,greater:()=>tt,greaterEqual:()=>ut,greaterEqualStrict:()=>Ed,greaterStrict:()=>Od,ifft:()=>dn,imag:()=>Qt,image:()=>Ra,inTopKAsync:()=>em,io:()=>Mr,irfft:()=>as,isFinite:()=>Wl,isInf:()=>Bl,isNaN:()=>$l,keep:()=>ol,kernel_impls:()=>Km,leakyRelu:()=>Gl,less:()=>Wn,lessEqual:()=>dt,lessEqualStrict:()=>kd,lessStrict:()=>_d,linalg:()=>Em,linspace:()=>jl,localResponseNormalization:()=>Pl,log:()=>wt,log1p:()=>cs,logSigmoid:()=>Hl,logSoftmax:()=>zl,logSumExp:()=>ls,logicalAnd:()=>yt,logicalNot:()=>Bn,logicalOr:()=>hs,logicalXor:()=>Yl,losses:()=>Om,matMul:()=>Y,math:()=>Gm,max:()=>mt,maxPool:()=>Ie,maxPool3d:()=>Vl,maxPoolWithArgmax:()=>Kl,maximum:()=>Ct,maximumStrict:()=>Ud,mean:()=>mn,memory:()=>Uy,min:()=>fn,minimum:()=>$n,minimumStrict:()=>Wd,mod:()=>us,modStrict:()=>Bd,moments:()=>Jl,movingAverage:()=>Hd,mul:()=>S,mulStrict:()=>$d,multiRNNCell:()=>Xl,multinomial:()=>Zl,neg:()=>re,nextFrame:()=>PI,norm:()=>Or,notEqual:()=>Gn,notEqualStrict:()=>Dd,oneHot:()=>Cr,ones:()=>xt,onesLike:()=>ga,op:()=>d,outerProduct:()=>Ql,pad:()=>je,pad1d:()=>eh,pad2d:()=>th,pad3d:()=>nh,pad4d:()=>rh,pool:()=>oh,pow:()=>Xe,powStrict:()=>Gd,prelu:()=>ds,print:()=>ih,prod:()=>sh,profile:()=>Wy,rand:()=>ah,randomGamma:()=>hh,randomNormal:()=>uh,randomUniform:()=>fs,range:()=>Er,ready:()=>Gy,real:()=>Gt,reciprocal:()=>dh,registerBackend:()=>zy,registerGradient:()=>Tp,registerKernel:()=>kw,relu:()=>se,relu6:()=>gs,removeBackend:()=>Py,reshape:()=>x,reverse:()=>Ke,reverse1d:()=>mh,reverse2d:()=>fh,reverse3d:()=>gh,reverse4d:()=>bh,rfft:()=>Pn,round:()=>yh,rsqrt:()=>bs,scalar:()=>k,scatterND:()=>Vd,scatter_util:()=>zd,selu:()=>xh,separableConv2d:()=>qn,serialization:()=>qm,setBackend:()=>$y,setPlatform:()=>Vy,setdiff1dAsync:()=>Lh,sigmoid:()=>Nt,sign:()=>Sh,signal:()=>Cm,sin:()=>ws,sinh:()=>ys,slice:()=>V,slice1d:()=>vh,slice2d:()=>Ih,slice3d:()=>xs,slice4d:()=>Th,slice_util:()=>yd,softmax:()=>en,softplus:()=>ps,spaceToBatchND:()=>jn,sparseToDense:()=>Jd,spectral:()=>Rm,split:()=>jt,sqrt:()=>de,square:()=>H,squaredDifference:()=>Hn,squaredDifferenceStrict:()=>jd,squeeze:()=>zn,stack:()=>Ue,step:()=>Et,stridedSlice:()=>Ah,sub:()=>_,subStrict:()=>Pd,sum:()=>W,sumOutType:()=>ey,tan:()=>Nh,tanh:()=>Ar,tensor:()=>Ye,tensor1d:()=>ge,tensor2d:()=>ft,tensor3d:()=>Ls,tensor4d:()=>Pt,tensor5d:()=>Rh,tensor6d:()=>Ch,tensor_util:()=>ud,test_util:()=>Id,tidy:()=>F,tile:()=>Zt,time:()=>By,topk:()=>Eh,train:()=>GI,transpose:()=>Z,truncatedNormal:()=>Oh,unregisterGradient:()=>Dw,unregisterKernel:()=>_w,unsortedSegmentSum:()=>Ss,unstack:()=>We,upcastType:()=>Ir,util:()=>Xu,valueAndGrad:()=>yL,valueAndGrads:()=>xL,variable:()=>kh,variableGrads:()=>ql,version_core:()=>$I,where:()=>Ee,whereAsync:()=>vs,zeros:()=>Re,zerosLike:()=>B});function nn(e,t,n=!1){if(e.beginPath(),t.slice(1).forEach(({x:r,y:o},i)=>{const a=t[i];e.moveTo(a.x,a.y),e.lineTo(r,o)}),n){const r=t[t.length-1],o=t[0];if(!r||!o)return;e.moveTo(r.x,r.y),e.lineTo(o.x,o.y)}e.stroke()}class Qe{constructor(e,t){if(!kt(e)||!kt(t))throw new Error(`Dimensions.constructor - expected width and height to be valid numbers, instead have ${JSON.stringify({width:e,height:t})}`);this._width=e,this._height=t}get width(){return this._width}get height(){return this._height}reverse(){return new Qe(1/this.width,1/this.height)}}const qs={};me(qs,{computeReshapedDimensions:()=>eu,getCenterPoint:()=>ar,isDimensions:()=>_a,isEven:()=>ka,isFloat:()=>Qh,isTensor:()=>or,isTensor1D:()=>NT,isTensor2D:()=>Zh,isTensor3D:()=>ir,isTensor4D:()=>gt,isValidNumber:()=>kt,isValidProbablitiy:()=>Br,range:()=>qt,round:()=>sr});function or(e,t){return e instanceof ne&&e.shape.length===t}function NT(e){return or(e,1)}function Zh(e){return or(e,2)}function ir(e){return or(e,3)}function gt(e){return or(e,4)}function Qh(e){return e%1!==0}function ka(e){return e%2===0}function sr(e,t=2){const n=Math.pow(10,t);return Math.floor(e*n)/n}function _a(e){return e&&e.width&&e.height}function eu({width:e,height:t},n){const r=n/Math.max(t,e);return new Qe(Math.round(e*r),Math.round(t*r))}function ar(e){return e.reduce((t,n)=>t.add(n),new J(0,0)).div(new J(e.length,e.length))}function qt(e,t,n){return Array(e).fill(0).map((r,o)=>t+o*n)}function kt(e){return!!e&&e!==Infinity&&e!==-Infinity&&!isNaN(e)||e===0}function Br(e){return kt(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 he{constructor(e,t=!0){const n=e||{},r=[n.left,n.top,n.right,n.bottom].every(kt),o=[n.x,n.y,n.width,n.height].every(kt);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];he.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(kt)}static assertIsValidBox(e,t,n=!1){if(!he.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 he({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 he({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 he({x:e,y:t,width:n,height:r})}rescale(e){const t=_a(e)?e.width:e,n=_a(e)?e.height:e;return new he({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 he({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 he({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 he({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 he({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 gr extends he{constructor(e,t,n,r,o=!1){super({left:e,top:t,right:n,bottom:r},o)}}class Tn{constructor(e,t,n,r,o){this._imageDims=new Qe(o.width,o.height),this._score=e,this._classScore=t,this._className=n,this._box=new he(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 he(this._box).rescale(this.imageDims.reverse())}forSize(e,t){return new Tn(this.score,this.classScore,this.className,this.relativeBox,{width:e,height:t})}}class ye extends Tn{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 ye(n,r,o)}}function Vs(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 Ys(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 gr(r,o,i,a)}function zs(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],m=e[l];c.push(Vs(h,m,r))}o=o.filter((p,l)=>c[l]<=n)}return i}function bt(e,t){return F(()=>{const[n,r,o]=t,i=Ge([...e.shape.slice(0,3),1],n),a=Ge([...e.shape.slice(0,3),1],r),s=Ge([...e.shape.slice(0,3),1],o),c=Q([i,a,s],3);return _(e,c)})}function Hs(e,t=!1){return F(()=>{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=m=>{const b=e.shape.slice();return b[a]=m,Ge(b,0)},c=s(i),p=o-c.shape[a],l=t&&p?s(p):null,h=[l,e,c].filter(m=>!!m).map(m=>m.toFloat());return Q(h,a)})}function $u(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 ur(e){return 1/(1+Math.exp(-e))}function Gu(e){return Math.log(e/(1-e))}class ea extends he{constructor(e,t,n,r,o=!1){super({x:e,y:t,width:n,height:r},o)}}const RT=.5,CT=.43,ET=.45;class ct{constructor(e,t,n=new J(0,0)){const{width:r,height:o}=t;this._imgDims=new Qe(r,o),this._shift=n,this._positions=e.map(i=>i.mul(new J(r,o)).add(n))}get shift(){return new J(this._shift.x,this._shift.y)}get imageWidth(){return this._imgDims.width}get imageHeight(){return this._imgDims.height}get positions(){return this._positions}get relativePositions(){return this._positions.map(e=>e.sub(this._shift).div(new J(this.imageWidth,this.imageHeight)))}forSize(e,t){return new this.constructor(this.relativePositions,{width:e,height:t})}shiftBy(e,t){return new this.constructor(this.relativePositions,this._imgDims,new J(e,t))}shiftByPoint(e){return this.shiftBy(e.x,e.y)}align(e,t={}){if(e){const o=e instanceof ye?e.box.floor():new he(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/ET),s=ar(e),c=Math.floor(Math.max(0,s.x-RT*a)),p=Math.floor(Math.max(0,s.y-CT*a));return new ea(c,p,Math.min(a,this.imageWidth+c),Math.min(a,this.imageHeight+p))}alignMinBbox(e){const t=Ys(this.positions);return t.pad(t.width*e,t.height*e)}getRefPointsForAlignment(){throw new Error("getRefPointsForAlignment not implemented by base class")}}class Yu extends ct{getRefPointsForAlignment(){const e=this.positions;return[e[0],e[1],ar([e[3],e[4]])]}}class fr extends ct{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(ar)}}class io{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?` (${sr(this.distance)})`:""}`}}class oo extends he{constructor(e,t){super(e);this._label=t}static assertIsValidLabeledBox(e,t){if(he.assertIsValidBox(e,t),!kt(e.label))throw new Error(`${t} - expected property label (${e.label}) to be a number`)}get label(){return this._label}}class ln{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 ln(e.label,t)}}class zu extends oo{constructor(e,t,n,r){super(e,t);this._score=n,this._classScore=r}static assertIsValidPredictedBox(e,t){if(oo.assertIsValidLabeledBox(e,t),!Br(e.score)||!Br(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 ye}function cn(e,t){const n={detection:t};return Object.assign({},e,n)}function tc(){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 Us(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 nc(){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=Us();return{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 rc(){return typeof window=="object"&&typeof document!="undefined"&&typeof HTMLImageElement!="undefined"&&typeof HTMLCanvasElement!="undefined"&&typeof HTMLVideoElement!="undefined"&&typeof ImageData!="undefined"&&typeof CanvasRenderingContext2D!="undefined"}const Gg=ee(qe());function wn(e){return!Gg.env.isNodejs()&&typeof e=="string"?document.getElementById(e):e}const jg=ee(qe());function Ze(e){const{Canvas:t,CanvasRenderingContext2D:n}=jg.env.getEnv();if(e instanceof n)return e;const r=wn(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 Ht;(function(e){e.TOP_LEFT="TOP_LEFT",e.TOP_RIGHT="TOP_RIGHT",e.BOTTOM_LEFT="BOTTOM_LEFT",e.BOTTOM_RIGHT="BOTTOM_RIGHT"})(Ht||(Ht={}));class Da{constructor(e={}){const{anchorPosition:t,backgroundColor:n,fontColor:r,fontSize:o,fontStyle:i,padding:a}=e;this.anchorPosition=t||Ht.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 $r{constructor(e,t,n={}){this.text=typeof e=="string"?[e]:e instanceof $r?e.text:e,this.anchor=t,this.options=new Da(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===Ht.BOTTOM_RIGHT||n===Ht.TOP_RIGHT,o=n===Ht.BOTTOM_LEFT||n===Ht.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),m=Math.max(Math.min(c,l-a),0);return{x:h,y:m}}return{x:s,y:c}}draw(e){const t=wn(e),n=Ze(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,m)=>{const b=s+l.x,y=s+l.y+(m+1)*i;n.fillText(h,b,y)})}}class Pg{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:Ht.BOTTOM_LEFT,backgroundColor:this.boxColor};this.drawLabelOptions=new Da(Object.assign({},i,o))}}class tu{constructor(e,t={}){this.box=new he(e),this.options=new Pg(t)}draw(e){const t=Ze(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 $r([c],{x:o-r/2,y:i},this.options.drawLabelOptions).draw(e)}}function OT(e,t){const n=Array.isArray(t)?t:[t];n.forEach(r=>{const o=r instanceof ye?r.score:It(r)?r.detection.score:void 0,i=r instanceof ye?r.box:It(r)?r.detection.box:new he(r),a=o?`${sr(o)}`:void 0;new tu(i,{label:a}).draw(e)})}const qg=ee(qe());function Zr(e){const{Image:t,Video:n}=qg.env.getEnv();return e instanceof t&&e.complete||e instanceof n&&e.readyState>=3}const Hg=ee(qe());function uc(e){return new Promise((t,n)=>{if(e instanceof Hg.env.getEnv().Canvas||Zr(e))return t();function r(i){if(!i.currentTarget)return;i.currentTarget.removeEventListener("load",r),i.currentTarget.removeEventListener("error",o),t(i)}function o(i){if(!i.currentTarget)return;i.currentTarget.removeEventListener("load",r),i.currentTarget.removeEventListener("error",o),n(i)}e.addEventListener("load",r),e.addEventListener("error",o)})}const zg=ee(qe());function hc(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=zg.env.getEnv().createImageElement();o.onload=()=>t(o),o.onerror=n,o.src=r.result},r.onerror=n,r.readAsDataURL(e)})}const Yg=ee(qe());function yn(e){const{Image:t,Video:n}=Yg.env.getEnv();return e instanceof t?new Qe(e.naturalWidth,e.naturalHeight):e instanceof n?new Qe(e.videoWidth,e.videoHeight):new Qe(e.width,e.height)}const nu=ee(qe());function hr({width:e,height:t}){const{createCanvasElement:n}=nu.env.getEnv(),r=n();return r.width=e,r.height=t,r}function Qr(e,t){const{ImageData:n}=nu.env.getEnv();if(!(e instanceof n)&&!Zr(e))throw new Error("createCanvasFromMedia - media has not finished loading yet");const{width:r,height:o}=t||yn(e),i=hr({width:r,height:o});return e instanceof n?Ze(i).putImageData(e,0,0):Ze(i).drawImage(e,0,0,r,o),i}const Vg=ee(qe());async function pc(e,t){const n=t||Vg.env.getEnv().createCanvasElement(),[r,o,i]=e.shape.slice(gt(e)?1:0),a=F(()=>e.as3D(r,o,i).toInt());return await Ur.toPixels(a,n),a.dispose(),n}const Kg=ee(qe());function Ws(e){const{Image:t,Canvas:n,Video:r}=Kg.env.getEnv();return e instanceof t||e instanceof n||e instanceof r}const Jg=ee(qe());function cc(e,t,n=!1){const{Image:r,Canvas:o}=Jg.env.getEnv();if(!(e instanceof r||e instanceof o))throw new Error("imageToSquare - expected arg0 to be HTMLImageElement | HTMLCanvasElement");const i=yn(e),a=t/Math.max(i.height,i.width),s=a*i.width,c=a*i.height,p=hr({width:t,height:t}),l=e instanceof o?e:Qr(e),h=Math.abs(s-c)/2,m=n&&s<c?h:0,b=n&&c<s?h:0;return Ze(p).drawImage(l,m,b,s,c),p}const ru=ee(qe());class Bs{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(ir(n)){this._imageTensors[r]=n,this._inputDimensions[r]=n.shape;return}if(gt(n)){const i=n.shape[0];if(i!==1)throw new Error(`NetInput - tf.Tensor4D with batchSize ${i} passed, but not supported in input array`);this._imageTensors[r]=n,this._inputDimensions[r]=n.shape.slice(1);return}const o=n instanceof ru.env.getEnv().Canvas?n:Qr(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 qt(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 eu({width:t,height:n},this.inputSize)}toBatchTensor(e,t=!0){return this._inputSize=e,F(()=>{const n=qt(this.batchSize,0,1).map(o=>{const i=this.getInput(o);if(i instanceof ne){let a=gt(i)?i:i.expandDims();return a=Hs(a,t),(a.shape[1]!==e||a.shape[2]!==e)&&(a=Ra.resizeBilinear(a,[e,e])),a.as3D(e,e,3)}if(i instanceof ru.env.getEnv().Canvas)return Ur.fromPixels(cc(i,e,t));throw new Error(`toBatchTensor - at batchIdx ${o}, expected input to be instanceof tf.Tensor or instanceof HTMLCanvasElement, instead have ${i}`)}),r=Ue(n.map(o=>o.toFloat())).as4D(this.batchSize,e,e,3);return r})}}async function ac(e){if(e instanceof Bs)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(wn);return r.forEach((o,i)=>{if(!Ws(o)&&!ir(o)&&!gt(o))throw typeof t[i]=="string"?new Error(`toNetInput -${n(i)} string passed, but could not resolve HTMLElement for element id ${t[i]}`):new Error(`toNetInput -${n(i)} expected media to be of type HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | tf.Tensor3D, or to be an element id`);if(gt(o)){const a=o.shape[0];if(a!==1)throw new Error(`toNetInput -${n(i)} tf.Tensor4D with batchSize ${a} passed, but not supported in input array`)}}),await Promise.all(r.map(o=>Ws(o)&&uc(o))),new Bs(r,Array.isArray(e))}const Xg=ee(qe());async function ow(e,t){const{Canvas:n}=Xg.env.getEnv();let r=e;if(!(e instanceof n)){const a=await ac(e);if(a.batchSize>1)throw new Error("extractFaces - batchSize > 1 not supported");const s=a.getInput(0);r=s instanceof n?s:await pc(s)}const o=Ze(r),i=t.map(a=>a instanceof ye?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=hr({width:c,height:p});return Ze(l).putImageData(o.getImageData(a,s,c,p),0,0),l})}async function iw(e,t){if(!ir(e)&&!gt(e))throw new Error("extractFaceTensors - expected image tensor to be 3D or 4D");if(gt(e)&&e.shape[0]>1)throw new Error("extractFaceTensors - batchSize > 1 not supported");return F(()=>{const[n,r,o]=e.shape.slice(gt(e)?1:0),i=t.map(s=>s instanceof ye?s.forSize(r,n).box:s).map(s=>s.clipAtImageBorders(r,n)),a=i.map(({x:s,y:c,width:p,height:l})=>xs(e.as3D(n,r,o),[c,s,0],[l,p,o]));return a})}const Zg=ee(qe());async function xn(e,t){const n=Zg.env.getEnv().fetch,r=await n(e,t);if(!(r.status<400))throw new Error(`failed to fetch: (${r.status}) ${r.statusText}, from url: ${r.url}`);return r}async function rw(e){const t=await xn(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 hc(n)}async function lc(e){return(await xn(e)).json()}async function nw(e){return new Float32Array(await(await xn(e)).arrayBuffer())}function Fa(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 tw(e,t){const{manifestUri:n,modelBaseUri:r}=Fa(e,t),o=await lc(n);return Mr.loadWeights(o,r)}function ew(e,t,n=!1){const{width:r,height:o}=n?yn(t):t;return e.width=r,e.height=o,{width:r,height:o}}const Qg=ee(ot()),eb=ee(qe());class He{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=Ye(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 Qg.loadWeightMap(e,this.getDefaultModelName());this.loadFromWeightMap(t)}async loadFromDisk(e){if(e&&typeof e!="string")throw new Error(`${this._name}.loadFromDisk - expected model file path`);const{readFile:t}=eb.env.getEnv(),{manifestUri:n,modelBaseUri:r}=Fa(e,this.getDefaultModelName()),o=c=>Promise.all(c.map(p=>t(p).then(l=>l.buffer))),i=Mr.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 ne))throw new Error(`traversePropertyPath - parameter is not a tensor, for path ${e}`);return{obj:n,objProp:r}}}function rt(e,t,n){return F(()=>{let r=qn(e,t.depthwise_filter,t.pointwise_filter,n,"same");return r=C(r,t.bias),r})}function Ma(e,t,n=!1){return F(()=>{const r=se(n?C(ve(e,t.conv0.filters,[2,2],"same"),t.conv0.bias):rt(e,t.conv0,[2,2])),o=rt(r,t.conv1,[1,1]),i=se(C(r,o)),a=rt(i,t.conv2,[1,1]);return se(C(r,C(o,a)))})}function Ns(e,t,n=!1,r=!0){return F(()=>{const o=se(n?C(ve(e,t.conv0.filters,r?[2,2]:[1,1],"same"),t.conv0.bias):rt(e,t.conv0,r?[2,2]:[1,1])),i=rt(o,t.conv1,[1,1]),a=se(C(o,i)),s=rt(a,t.conv2,[1,1]),c=se(C(o,C(i,s))),p=rt(c,t.conv3,[1,1]);return se(C(o,C(i,C(s,p))))})}function Ua(e,t,n="same",r=!1){return F(()=>{const o=C(ve(e,t.filters,[1,1],n),t.bias);return r?se(o):o})}function st(e,t){Object.keys(e).forEach(n=>{t.some(r=>r.originalPath===n)||e[n].dispose()})}function Gr(e,t){return function(n,r,o,i){const a=Pt(e(n*r*o*o),[o,o,n,r]),s=ge(e(r));return t.push({paramPath:`${i}/filters`},{paramPath:`${i}/bias`}),{filters:a,bias:s}}}function Wa(e,t){return function(n,r,o){const i=ft(e(n*r),[n,r]),a=ge(e(r));return t.push({paramPath:`${o}/weights`},{paramPath:`${o}/bias`}),{weights:i,bias:a}}}class ou{constructor(e,t,n){this.depthwise_filter=e,this.pointwise_filter=t,this.bias=n}}function jr(e,t){return function(n,r,o){const i=Pt(e(3*3*n),[3,3,n,1]),a=Pt(e(n*r),[1,1,n,r]),s=ge(e(r));return t.push({paramPath:`${o}/depthwise_filter`},{paramPath:`${o}/pointwise_filter`},{paramPath:`${o}/bias`}),new ou(i,a,s)}}function Pr(e){return function(t){const n=e(`${t}/depthwise_filter`,4),r=e(`${t}/pointwise_filter`,4),o=e(`${t}/bias`,1);return new ou(n,r,o)}}function St(e,t){return function(n,r,o){const i=e[n];if(!or(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 at(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 Ba(e,t){const n=Gr(e,t),r=jr(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`),m=r(s,s,`${c}/conv2`);return{conv0:l,conv1:h,conv2:m}}function i(a,s,c,p=!1){const{conv0:l,conv1:h,conv2:m}=o(a,s,c,p),b=r(s,s,`${c}/conv3`);return{conv0:l,conv1:h,conv2:m,conv3:b}}return{extractDenseBlock3Params:o,extractDenseBlock4Params:i}}function tb(e){const t=[],{extractWeights:n,getRemainingWeights:r}=at(e),{extractDenseBlock4Params:o}=Ba(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 $a(e){return function(t){const n=e(`${t}/filters`,4),r=e(`${t}/bias`,1);return{filters:n,bias:r}}}function Ga(e,t){const n=St(e,t),r=$a(n),o=Pr(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`),m=o(`${s}/conv3`);return{conv0:p,conv1:l,conv2:h,conv3:m}}return{extractDenseBlock3Params:i,extractDenseBlock4Params:a}}function nb(e){const t=[],{extractDenseBlock4Params:n}=Ga(e,t),r={dense0:n("dense0",!0),dense1:n("dense1"),dense2:n("dense2"),dense3:n("dense3")};return st(e,t),{params:r,paramMappings:t}}const rb=ee(ot());class ja extends He{constructor(){super("FaceFeatureExtractor")}forwardInput(e){const{params:t}=this;if(!t)throw new Error("FaceFeatureExtractor - load model before inference");return F(()=>{const n=e.toBatchTensor(112,!0),r=[122.782,117.001,104.298],o=bt(n,r).div(k(255));let i=Ns(o,t.dense0,!0);return i=Ns(i,t.dense1),i=Ns(i,t.dense2),i=Ns(i,t.dense3),i=ht(i,[7,7],[2,2],"valid"),i})}async forward(e){return this.forwardInput(await rb.toNetInput(e))}getDefaultModelName(){return"face_feature_extractor_model"}extractParamsFromWeigthMap(e){return nb(e)}extractParams(e){return tb(e)}}function Rs(e,t){return F(()=>C(Y(e,t.weights),t.bias))}function ob(e,t,n){const r=[],{extractWeights:o,getRemainingWeights:i}=at(e),a=Wa(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 ib(e){const t=[],n=St(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 st(e,t),{params:o,paramMappings:t}}function Pa(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}}const sb=ee(ot());class qa extends He{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 F(()=>{const n=e instanceof sb.NetInput?this.faceFeatureExtractor.forwardInput(e):e;return Rs(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 ob(e,this.getClassifierChannelsIn(),this.getClassifierChannelsOut())}extractParamsFromWeigthMap(e){const{featureExtractorMap:t,classifierMap:n}=Pa(e);return this.faceFeatureExtractor.loadFromWeightMap(t),ib(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 Xs=["neutral","happy","sad","angry","fearful","disgusted","surprised"];class pn{constructor(e){if(e.length!==7)throw new Error(`FaceExpressions.constructor - expected probabilities.length to be 7, have: ${e.length}`);Xs.forEach((t,n)=>{this[t]=e[n]})}asSortedArray(){return Xs.map(e=>({expression:e,probability:this[e]})).sort((e,t)=>t.probability-e.probability)}}const iu=ee(ot());class Zs extends qa{constructor(e=new ja()){super("FaceExpressionNet",e)}forwardInput(e){return F(()=>en(this.runNet(e)))}async forward(e){return this.forwardInput(await iu.toNetInput(e))}async predictExpressions(e){const t=await iu.toNetInput(e),n=await this.forwardInput(t),r=await Promise.all(We(n).map(async i=>{const a=await i.data();return i.dispose(),a}));n.dispose();const o=r.map(i=>new pn(i));return t.isBatchInput?o:o[0]}getDefaultModelName(){return"face_expression_model"}getClassifierChannelsIn(){return 256}getClassifierChannelsOut(){return 7}}function Ks(e){return e.expressions instanceof pn}function to(e,t){const n={expressions:t};return Object.assign({},e,n)}function kT(e,t,n=.1,r){const o=Array.isArray(t)?t:[t];o.forEach(i=>{const a=i instanceof pn?i:Ks(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 $r(c.map(h=>`${h.expression} (${sr(h.probability)})`),p);l.draw(e)})}function an(e){return It(e)&&e.landmarks instanceof ct&&e.unshiftedLandmarks instanceof ct&&e.alignedRect instanceof ye}function In(e,t){const{box:n}=e.detection,r=t.shiftBy(n.x,n.y),o=r.align(),{imageDims:i}=e.detection,a=new ye(e.detection.score,o.rescale(i.reverse()),i),s={landmarks:r,unshiftedLandmarks:t,alignedRect:a};return Object.assign({},e,s)}class ab{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 cb{constructor(e,t={}){this.faceLandmarks=e,this.options=new ab(t)}draw(e){const t=Ze(e),{drawLines:n,drawPoints:r,lineWidth:o,lineColor:i,pointSize:a,pointColor:s}=this.options;if(n&&this.faceLandmarks instanceof fr&&(t.strokeStyle=i,t.lineWidth=o,nn(t,this.faceLandmarks.getJawOutline()),nn(t,this.faceLandmarks.getLeftEyeBrow()),nn(t,this.faceLandmarks.getRightEyeBrow()),nn(t,this.faceLandmarks.getNose()),nn(t,this.faceLandmarks.getLeftEye(),!0),nn(t,this.faceLandmarks.getRightEye(),!0),nn(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 _T(e,t){const n=Array.isArray(t)?t:[t];n.forEach(r=>{const o=r instanceof ct?r:an(r)?r.landmarks:void 0;if(!o)throw new Error("drawFaceLandmarks - expected faceExpressions to be FaceLandmarks | WithFaceLandmarks<WithFaceDetection<{}>> or array thereof");new cb(o).draw(e)})}const Ps={};me(Ps,{AnchorPosition:()=>Ht,DrawBox:()=>tu,DrawBoxOptions:()=>Pg,DrawFaceLandmarks:()=>cb,DrawFaceLandmarksOptions:()=>ab,DrawTextField:()=>$r,DrawTextFieldOptions:()=>Da,drawContour:()=>nn,drawDetections:()=>OT,drawFaceExpressions:()=>kT,drawFaceLandmarks:()=>_T});function DT(e,t){const n=Gr(e,t),r=jr(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 pb(e,t){const n=[],{extractWeights:r,getRemainingWeights:o}=at(e),{extractConvParams:i,extractSeparableConvParams:a,extractReductionBlockParams:s,extractMainBlockParams:c}=DT(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"),m={conv_in:p,reduction_block_0:l,reduction_block_1:h},b={};qt(t,0,1).forEach(v=>{b[`main_block_${v}`]=c(128,`middle_flow/main_block_${v}`)});const y=s(128,256,"exit_flow/reduction_block"),w=a(256,512,"exit_flow/separable_conv"),L={reduction_block:y,separable_conv:w};if(o().length!==0)throw new Error(`weights remaing after extract: ${o().length}`);return{paramMappings:n,params:{entry_flow:m,middle_flow:b,exit_flow:L}}}function FT(e,t){const n=St(e,t),r=$a(n),o=Pr(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 lb(e,t){const n=[],{extractConvParams:r,extractSeparableConvParams:o,extractReductionBlockParams:i,extractMainBlockParams:a}=FT(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={};qt(t,0,1).forEach(w=>{h[`main_block_${w}`]=a(`middle_flow/main_block_${w}`)});const m=i("exit_flow/reduction_block"),b=o("exit_flow/separable_conv"),y={reduction_block:m,separable_conv:b};return st(e,n),{params:{entry_flow:l,middle_flow:h,exit_flow:y},paramMappings:n}}const hb=ee(ot());function ub(e,t,n){return C(ve(e,t.filters,n,"same"),t.bias)}function su(e,t,n=!0){let r=n?se(e):e;return r=rt(r,t.separable_conv0,[1,1]),r=rt(se(r),t.separable_conv1,[1,1]),r=Ie(r,[3,3],[2,2],"same"),r=C(r,ub(e,t.expansion_conv,[2,2])),r}function MT(e,t){let n=rt(se(e),t.separable_conv0,[1,1]);return n=rt(se(n),t.separable_conv1,[1,1]),n=rt(se(n),t.separable_conv2,[1,1]),n=C(n,e),n}class db extends He{constructor(e){super("TinyXception");this._numMainBlocks=e}forwardInput(e){const{params:t}=this;if(!t)throw new Error("TinyXception - load model before inference");return F(()=>{const n=e.toBatchTensor(112,!0),r=[122.782,117.001,104.298],o=bt(n,r).div(k(256));let i=se(ub(o,t.entry_flow.conv_in,[2,2]));return i=su(i,t.entry_flow.reduction_block_0,!1),i=su(i,t.entry_flow.reduction_block_1),qt(this._numMainBlocks,0,1).forEach(a=>{i=MT(i,t.middle_flow[`main_block_${a}`])}),i=su(i,t.exit_flow.reduction_block),i=se(rt(i,t.exit_flow.separable_conv,[1,1])),i})}async forward(e){return this.forwardInput(await hb.toNetInput(e))}getDefaultModelName(){return"tiny_xception_model"}extractParamsFromWeigthMap(e){return lb(e,this._numMainBlocks)}extractParams(e){return pb(e,this._numMainBlocks)}}function mb(e){const t=[],{extractWeights:n,getRemainingWeights:r}=at(e),o=Wa(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 fb(e){const t=[],n=St(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 st(e,t),{params:o,paramMappings:t}}var Dt;(function(e){e.FEMALE="female",e.MALE="male"})(Dt||(Dt={}));const Cs=ee(ot());class ta extends He{constructor(e=new db(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 F(()=>{const n=e instanceof Cs.NetInput?this.faceFeatureExtractor.forwardInput(e):e,r=ht(n,[7,7],[2,2],"valid").as2D(n.shape[0],-1),o=Rs(r,t.fc.age).as1D(),i=Rs(r,t.fc.gender);return{age:o,gender:i}})}forwardInput(e){return F(()=>{const{age:t,gender:n}=this.runNet(e);return{age:t,gender:en(n)}})}async forward(e){return this.forwardInput(await Cs.toNetInput(e))}async predictAgeAndGender(e){const t=await Cs.toNetInput(e),n=await this.forwardInput(t),r=We(n.age),o=We(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,m=h?Dt.MALE:Dt.FEMALE,b=h?l:1-l;return s.dispose(),c.dispose(),{age:p,gender:m,genderProbability:b}}));return n.age.dispose(),n.gender.dispose(),t.isBatchInput?a:a[0]}getDefaultModelName(){return"age_gender_model"}dispose(e=!0){this.faceFeatureExtractor.dispose(e),super.dispose(e)}loadClassifierParams(e){const{params:t,paramMappings:n}=this.extractClassifierParams(e);this._params=t,this._paramMappings=n}extractClassifierParams(e){return mb(e)}extractParamsFromWeigthMap(e){const{featureExtractorMap:t,classifierMap:n}=Pa(e);return this.faceFeatureExtractor.loadFromWeightMap(t),fb(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)}}const au=ee(ot());class Ha extends qa{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 F(()=>{const i=(l,h)=>Ue([Ge([68],l),Ge([68],h)],1).as2D(1,136).as1D(),a=(l,h)=>{const{width:m,height:b}=r[l];return h(m,b)?Math.abs(m-b)/2:0},s=l=>a(l,(h,m)=>h<m),c=l=>a(l,(h,m)=>m<h),p=e.mul(Ge([o,136],t)).sub(Ue(Array.from(Array(o),(l,h)=>i(s(h),c(h))))).div(Ue(Array.from(Array(o),(l,h)=>i(r[h].width,r[h].height))));return p})}forwardInput(e){return F(()=>{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 au.toNetInput(e))}async detectLandmarks(e){const t=await au.toNetInput(e),n=F(()=>We(this.forwardInput(t))),r=await Promise.all(n.map(async(o,i)=>{const a=Array.from(await o.data()),s=a.filter((p,l)=>ka(l)),c=a.filter((p,l)=>!ka(l));return new fr(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 mr extends Ha{constructor(e=new ja()){super("FaceLandmark68Net",e)}getDefaultModelName(){return"face_landmark_68_model"}getClassifierChannelsIn(){return 256}}function gb(e){const t=[],{extractDenseBlock3Params:n}=Ga(e,t),r={dense0:n("dense0",!0),dense1:n("dense1"),dense2:n("dense2")};return st(e,t),{params:r,paramMappings:t}}function bb(e){const t=[],{extractWeights:n,getRemainingWeights:r}=at(e),{extractDenseBlock3Params:o}=Ba(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}}}const wb=ee(ot());class yb extends He{constructor(){super("TinyFaceFeatureExtractor")}forwardInput(e){const{params:t}=this;if(!t)throw new Error("TinyFaceFeatureExtractor - load model before inference");return F(()=>{const n=e.toBatchTensor(112,!0),r=[122.782,117.001,104.298],o=bt(n,r).div(k(255));let i=Ma(o,t.dense0,!0);return i=Ma(i,t.dense1),i=Ma(i,t.dense2),i=ht(i,[14,14],[2,2],"valid"),i})}async forward(e){return this.forwardInput(await wb.toNetInput(e))}getDefaultModelName(){return"face_feature_extractor_tiny_model"}extractParamsFromWeigthMap(e){return gb(e)}extractParams(e){return bb(e)}}class Js extends Ha{constructor(e=new yb()){super("FaceLandmark68TinyNet",e)}getDefaultModelName(){return"face_landmark_68_tiny_model"}getClassifierChannelsIn(){return 128}}class Hu extends mr{}function xb(e,t){return C(S(e,t.weights),t.biases)}function cu(e,t,n,r,o="same"){const{filters:i,bias:a}=t.conv;let s=ve(e,i,n,o);return s=C(s,a),s=xb(s,t.scale),r?se(s):s}function Lb(e,t){return cu(e,t,[1,1],!0)}function pu(e,t){return cu(e,t,[1,1],!1)}function za(e,t){return cu(e,t,[2,2],!0,"valid")}function UT(e,t){function n(s,c,p){const l=e(s),h=l.length/(c*p*p);if(Qh(h))throw new Error(`depth has to be an integer: ${h}, weights.length: ${l.length}, numFilters: ${c}, filterSize: ${p}`);return F(()=>Z(Pt(l,[c,h,p,p]),[2,3,1,0]))}function r(s,c,p,l){const h=n(s,c,p),m=ge(e(c));return t.push({paramPath:`${l}/filters`},{paramPath:`${l}/bias`}),{filters:h,bias:m}}function o(s,c){const p=ge(e(s)),l=ge(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`),m=o(c,`${l}/scale`);return{conv:h,scale:m}}function a(s,c,p,l,h=!1){const m=i((h?.5:1)*s,c,p,`${l}/conv1`),b=i(s,c,p,`${l}/conv2`);return{conv1:m,conv2:b}}return{extractConvLayerParams:i,extractResidualLayerParams:a}}function Sb(e){const{extractWeights:t,getRemainingWeights:n}=at(e),r=[],{extractConvLayerParams:o,extractResidualLayerParams:i}=UT(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"),m=i(36864,64,3,"conv64_2"),b=i(36864,64,3,"conv64_3"),y=i(147456,128,3,"conv128_down",!0),w=i(147456,128,3,"conv128_1"),L=i(147456,128,3,"conv128_2"),v=i(589824,256,3,"conv256_down",!0),A=i(589824,256,3,"conv256_1"),R=i(589824,256,3,"conv256_2"),N=i(589824,256,3,"conv256_down_out"),O=F(()=>Z(ft(t(256*128),[128,256]),[1,0]));if(r.push({paramPath:"fc"}),n().length!==0)throw new Error(`weights remaing after extract: ${n().length}`);const M={conv32_down:a,conv32_1:s,conv32_2:c,conv32_3:p,conv64_down:l,conv64_1:h,conv64_2:m,conv64_3:b,conv128_down:y,conv128_1:w,conv128_2:L,conv256_down:v,conv256_1:A,conv256_2:R,conv256_down_out:N,fc:O};return{params:M,paramMappings:r}}function WT(e,t){const n=St(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 vb(e){const t=[],{extractConvLayerParams:n,extractResidualLayerParams:r}=WT(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"),m=r("conv128_down"),b=r("conv128_1"),y=r("conv128_2"),w=r("conv256_down"),L=r("conv256_1"),v=r("conv256_2"),A=r("conv256_down_out"),R=e.fc;if(t.push({originalPath:"fc",paramPath:"fc"}),!Zh(R))throw new Error(`expected weightMap[fc] to be a Tensor2D, instead have ${R}`);const N={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:m,conv128_1:b,conv128_2:y,conv256_down:w,conv256_1:L,conv256_2:v,conv256_down_out:A,fc:R};return st(e,t),{params:N,paramMappings:t}}function _t(e,t){let n=Lb(e,t.conv1);return n=pu(n,t.conv2),n=C(n,e),n=se(n),n}function Es(e,t){let n=za(e,t.conv1);n=pu(n,t.conv2);let r=ht(e,2,2,"valid");const o=Re(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=Re(s);n=Q([n,c],1);const p=[...n.shape];p[2]=1;const l=Re(p);n=Q([n,l],2)}return r=i?Q([r,o],3):r,n=C(r,n),n=se(n),n}const lu=ee(ot());class dr extends He{constructor(){super("FaceRecognitionNet")}forwardInput(e){const{params:t}=this;if(!t)throw new Error("FaceRecognitionNet - load model before inference");return F(()=>{const n=e.toBatchTensor(150,!0).toFloat(),r=[122.782,117.001,104.298],o=bt(n,r).div(k(256));let i=za(o,t.conv32_down);i=Ie(i,3,2,"valid"),i=_t(i,t.conv32_1),i=_t(i,t.conv32_2),i=_t(i,t.conv32_3),i=Es(i,t.conv64_down),i=_t(i,t.conv64_1),i=_t(i,t.conv64_2),i=_t(i,t.conv64_3),i=Es(i,t.conv128_down),i=_t(i,t.conv128_1),i=_t(i,t.conv128_2),i=Es(i,t.conv256_down),i=_t(i,t.conv256_1),i=_t(i,t.conv256_2),i=Es(i,t.conv256_down_out);const a=i.mean([1,2]),s=Y(a,t.fc);return s})}async forward(e){return this.forwardInput(await lu.toNetInput(e))}async computeFaceDescriptor(e){const t=await lu.toNetInput(e),n=F(()=>We(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 vb(e)}extractParams(e){return Sb(e)}}function qu(e){const t=new dr();return t.extractWeights(e),t}function no(e,t){const n={descriptor:t};return Object.assign({},e,n)}function Pu(e){return typeof e.age=="number"}function ro(e,t){const n={age:t};return Object.assign({},e,n)}function ju(e){return(e.gender===Dt.MALE||e.gender===Dt.FEMALE)&&Br(e.genderProbability)}function eo(e,t,n){const r={gender:t,genderProbability:n};return Object.assign({},e,r)}class vt{async then(e){return e(await this.run())}async run(){throw new Error("ComposableTask - run is not implemented")}}const Ya=ee(ot());async function cr(e,t,n,r,o=({alignedRect:i})=>i){const i=e.map(c=>an(c)?o(c):c.detection),a=r||(t instanceof ne?await Ya.extractFaceTensors(t,i):await Ya.extractFaces(t,i)),s=await n(a);return a.forEach(c=>c instanceof ne&&c.dispose()),s}async function qr(e,t,n,r,o){return cr([e],t,async i=>n(i[0]),r,o)}const Va=e=>typeof e=="number";function mc(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(!Va(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=>Va(t.x)&&Va(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(Va)))throw new Error(`config.meanRgb has to be an array of shape [number, number, number], have: ${JSON.stringify(e.meanRgb)}`)}function Hr(e){return F(()=>{const t=S(e,k(.10000000149011612));return C(se(_(e,t)),t)})}function rn(e,t){return F(()=>{let n=je(e,[[0,0],[1,1],[1,1],[0,0]]);return n=ve(n,t.conv.filters,[1,1],"valid"),n=_(n,t.bn.sub),n=S(n,t.bn.truediv),n=C(n,t.conv.bias),Hr(n)})}function on(e,t){return F(()=>{let n=je(e,[[0,0],[1,1],[1,1],[0,0]]);return n=qn(n,t.depthwise_filter,t.pointwise_filter,[1,1],"valid"),n=C(n,t.bias),Hr(n)})}function BT(e,t){const n=Gr(e,t);function r(a,s){const c=ge(e(a)),p=ge(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=jr(e,t);return{extractConvParams:n,extractConvWithBatchNormParams:o,extractSeparableConvParams:i}}function Ib(e,t,n,r){const{extractWeights:o,getRemainingWeights:i}=at(e),a=[],{extractConvParams:s,extractConvWithBatchNormParams:c,extractSeparableConvParams:p}=BT(o,a);let l;if(t.withSeparableConvs){const[h,m,b,y,w,L,v,A,R]=r,N=t.isFirstLayerConv2d?s(h,m,3,"conv0"):p(h,m,"conv0"),O=p(m,b,"conv1"),M=p(b,y,"conv2"),D=p(y,w,"conv3"),G=p(w,L,"conv4"),$=p(L,v,"conv5"),j=A?p(v,A,"conv6"):void 0,oe=R?p(A,R,"conv7"):void 0,ie=s(R||A||v,5*n,1,"conv8");l={conv0:N,conv1:O,conv2:M,conv3:D,conv4:G,conv5:$,conv6:j,conv7:oe,conv8:ie}}else{const[h,m,b,y,w,L,v,A,R]=r,N=c(h,m,"conv0"),O=c(m,b,"conv1"),M=c(b,y,"conv2"),D=c(y,w,"conv3"),G=c(w,L,"conv4"),$=c(L,v,"conv5"),j=c(v,A,"conv6"),oe=c(A,R,"conv7"),ie=s(R,5*n,1,"conv8");l={conv0:N,conv1:O,conv2:M,conv3:D,conv4:G,conv5:$,conv6:j,conv7:oe,conv8:ie}}if(i().length!==0)throw new Error(`weights remaing after extract: ${i().length}`);return{params:l,paramMappings:a}}function $T(e,t){const n=St(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=Pr(n);return{extractConvParams:o,extractConvWithBatchNormParams:i,extractSeparableConvParams:a}}function Tb(e,t){const n=[],{extractConvParams:r,extractConvWithBatchNormParams:o,extractSeparableConvParams:i}=$T(e,n);let a;if(t.withSeparableConvs){const s=t.filterSizes&&t.filterSizes.length||9;a={conv0:t.isFirstLayerConv2d?r("conv0"):i("conv0"),conv1:i("conv1"),conv2:i("conv2"),conv3:i("conv3"),conv4:i("conv4"),conv5:i("conv5"),conv6:s>7?i("conv6"):void 0,conv7:s>8?i("conv7"):void 0,conv8:r("conv8")}}else a={conv0:o("conv0"),conv1:o("conv1"),conv2:o("conv2"),conv3:o("conv3"),conv4:o("conv4"),conv5:o("conv5"),conv6:o("conv6"),conv7:o("conv7"),conv8:r("conv8")};return st(e,n),{params:a,paramMappings:n}}var fc;(function(e){e[e.XS=224]="XS",e[e.SM=320]="SM",e[e.MD=416]="MD",e[e.LG=608]="LG"})(fc||(fc={}));class gc{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}}const hu=ee(ot());class zr extends He{constructor(e){super("TinyYolov2");mc(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=Ie(n,[2,2],[2,2],"same"),n=rn(n,t.conv1),n=Ie(n,[2,2],[2,2],"same"),n=rn(n,t.conv2),n=Ie(n,[2,2],[2,2],"same"),n=rn(n,t.conv3),n=Ie(n,[2,2],[2,2],"same"),n=rn(n,t.conv4),n=Ie(n,[2,2],[2,2],"same"),n=rn(n,t.conv5),n=Ie(n,[2,2],[1,1],"same"),n=rn(n,t.conv6),n=rn(n,t.conv7),Ua(n,t.conv8,"valid",!1)}runMobilenet(e,t){let n=this.config.isFirstLayerConv2d?Hr(Ua(e,t.conv0,"valid",!1)):on(e,t.conv0);return n=Ie(n,[2,2],[2,2],"same"),n=on(n,t.conv1),n=Ie(n,[2,2],[2,2],"same"),n=on(n,t.conv2),n=Ie(n,[2,2],[2,2],"same"),n=on(n,t.conv3),n=Ie(n,[2,2],[2,2],"same"),n=on(n,t.conv4),n=Ie(n,[2,2],[2,2],"same"),n=on(n,t.conv5),n=Ie(n,[2,2],[1,1],"same"),n=t.conv6?on(n,t.conv6):n,n=t.conv7?on(n,t.conv7):n,Ua(n,t.conv8,"valid",!1)}forwardInput(e,t){const{params:n}=this;if(!n)throw new Error("TinyYolov2 - load model before inference");return F(()=>{let r=e.toBatchTensor(t,!1).toFloat();return r=this.config.meanRgb?bt(r,this.config.meanRgb):r,r=r.div(k(256)),this.config.withSeparableConvs?this.runMobilenet(r,n):this.runTinyYolov2(r,n)})}async forward(e,t){return await this.forwardInput(await hu.toNetInput(e),t)}async detect(e,t={}){const{inputSize:n,scoreThreshold:r}=new gc(t),o=await hu.toNetInput(e),i=await this.forwardInput(o,n),a=F(()=>We(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),m=c.map(w=>this.config.classes[w.label]),b=zs(p.map(w=>w.rescale(n)),l,this.config.iouThreshold,!0),y=b.map(w=>new Tn(l[w],h[w],m[w],p[w],s));return y}getDefaultModelName(){return""}extractParamsFromWeigthMap(e){return Tb(e,this.config)}extractParams(e){const t=this.config.filterSizes||zr.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 Ib(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,m]=F(()=>{const L=e.reshape([c,c,p,this.boxEncodingSize]),v=L.slice([0,0,0,0],[c,c,p,4]),A=L.slice([0,0,0,4],[c,c,p,1]),R=this.withClassScores?en(L.slice([0,0,0,5],[c,c,p,this.config.classes.length]),3):k(0);return[v,A,R]}),b=[],y=await h.array(),w=await l.array();for(let L=0;L<c;L++)for(let v=0;v<c;v++)for(let A=0;A<p;A++){const R=ur(y[L][v][A][0]);if(!n||R>n){const N=(v+ur(w[L][v][A][0]))/c*a,O=(L+ur(w[L][v][A][1]))/c*s,M=Math.exp(w[L][v][A][2])*this.config.anchors[A].x/c*a,D=Math.exp(w[L][v][A][3])*this.config.anchors[A].y/c*s,G=N-M/2,$=O-D/2,j={row:L,col:v,anchor:A},{classScore:oe,label:ie}=this.withClassScores?await this.extractPredictedClass(m,j):{classScore:1,label:0};b.push({box:new gr(G,$,G+M,$+D),score:R,classScore:R*oe,label:ie,...j})}}return l.dispose(),h.dispose(),m.dispose(),b}async extractPredictedClass(e,t){const{row:n,col:r,anchor:o}=t,i=await e.array();return Array(this.config.classes.length).fill(0).map((a,s)=>i[n][r][o][s]).map((a,s)=>({classScore:a,label:s})).reduce((a,s)=>a.classScore>s.classScore?a:s)}}zr.DEFAULT_FILTER_SIZES=[3,16,32,64,128,256,512,1024,1024];const Ab=.4,Nb=[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)],Rb=[117.001,114.697,97.404];class vn extends zr{constructor(){const e={withSeparableConvs:!0,iouThreshold:Ab,classes:["face"],anchors:Nb,meanRgb:Rb,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 ye(r.score,r.relativeBox,{width:r.imageWidth,height:r.imageHeight}))}getDefaultModelName(){return"tiny_face_detector_model"}extractParamsFromWeigthMap(e){return super.extractParamsFromWeigthMap(e)}}const Cb=.4,Eb=[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)],Ob=[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)],kb=[117.001,114.697,97.404],_b="tiny_yolov2_model",Db="tiny_yolov2_separable_conv_model";class dc extends zr{constructor(e=!0){const t=Object.assign({},{withSeparableConvs:e,iouThreshold:Cb,classes:["face"]},e?{anchors:Ob,meanRgb:kb}:{anchors:Eb,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 ye(r.score,r.relativeBox,{width:r.imageWidth,height:r.imageHeight}))}getDefaultModelName(){return this.withSeparableConvs?Db:_b}extractParamsFromWeigthMap(e){return super.extractParamsFromWeigthMap(e)}}const Fb=ee($s()),le={tinyFaceDetector:new vn(),tinyYolov2:new Fb.TinyYolov2(),faceLandmark68Net:new mr(),faceLandmark68TinyNet:new Js(),faceRecognitionNet:new dr(),faceExpressionNet:new Zs(),ageGenderNet:new ta()},pw=(e,t)=>le.tinyFaceDetector.locateFaces(e,t),Fu=e=>le.faceLandmark68Net.detectLandmarks(e),lw=e=>le.faceLandmark68TinyNet.detectLandmarks(e),hw=e=>le.faceRecognitionNet.computeFaceDescriptor(e),uw=e=>le.faceExpressionNet.predictExpressions(e),dw=e=>le.ageGenderNet.predictAgeAndGender(e),Mu=e=>le.tinyFaceDetector.load(e),mw=e=>le.tinyYolov2.load(e),fw=e=>le.faceLandmark68Net.load(e),gw=e=>le.faceLandmark68TinyNet.load(e),bw=e=>le.faceRecognitionNet.load(e),ww=e=>le.faceExpressionNet.load(e),yw=e=>le.ageGenderNet.load(e),xw=Mu,Lw=vn,Sw=Fu;class Mb extends vt{constructor(e,t,n){super();this.parentTask=e,this.input=t,this.extractedFaces=n}}class _s extends Mb{async run(){const e=await this.parentTask,t=await cr(e,this.input,async n=>await Promise.all(n.map(r=>le.faceExpressionNet.predictExpressions(r))),this.extractedFaces);return e.map((n,r)=>to(n,t[r]))}withAgeAndGender(){return new Os(this,this.input)}}class Ds extends Mb{async run(){const e=await this.parentTask;if(!e)return;const t=await qr(e,this.input,n=>le.faceExpressionNet.predictExpressions(n),this.extractedFaces);return to(e,t)}withAgeAndGender(){return new ks(this,this.input)}}class Kr extends _s{withAgeAndGender(){return new Yr(this,this.input)}withFaceDescriptors(){return new Ln(this,this.input)}}class Jr extends Ds{withAgeAndGender(){return new Vr(this,this.input)}withFaceDescriptor(){return new Sn(this,this.input)}}class Ub extends vt{constructor(e,t,n){super();this.parentTask=e,this.input=t,this.extractedFaces=n}}class Os extends Ub{async run(){const e=await this.parentTask,t=await cr(e,this.input,async n=>await Promise.all(n.map(r=>le.ageGenderNet.predictAgeAndGender(r))),this.extractedFaces);return e.map((n,r)=>{const{age:o,gender:i,genderProbability:a}=t[r];return ro(eo(n,i,a),o)})}withFaceExpressions(){return new _s(this,this.input)}}class ks extends Ub{async run(){const e=await this.parentTask;if(!e)return;const{age:t,gender:n,genderProbability:r}=await qr(e,this.input,o=>le.ageGenderNet.predictAgeAndGender(o),this.extractedFaces);return ro(eo(e,n,r),t)}withFaceExpressions(){return new Ds(this,this.input)}}class Yr extends Os{withFaceExpressions(){return new Kr(this,this.input)}withFaceDescriptors(){return new Ln(this,this.input)}}class Vr extends ks{withFaceExpressions(){return new Jr(this,this.input)}withFaceDescriptor(){return new Sn(this,this.input)}}class Sc extends vt{constructor(e,t){super();this.parentTask=e,this.input=t}}class Ln extends Sc{async run(){const e=await this.parentTask,t=await cr(e,this.input,n=>Promise.all(n.map(r=>le.faceRecognitionNet.computeFaceDescriptor(r))),null,n=>n.landmarks.align(null,{useDlibAlignment:!0}));return t.map((n,r)=>no(e[r],n))}withFaceExpressions(){return new Kr(this,this.input)}withAgeAndGender(){return new Yr(this,this.input)}}class Sn extends Sc{async run(){const e=await this.parentTask;if(!e)return;const t=await qr(e,this.input,n=>le.faceRecognitionNet.computeFaceDescriptor(n),null,n=>n.landmarks.align(null,{useDlibAlignment:!0}));return no(e,t)}withFaceExpressions(){return new Jr(this,this.input)}withAgeAndGender(){return new Vr(this,this.input)}}const Wb=ee($s());class sn extends Wb.TinyYolov2Options{constructor(){super(...arguments);this._name="TinyFaceDetectorOptions"}}const Xr=ee(ot());class yc extends vt{constructor(e,t,n){super();this.parentTask=e,this.input=t,this.useTinyLandmarkNet=n}get landmarkNet(){return this.useTinyLandmarkNet?le.faceLandmark68TinyNet:le.faceLandmark68Net}}class xc extends yc{async run(){const e=await this.parentTask,t=e.map(o=>o.detection),n=this.input instanceof ne?await Xr.extractFaceTensors(this.input,t):await Xr.extractFaces(this.input,t),r=await Promise.all(n.map(o=>this.landmarkNet.detectLandmarks(o)));return n.forEach(o=>o instanceof ne&&o.dispose()),e.map((o,i)=>In(o,r[i]))}withFaceExpressions(){return new Kr(this,this.input)}withAgeAndGender(){return new Yr(this,this.input)}withFaceDescriptors(){return new Ln(this,this.input)}}class Lc extends yc{async run(){const e=await this.parentTask;if(!e)return;const{detection:t}=e,n=this.input instanceof ne?await Xr.extractFaceTensors(this.input,[t]):await Xr.extractFaces(this.input,[t]),r=await this.landmarkNet.detectLandmarks(n[0]);return n.forEach(o=>o instanceof ne&&o.dispose()),In(e,r)}withFaceExpressions(){return new Jr(this,this.input)}withAgeAndGender(){return new Vr(this,this.input)}withFaceDescriptor(){return new Sn(this,this.input)}}class bc extends vt{constructor(e,t=new sn()){super();this.input=e,this.options=t}}class Gs extends bc{async run(){const{input:e,options:t}=this,n=t instanceof sn?r=>le.tinyFaceDetector.locateFaces(r,t):null;if(!n)throw new Error("detectFaces - expected options to be instance of TinyFaceDetectorOptions | SsdMobilenetv1Options | MtcnnOptions | TinyYolov2Options");return n(e)}runAndExtendWithFaceDetections(){return new Promise(async e=>{const t=await this.run();return e(t.map(n=>cn({},n)))})}withFaceLandmarks(e=!1){return new xc(this.runAndExtendWithFaceDetections(),this.input,e)}withFaceExpressions(){return new _s(this.runAndExtendWithFaceDetections(),this.input)}withAgeAndGender(){return new Os(this.runAndExtendWithFaceDetections(),this.input)}}class wc extends bc{async run(){const e=await new Gs(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?cn({},t):void 0)})}withFaceLandmarks(e=!1){return new Lc(this.runAndExtendWithFaceDetection(),this.input,e)}withFaceExpressions(){return new Ds(this.runAndExtendWithFaceDetection(),this.input)}withAgeAndGender(){return new ks(this.runAndExtendWithFaceDetection(),this.input)}}function vw(e,t=new sn()){return new wc(e,t)}function Iw(e,t=new sn()){return new Gs(e,t)}function Qs(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 Uu{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 ln)return i;if(i instanceof Float32Array)return new ln(o(),[i]);if(i.descriptor&&i.descriptor instanceof Float32Array)return new ln(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=>Qs(n,e)).reduce((n,r)=>n+r,0)/(t.length||1)}matchDescriptor(e){return this.labeledDescriptors.map(({descriptors:t,label:n})=>new io(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 io("unknown",t.distance)}toJSON(){return{distanceThreshold:this.distanceThreshold,labeledDescriptors:this.labeledDescriptors.map(e=>e.toJSON())}}static fromJSON(e){const t=e.labeledDescriptors.map(n=>ln.fromJSON(n));return new Uu(t,e.distanceThreshold)}}function Bu(e){const t=new vn();return t.extractWeights(e),t}function vc(e,t){const{width:n,height:r}=new Qe(t.width,t.height);if(n<=0||r<=0)throw new Error(`resizeResults - invalid dimensions: ${JSON.stringify({width:n,height:r})}`);if(Array.isArray(e))return e.map(o=>vc(o,{width:n,height:r}));if(an(e)){const o=e.detection.forSize(n,r),i=e.unshiftedLandmarks.forSize(o.box.width,o.box.height);return In(cn(e,o),i)}return It(e)?cn(e,e.detection.forSize(n,r)):e instanceof ct||e instanceof ye?e.forSize(n,r):e}Vu();})();
/**
* @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