UNPKG

@vladmandic/face-api

Version:

JavaScript module for Face Detection and Face Recognition Using Tensorflow/JS

5 lines 1.12 MB
var Mm=Object.defineProperty,LJ=Object.prototype.hasOwnProperty,ES=(r,l)=>()=>(l||(l={exports:{}},r(l.exports,l)),l.exports),XC=r=>Mm(r,"__esModule",{value:!0}),Pm=(r,l)=>{XC(r);for(var u in l)Mm(r,u,{get:l[u],enumerable:!0})},SJ=(r,l)=>{if(XC(r),typeof l=="object"||typeof l=="function")for(let u in l)!LJ.call(r,u)&&u!=="default"&&Mm(r,u,{get:()=>l[u],enumerable:!0});return r},Je=r=>r&&r.__esModule?r:SJ(Mm({},"default",{value:r,enumerable:!0}),r);var ZC=ES((Ac,JC)=>{"use strict";var IJ=function(){if(typeof self!="undefined")return self;if(typeof window!="undefined")return window;if(typeof mr!="undefined")return mr;throw new Error("unable to locate global object")},mr=IJ();JC.exports=Ac=mr.fetch;mr.fetch&&(Ac.default=mr.fetch.bind(mr));Ac.Headers=mr.Headers;Ac.Request=mr.Request;Ac.Response=mr.Response});var Ze=ES((zm,QC)=>{(function(r,l){typeof zm=="object"&&typeof QC!="undefined"?l(zm):typeof define=="function"&&define.amd?define(["exports"],l):(r=r||self,l(r.tf=r.tf||{}))})(zm,function(r){"use strict";const l=1e-7,u=1e-4;class p{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 y{time(e){return g("time")}read(e){return g("read")}readSync(e){return g("readSync")}numDataIds(){return g("numDataIds")}disposeData(e){return g("disposeData")}write(e,t,n){return g("write")}move(e,t,n,s){return g("move")}memory(){return g("memory")}floatPrecision(){return g("floatPrecision")}epsilon(){return this.floatPrecision()===32?l:u}batchMatMul(e,t,n,s){return g("batchMatMul")}fusedBatchMatMul({a:e,b:t,transposeA:n,transposeB:s,bias:i,activation:o,preluActivationWeights:a}){return g("fusedBatchMatMul")}slice(e,t,n){return g("slice")}stridedSlice(e,t,n,s){return g("stridedSlice")}unstack(e,t){return g("unstack")}reverse(e,t){return g("reverse")}concat(e,t){return g("concat")}neg(e){return g("neg")}add(e,t){return g("add")}addN(e){return g("addN")}subtract(e,t){return g("subtract")}multiply(e,t){return g("multiply")}realDivide(e,t){return g("realDivide")}floorDiv(e,t){return g("floorDiv")}sum(e,t){return g("sum")}prod(e,t){return g("prod")}unsortedSegmentSum(e,t,n){return g("unsortedSegmentSum")}argMin(e,t){return g("argMin")}argMax(e,t){return g("argMax")}equal(e,t){return g("equal")}notEqual(e,t){return g("notEqual")}less(e,t){return g("less")}lessEqual(e,t){return g("lessEqual")}greater(e,t){return g("greater")}greaterEqual(e,t){return g("greaterEqual")}logicalNot(e){return g("logicalNot")}logicalAnd(e,t){return g("logicalAnd")}logicalOr(e,t){return g("logicalOr")}where(e){return g("where")}select(e,t,n){return g("select")}topk(e,t,n){return g("topk")}min(e,t){return g("min")}minimum(e,t){return g("minimum")}mod(e,t){return g("mod")}max(e,t){return g("max")}maximum(e,t){return g("maximum")}all(e,t){return g("all")}any(e,t){return g("any")}squaredDifference(e,t){return g("squaredDifference")}ceil(e){return g("ceil")}floor(e){return g("floor")}round(e){return g("round")}sign(e){return g("sign")}isNaN(e){return g("isNaN")}isInf(e){return g("isInf")}isFinite(e){return g("isFinite")}pow(e,t){return g("pow")}exp(e){return g("exp")}expm1(e){return g("expm1")}softmax(e,t){return g("softmax")}log(e){return g("log")}log1p(e){return g("log1p")}sqrt(e){return g("sqrt")}rsqrt(e){return g("rsqrt")}square(e){return g("square")}reciprocal(e){return g("reciprocal")}relu(e){return g("relu")}relu6(e){return g("relu6")}prelu(e,t){return g("prelu")}elu(e){return g("elu")}eluDer(e,t){return g("eluDer")}selu(e){return g("selu")}int(e){return g("int")}clip(e,t,n){return g("clip")}abs(e){return g("abs")}complexAbs(e){return g("complexAbs")}sigmoid(e){return g("sigmoid")}softplus(e){return g("softplus")}sin(e){return g("sin")}cos(e){return g("cos")}tan(e){return g("tan")}asin(e){return g("asin")}acos(e){return g("acos")}atan(e){return g("atan")}atan2(e,t){return g("atan2")}sinh(e){return g("sinh")}cosh(e){return g("cosh")}tanh(e){return g("tanh")}asinh(e){return g("asinh")}acosh(e){return g("acosh")}atanh(e){return g("atanh")}erf(e){return g("erf")}step(e,t){return g("step")}fusedConv2d({input:e,filter:t,convInfo:n,bias:s,activation:i,preluActivationWeights:o}){return g("fusedConv2d")}conv2d(e,t,n){return g("conv2d")}conv2dDerInput(e,t,n){return g("conv2dDerInput")}conv2dDerFilter(e,t,n){return g("conv2dDerFilter")}fusedDepthwiseConv2D({input:e,filter:t,convInfo:n,bias:s,activation:i,preluActivationWeights:o}){return g("fusedDepthwiseConv2D")}depthwiseConv2D(e,t,n){return g("depthwiseConv2D")}depthwiseConv2DDerInput(e,t,n){return g("depthwiseConv2DDerInput")}depthwiseConv2DDerFilter(e,t,n){return g("depthwiseConv2DDerFilter")}conv3d(e,t,n){return g("conv3d")}conv3dDerInput(e,t,n){return g("conv3dDerInput")}conv3dDerFilter(e,t,n){return g("conv3dDerFilter")}maxPool(e,t){return g("maxPool")}maxPoolBackprop(e,t,n,s){return g("maxPoolBackprop")}avgPool(e,t){return g("avgPool")}avgPoolBackprop(e,t,n){return g("avgPoolBackprop")}avgPool3d(e,t){return g("avgPool3d")}avgPool3dBackprop(e,t,n){return g("avgPool3dBackprop")}maxPool3d(e,t){return g("maxPool3d")}maxPool3dBackprop(e,t,n,s){return g("maxPool3dBackprop")}reshape(e,t){return g("reshape")}cast(e,t){return g("cast")}tile(e,t){return g("tile")}pad(e,t,n){return g("pad")}transpose(e,t){return g("transpose")}gather(e,t,n){return g("gather")}gatherND(e,t){return g("gatherND")}scatterND(e,t,n){return g("scatterND")}batchToSpaceND(e,t,n){return g("batchToSpaceND")}spaceToBatchND(e,t,n){return g("spaceToBatchND")}resizeBilinear(e,t,n,s){return g("resizeBilinear")}resizeBilinearBackprop(e,t,n){return g("resizeBilinearBackprop")}resizeNearestNeighbor(e,t,n,s){return g("resizeNearestNeighbor")}resizeNearestNeighborBackprop(e,t,n){return g("resizeNearestNeighborBackprop")}batchNorm(e,t,n,s,i,o){return g("batchNorm")}localResponseNormalization4D(e,t,n,s,i){return g("localResponseNormalization4D")}LRNGrad(e,t,n,s,i,o,a){return g("LRNGrad")}multinomial(e,t,n,s){return g("multinomial")}oneHot(e,t,n,s){return g("oneHot")}cumsum(e,t,n,s){return g("cumsum")}nonMaxSuppression(e,t,n,s,i){return g("nonMaxSuppression")}fft(e){return g("fft")}ifft(e){return g("ifft")}complex(e,t){return g("complex")}real(e){return g("real")}imag(e){return g("imag")}cropAndResize(e,t,n,s,i,o){return g("cropAndResize")}depthToSpace(e,t,n){return g("depthToSpace")}split(e,t,n){return g("split")}sparseToDense(e,t,n,s){return g("sparseToDense")}diag(e){return g("diag")}fill(e,t,n){return g("fill")}onesLike(e){return g("onesLike")}zerosLike(e){return g("zerosLike")}linspace(e,t,n){return g("linspace")}dispose(){return g("dispose")}}function g(e){throw new Error(`'${e}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}function I(e){let t=e.length,n=0,s=0;for(;t>0;)s=Math.random()*t|0,t--,n=e[t],e[t]=e[s],e[s]=n}function S(e,t,n){return Math.max(e,Math.min(t,n))}function T(e){return e%2===0?e:e+1}function C(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t}function D(e,t){const n=Math.random();return t*n+(1-n)*e}function _(e,t){let n=0;for(let s=0;s<e.length;s++){const i=Number(e[s])-Number(t[s]);n+=i*i}return n}function A(e,t){if(!e)throw new Error(typeof t=="string"?t:t())}function B(e,t,n=""){A(ae(e,t),()=>n+` Shapes ${e} and ${t} must match`)}function ne(e){A(e!=null,()=>"The input to the tensor constructor must be a non-null value.")}function te(e,t=[],n=!1){if(t==null&&(t=[]),Array.isArray(e)||hn(e)&&!n)for(let s=0;s<e.length;++s)te(e[s],t,n);else t.push(e);return t}function P(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 ge(e){return e.length===0}function ae(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 Le(e){return e%1===0}function ve(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 Ve(e){const t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function at(e){const t=new Uint32Array(e);for(let n=0;n<e;++n)t[n]=n;return I(t),t}function pt(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function $t(e,t=s=>0,n){return new Promise((s,i)=>{let o=0;const a=()=>{if(e()){s();return}o++;const c=t(o);if(n!=null&&o>=n){i();return}setTimeout(a,c)};a()})}function Vt(e,t){let n=1,s=-1;for(let o=0;o<e.length;++o)if(e[o]>=0)n*=e[o];else if(e[o]===-1){if(s!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${s} and dim ${o}`);s=o}else if(e[o]<0)throw Error(`Shapes can not be < 0. Found ${e[o]} at dim ${o}`);if(s===-1){if(t>0&&t!==n)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(n===0)throw Error(`Cannot infer the missing size in [${e}] when there are 0 elements`);if(t%n!==0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${n}`);const i=e.slice();return i[s]=t/n,i}function qe(e,t){const n=t.length;return e=e==null?t.map((s,i)=>i):[].concat(e),A(e.every(s=>s>=-n&&s<n),()=>`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`),A(e.every(s=>Le(s)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(s=>s<0?n+s:s)}function ln(e,t){const n=[],s=[],i=t!=null&&Array.isArray(t)&&t.length===0,o=t==null||i?null:qe(t,e).sort();let a=0;for(let c=0;c<e.length;++c){if(o!=null){if(o[a]===c&&e[c]!==1)throw new Error(`Can't squeeze axis ${c} since its dim '${e[c]}' is not 1`);(o[a]==null||o[a]>c)&&e[c]===1&&(n.push(e[c]),s.push(c)),o[a]<=c&&a++}e[c]!==1&&(n.push(e[c]),s.push(c))}return{newShape:n,keptDims:s}}function bt(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 ws(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 Nr(e,t){for(let n=0;n<e.length;n++){const s=e[n];if(isNaN(s)||!isFinite(s))throw Error(`A tensor of type ${t} being uploaded contains ${s}.`)}}function Cr(e){return e==="bool"||e==="complex64"||e==="float32"||e==="int32"||e==="string"}function ba(e,t){return t==="complex64"||(t==="float32"&&e!=="complex64"||t==="int32"&&e!=="float32"&&e!=="complex64")?!1:!(t==="bool"&&e==="bool")}function hn(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array}function Bg(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 Ix(e){if(e==null)return 0;let t=0;return e.forEach(n=>t+=n.length),t}function Yi(e){return typeof e=="string"||e instanceof String}function xx(e){return typeof e=="boolean"}function Qu(e){return typeof e=="number"}function wa(e){return Array.isArray(e)?wa(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array?"int32":Qu(e)?"float32":Yi(e)?"string":xx(e)?"bool":"float32"}function Rr(e){return!!(e&&e.constructor&&e.call&&e.apply)}function ed(e,t){for(let n=t;n<e;++n)if(e%n===0)return n;return e}function je(e){const t=e.length;if(t<2)return[];const n=new Array(t-1);n[t-2]=e[t-1];for(let s=t-3;s>=0;--s)n[s]=n[s+1]*e[s+1];return n}function Tx(e,t,n){const s=new Array;if(t.length===1){const i=t[0];for(let o=0;o<i;o++)s[o]=n[e+o]}else{const i=t[0],o=t.slice(1),a=o.reduce((c,h)=>c*h);for(let c=0;c<i;c++)s[c]=Tx(e+c*a,o,n)}return s}function Ls(e,t){if(e.length===0)return t[0];const n=e.reduce((s,i)=>s*i);if(n===0)return[];if(n!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}.`);return Tx(0,e,t)}function Mg(e,t){const n=La(e,t);for(let s=0;s<n.length;s++)n[s]=1;return n}function La(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 Pg(e,t){const n=e.reduce((s,i)=>s*i,1);if(t==null||t==="float32")return Ls(e,new Float32Array(n));if(t==="int32")return Ls(e,new Int32Array(n));if(t==="bool")return Ls(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function zg(e){e.forEach(t=>{A(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function _s(e,t,n){if(t===0)return 0;if(t===1)return e[0];let s=e[e.length-1];for(let i=0;i<e.length-1;++i)s+=n[i]*e[i];return s}function yo(e,t,n){if(t===0)return[];if(t===1)return[e];const s=new Array(t);for(let i=0;i<s.length-1;++i)s[i]=Math.floor(e/n[i]),e-=s[i]*n[i];return s[s.length-1]=e,s}function bo(e){return e&&e.then&&typeof e.then=="function"}const Ax="tfjsflags";class vx{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 s=this.urlFlags[e];console.warn(`Setting feature override from URL ${e}: ${s}.`),this.set(e,s)}}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(bo(t))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=zD(this.global.location.search);if(Ax in e){const t=e[Ax].split(",");t.forEach(n=>{const[s,i]=n.split(":");this.urlFlags[s]=GD(s,i)})}}}function zD(e){const t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(n,...s)=>(VD(t,s[0],s[1]),s.join("="))),t}function VD(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}function GD(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 oe(){return r.ENV}r.ENV=null;function YD(e){r.ENV=e}let Vg;function Nx(){if(Vg==null){let e;if(typeof window!="undefined")e=window;else if(typeof global!="undefined")e=global;else if(typeof process!="undefined")e=process;else if(typeof self!="undefined")e=self;else throw new Error("Could not find a global object");Vg=e}return Vg}function HD(){const e=Nx();return e._tfGlobals==null&&(e._tfGlobals=new Map),e._tfGlobals}function Cx(e,t){const n=HD();if(n.has(e))return n.get(e);{const s=t();return n.set(e,s),n.get(e)}}const td="Abs",ol="Acos",al="Acosh",wo="Add",Gg="AddN",Rx="All",Ox="Any",Yg="ArgMax",Hg="ArgMin",cl="Asin",ll="Asinh",hl="Atan",ul="Atanh",nd="Atan2",dl="AvgPool",sd="AvgPoolBackprop",qg="AvgPool3D",Ex="AvgPool3DBackprop",id="BatchMatMul",jg="BatchToSpaceND",Kg="BroadcastTo",Sa="Cast",pl="Ceil",ml="ClipByValue",rd="Complex",fl="Concat",od="Conv2D",Xg="Conv2DBackpropFilter",ad="Conv2DBackpropInput",cd="Conv3D",Jg="Conv3DBackpropFilterV2",Zg="Conv3DBackpropInputV2",Ia="Cos",gl="Cosh",Qg="Cumsum",Dx="CropAndResize",kx="DepthToSpace",ld="DepthwiseConv2dNative",ey="DepthwiseConv2dNativeBackpropFilter",ty="DepthwiseConv2dNativeBackpropInput",Fx="Diag",hd="Dilation2D",ud="Dilation2DBackpropInput",dd="Dilation2DBackpropFilter",xa="Div",yl="Elu",_x="EluGrad",bl="Erf",Wx="Equal",wl="Exp",Ll="Expm1",pd="FFT",ny="Fill",md="FlipLeftRight",Sl="Floor",sy="FloorDiv",Il="FusedBatchNorm",iy="GatherV2",$x="GatherNd",Ux="Greater",ry="GreaterEqual",xl="Identity",fd="IFFT",gd="Imag",Tl="IsFinite",Al="IsInf",vl="IsNan",Bx="Less",Mx="LessEqual",Px="LinSpace",Nl="Log",Cl="Log1p",zx="LogicalAnd",yd="LogicalNot",Vx="LogicalOr",oy="LogSoftmax",ay="LRN",Gx="LRNBackprop",Rl="Max",cy="Maximum",Ol="MaxPool",bd="MaxPoolBackprop",ly="MaxPool3D",Yx="MaxPool3DBackprop",wd="MaxPoolWithArgmax",hy="Mean",uy="Min",dy="Minimum",El="MirrorPad",py="Mod",Ta="Multiply",my="Negate",Dl="NotEqual",fy="NonMaxSuppressionV3",Ld="NonMaxSuppressionV4",Sd="NonMaxSuppressionV5",gy="OnesLike",yy="OneHot",Id="PadV2",qD="Pool",by="Pow",xd="Prelu",Hx="Prod",qx="Range",Td="Real",kl="Reciprocal",Fl="Relu",_l="Reshape",wy="ResizeNearestNeighbor",jx="ResizeNearestNeighborGrad",Ly="ResizeBilinear",Kx="ResizeBilinearGrad",Wl="Relu6",Sy="Reverse",$l="Round",Ul="Rsqrt",Xx="ScatterNd",Iy="SelectV2",Bl="Selu",Ad="Slice",Aa="Sin",Ml="Sinh",Pl="Sign",zl="Sigmoid",Vl="Softplus",Gl="Sqrt",xy="Sum",vd="SpaceToBatchND",Ty="SplitV",Ay="Softmax",va="SquaredDifference",Nd="Square",Na="Sub",Jx="SparseToDense",Zx="StridedSlice",Ca="Tan",Yl="Tanh",vy="Tile",Qx="TopK",Hl="Transpose",Cd="Unique",Ny="Unpack",Cy="UnsortedSegmentSum",Ry="ZerosLike",ql="Step",Rd="FromPixels",Od="RotateWithOffset",Ed="_FusedMatMul",Dd="FusedConv2D",kd="FusedDepthwiseConv2D";const Ra=Cx("kernelRegistry",()=>new Map),jl=Cx("gradRegistry",()=>new Map);function Oy(e,t){const n=Dy(e,t);return Ra.get(n)}function Ey(e){return jl.get(e)}function Fd(e){const t=Ra.entries(),n=[];for(;;){const{done:s,value:i}=t.next();if(s)break;const[o,a]=i,[c]=o.split("_");c===e&&n.push(a)}return n}function _d(e){const{kernelName:t,backendName:n}=e,s=Dy(t,n);Ra.has(s)&&console.warn(`The kernel '${t}' for backend '${n}' is already registered`),Ra.set(s,e)}function eT(e){const{kernelName:t}=e;jl.has(t)&&(oe().getBool("DEBUG")&&console.warn(`Overriding the gradient for '${t}'`)),jl.set(t,e)}function jD(e,t){const n=Dy(e,t);if(!Ra.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);Ra.delete(n)}function KD(e){if(!jl.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);jl.delete(e)}function XD(e,t){const n=Fd(e);n.forEach(s=>{const i=Object.assign({},s,{backendName:t});_d(i)})}function Dy(e,t){return`${t}_${e}`}function tT(e,t){return t==="string"?Wd(e):Or([e],t)}function JD(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function Or(e,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=te(e)),oe().getBool("DEBUG")&&Nr(e,t),JD(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 s=0;s<n.length;++s)Math.round(e[s])!==0&&(n[s]=1);return n}else throw new Error(`Unknown data type ${t}`)}function jn(){return oe().platform.now()}function nT(e,t){return oe().platform.fetch(e,t)}function Wd(e,t="utf-8"){return t=t||"utf-8",oe().platform.encode(e,t)}function Kl(e,t="utf-8"){return t=t||"utf-8",oe().platform.decode(e,t)}var ZD=Object.freeze({__proto__:null,createScalarValue:tT,toTypedArray:Or,now:jn,fetch:nT,encodeString:Wd,decodeString:Kl,shuffle:I,clamp:S,nearestLargerEven:T,sum:C,randUniform:D,distSquared:_,assert:A,assertShapesMatch:B,assertNonNull:ne,flatten:te,sizeFromShape:P,isScalarShape:ge,arraysEqual:ae,isInt:Le,tanh:ve,sizeToSquarishShape:Ve,createShuffledIndices:at,rightPad:pt,repeatedTry:$t,inferFromImplicitShape:Vt,parseAxisParam:qe,squeezeShape:ln,getTypedArrayFromDType:bt,getArrayFromDType:ws,checkConversionForErrors:Nr,isValidDtype:Cr,hasEncodingLoss:ba,isTypedArray:hn,bytesPerElement:Bg,bytesFromStringArray:Ix,isString:Yi,isBoolean:xx,isNumber:Qu,inferDtype:wa,isFunction:Rr,nearestDivisor:ed,computeStrides:je,toNestedArray:Ls,makeOnesTypedArray:Mg,makeZerosTypedArray:La,makeZerosNestedTypedArray:Pg,assertNonNegativeIntegerDimensions:zg,locToIndex:_s,indexToLoc:yo,isPromise:bo});class QD{constructor(e,t){this.backendTimer=e,this.logger=t,t==null&&(this.logger=new tk)}profileKernel(e,t,n){let s;const i=()=>{s=n()},o=this.backendTimer.time(i);for(let c=0;c<s.length;c++){const h=s[c];h.data().then(d=>{ek(d,h.dtype,e)})}const a={kernelName:e,outputs:s,inputs:t,timeMs:o.then(c=>c.kernelMs),extraInfo:o.then(c=>c.getExtraProfileInfo!=null?c.getExtraProfileInfo():"")};return a}logKernelProfile(e){const{kernelName:t,outputs:n,timeMs:s,inputs:i,extraInfo:o}=e;n.forEach(a=>{Promise.all([a.data(),s,o]).then(c=>{this.logger.logKernelProfile(t,a,c[0],c[1],i,c[2])})})}}function ek(e,t,n){if(t!=="float32")return!1;for(let s=0;s<e.length;s++){const i=e[s];if(isNaN(i)||!isFinite(i))return console.warn(`Found ${i} in the result of '${n}'`),!0}return!1}class tk{logKernelProfile(e,t,n,s,i,o){const a=typeof s=="number"?pt(`${s}ms`,9):s.error,c=pt(e,25),h=t.rank,d=t.size,m=pt(t.shape.toString(),14);let f="";for(const b in i){const w=i[b];if(w!=null){const L=w.shape||t.shape,x=L.length;f+=`${b}: ${x}D ${x>0?L:""} `}}console.log(`%c${c} %c${a} %c${h}D ${m} %c${d} %c${f} %c${o}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}function nk(e,t,n){const s={},i={};for(let h=0;h<t.length;h++)s[t[h].id]=!0;for(let h=0;h<e.length;h++){const d=e[h],m=d.inputs;for(const f in m){const b=m[f];let w=!1;for(let L=0;L<t.length;L++)if(s[b.id]){d.outputs.forEach(x=>s[x.id]=!0),w=!0,i[d.id]=!0;break}if(w)break}}const o={};o[n.id]=!0;const a={};for(let h=e.length-1;h>=0;h--){const d=e[h],m=d.inputs;for(let f=0;f<d.outputs.length;f++)if(o[d.outputs[f].id]){for(const b in m)o[m[b].id]=!0,a[d.id]=!0;break}}const c=[];for(let h=0;h<e.length;h++){const d=e[h];if(i[d.id]&&a[d.id]){const m={};for(const b in d.inputs){const w=d.inputs[b];s[w.id]&&(m[b]=w)}const f=Object.assign({},d);f.inputs=m,f.outputs=d.outputs,c.push(f)}}return c}function sk(e,t,n,s){for(let i=t.length-1;i>=0;i--){const o=t[i],a=[];if(o.outputs.forEach(h=>{const d=e[h.id];d!=null?a.push(d):a.push(null)}),o.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${o.kernelName}.`);const c=o.gradient(a);for(const h in o.inputs){if(!(h in c))throw new Error(`Cannot backprop through input ${h}. Available gradients found: ${Object.keys(c)}.`);const d=n(()=>c[h]());if(d.dtype!=="float32")throw new Error(`Error in gradient for op ${o.kernelName}. The gradient of input ${h} must have 'float32' dtype, but has '${d.dtype}'`);const m=o.inputs[h];if(!ae(d.shape,m.shape))throw new Error(`Error in gradient for op ${o.kernelName}. The gradient of input '${h}' has shape '${d.shape}', which does not match the shape of the input '${m.shape}'`);if(e[m.id]==null)e[m.id]=d;else{const f=e[m.id];e[m.id]=s(f,d),f.dispose()}}}}const sT=20,Xl=3,ky=7;function ik(e,t,n,s){const i=je(t),o=rk(e,t,n,i),a=t.length,c=$d(e,t,n,i,o),h=["Tensor"];return s&&(h.push(` dtype: ${n}`),h.push(` rank: ${a}`),h.push(` shape: [${t}]`),h.push(" values:")),h.push(c.map(d=>" "+d).join(` `)),h.join(` `)}function rk(e,t,n,s){const i=P(t),o=s[s.length-1],a=new Array(o).fill(0),c=t.length,h=n==="complex64"?Zl(e):e;if(c>1)for(let d=0;d<i/o;d++){const m=d*o;for(let f=0;f<o;f++)a[f]=Math.max(a[f],Jl(h[m+f],0,n).length)}return a}function Jl(e,t,n){let s;return Array.isArray(e)?s=`${parseFloat(e[0].toFixed(ky))} + ${parseFloat(e[1].toFixed(ky))}j`:Yi(e)?s=`'${e}'`:n==="bool"?s=iT(e):s=parseFloat(e.toFixed(ky)).toString(),pt(s,t)}function iT(e){return e===0?"false":"true"}function $d(e,t,n,s,i,o=!0){const a=n==="complex64"?2:1,c=t[0],h=t.length;if(h===0){if(n==="complex64"){const x=Zl(e);return[Jl(x[0],0,n)]}return n==="bool"?[iT(e[0])]:[e[0].toString()]}if(h===1){if(c>sT){const v=Xl*a;let N=Array.from(e.slice(0,v)),O=Array.from(e.slice((c-Xl)*a,c*a));return n==="complex64"&&(N=Zl(N),O=Zl(O)),["["+N.map((E,k)=>Jl(E,i[k],n)).join(", ")+", ..., "+O.map((E,k)=>Jl(E,i[c-Xl+k],n)).join(", ")+"]"]}const x=n==="complex64"?Zl(e):Array.from(e);return["["+x.map((v,N)=>Jl(v,i[N],n)).join(", ")+"]"]}const d=t.slice(1),m=s.slice(1),f=s[0]*a,b=[];if(c>sT){for(let x=0;x<Xl;x++){const v=x*f,N=v+f;b.push(...$d(e.slice(v,N),d,n,m,i,!1))}b.push("...");for(let x=c-Xl;x<c;x++){const v=x*f,N=v+f;b.push(...$d(e.slice(v,N),d,n,m,i,x===c-1))}}else for(let x=0;x<c;x++){const v=x*f,N=v+f;b.push(...$d(e.slice(v,N),d,n,m,i,x===c-1))}const w=h===2?",":"";b[0]="["+b[0]+w;for(let x=1;x<b.length-1;x++)b[x]=" "+b[x]+w;let L=`, `;for(let x=2;x<h;x++)L+=` `;return b[b.length-1]=" "+b[b.length-1]+"]"+(o?"":L),b}function Zl(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}class an{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=P(e),n!=null){const s=n.length;A(s===this.size,()=>`Length of values '${s}' does not match the size inferred by the shape '${this.size}'.`)}if(t==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||ws(t,this.size),this.strides=je(e)}set(e,...t){t.length===0&&(t=[0]),A(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 s of e){if(s<0||s>=this.shape[t]){const i=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(i)}t++}let n=e[e.length-1];for(let s=0;s<e.length-1;++s)n+=this.strides[s]*e[s];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 Si().makeTensor(this.values,this.shape,this.dtype)}}let Si=null,Oa=null,rT=null;function ok(e){Si=e}function ak(e){Oa=e}function ck(e){rT=e}class ee{constructor(e,t,n,s){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=P(e),this.strides=je(e),this.dataId=n,this.id=s,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){const e=await this.data();return Oa.buffer(this.shape,this.dtype,e)}bufferSync(){return Oa.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return Ls(this.shape,e)}arraySync(){return Ls(this.shape,this.dataSync())}async data(){this.throwIfDisposed();const e=Si().read(this.dataId);if(this.dtype==="string"){const t=await e;try{return t.map(n=>Kl(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=Si().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>Kl(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 Si().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){if(this.isDisposed)return;Si().disposeTensor(this),this.isDisposedInternal=!0}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Oa.print(this,e)}clone(){return this.throwIfDisposed(),Oa.clone(this)}toString(e=!1){const t=this.dataSync();return ik(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Oa.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Si().makeVariable(this,e,t,n)}}Object.defineProperty(ee,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});class Ql extends ee{constructor(e,t,n,s){super(e.shape,e.dtype,e.dataId,s);this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!ae(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Si().disposeTensor(this),this.dataId=e.dataId,Si().incRef(this,null)}dispose(){Si().disposeVariable(this),this.isDisposedInternal=!0}}Object.defineProperty(Ql,Symbol.hasInstance,{value:e=>e instanceof ee&&e.assign!=null&&e.assign instanceof Function});(function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"})(r.Rank||(r.Rank={}));var Fy;(function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"})(Fy||(Fy={}));var _y;(function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"})(_y||(_y={}));var Wy;(function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"})(Wy||(Wy={}));var $y;(function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"})($y||($y={}));const lk={float32:Wy,int32:Fy,bool:_y,complex64:$y};function $n(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return lk[e][t]}function Ud(e){return $n(e,"int32")}function Gt(e,t){if(e.dtype===t.dtype)return[e,t];const n=$n(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function oT(e,t){A(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function Bd(e,t){return t.some(n=>n.id===e.id)}function Hi(e){const t=[],n=new Set;return aT(e,t,n),t}function aT(e,t,n){if(e==null)return;if(e instanceof ee){t.push(e);return}if(!hk(e))return;const s=e;for(const i in s){const o=s[i];n.has(o)||(n.add(o),aT(o,t,n))}}function hk(e){return Array.isArray(e)||typeof e=="object"}var uk=Object.freeze({__proto__:null,makeTypesMatch:Gt,assertTypesMatch:oT,isTensorInList:Bd,getTensorsInContainer:Hi});class cT{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 eh{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new cT}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],s=await this.initializeBackend(n).success;if(s){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),s=n?await t:t;if(!s)return!1}return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new QD(this.backendInstance),!0}setupRegisteredKernels(){const e=Fd(this.backendName);e.forEach(t=>{t.setupFunc!=null&&t.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){const t=Fd(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(n&&!(n instanceof y)&&typeof n.then=="function"){const s=++this.pendingBackendInitId,i=n.then(o=>s<this.pendingBackendInitId?!1:(this.registry[e]=o,this.pendingBackendInit=null,!0)).catch(o=>(s<this.pendingBackendInitId||(this.pendingBackendInit=null,console.warn(`Initialization of backend ${e} failed`),console.warn(o.stack||o.message)),!1));return this.pendingBackendInit=i,{success:i,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:s,asyncInit:i}=this.initializeBackend(n);if(i||s)return{name:n,asyncInit:i}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){const n=this.state.tensorInfo.get(t),s=n.backend,i=this.readSync(t);s.disposeData(t),n.backend=e,e.move(t,i,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 s;return this.scopedRun(()=>this.startScope(n),()=>this.endScope(s),()=>(s=t(),s instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),s))}scopedRun(e,t,n){e();try{const s=n();return t(),s}catch(s){throw t(),s}}nextTensorId(){return eh.nextTensorId++}nextVariableId(){return eh.nextVariableId++}clone(e){const t=this.makeTensorFromDataId(e.dataId,e.shape,e.dtype),n={x:e},s=o=>({x:()=>{const a="float32",c={x:o},h={dtype:a};return G.runKernelFunc(d=>d.cast(o,a),c,null,Sa,h)}}),i=[];return this.addTapeNode(this.state.activeScope.name,n,[t],s,i,{}),t}runKernel(e,t,n,s,i){const o=null,a=null;return this.runKernelFunc(o,t,a,e,n,s,i)}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){const s=this.backend.numDataIds();let i=0;n.forEach(c=>{i+=c.dtype==="complex64"?3:1});const o=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],a=s-t-i-o;if(a>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${a} data ids) after running '${e}'`)}runKernelFunc(e,t,n,s,i,o,a){let c,h=[];const d=this.isTapeOn();s==null&&(s=this.state.activeScope!=null?this.state.activeScope.name:"");const m=this.state.numBytes,f=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let b;const w=Oy(s,this.backendName);let L;if(w!=null)b=()=>{const v=this.backend.numDataIds();L=w.kernelFunc({inputs:t,attrs:i,backend:this.backend});const N=Array.isArray(L)?L:[L];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(s,v,N);const O=N.map(({dataId:E,shape:k,dtype:F})=>this.makeTensorFromDataId(E,k,F));if(d){let E=this.getTensorsForGradient(s,t,O);if(E==null){a==null&&(a=[]);const k=O.filter((F,U)=>a[U]);E=(o||[]).slice().concat(k)}h=this.saveTensorsForBackwardMode(E)}return O};else{const v=N=>{if(!d)return;h=N.map(O=>this.keep(this.clone(O)))};b=()=>{const N=this.backend.numDataIds();L=this.tidy(()=>e(this.backend,v));const O=Array.isArray(L)?L:[L];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(s,N,O),O}}let x;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?c=b():(x=this.profiler.profileKernel(s,t,()=>b()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(x),c=x.outputs)}),d&&this.addTapeNode(s,t,c,n,h,i),this.state.profiling&&this.state.activeProfile.kernels.push({name:s,bytesAdded:this.state.numBytes-m,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-f,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(t).map(v=>t[v]!=null?t[v].shape:null),outputShapes:c.map(v=>v.shape),kernelTimeMs:x.timeMs,extraInfo:x.extraInfo}),Array.isArray(L)?c:c[0]}saveTensorsForBackwardMode(e){const t=e.map(n=>this.keep(this.clone(n)));return t}getTensorsForGradient(e,t,n){const s=Ey(e);if(s!=null){const i=s.inputsToSave||[],o=s.outputsToSave||[];let a;s.saveAllInputs?(A(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),a=Object.keys(t).map(h=>t[h])):a=i.map(h=>t[h]);const c=n.filter((h,d)=>o[d]);return a.concat(c)}return null}makeTensor(e,t,n,s){if(e==null)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",s=s||this.backend;let i=e;n==="string"&&Yi(e[0])&&(i=e.map(c=>Wd(c)));const o=s.write(i,t,n),a=new ee(t,n,o,this.nextTensorId());if(this.incRef(a,s),n==="string"){const c=this.state.tensorInfo.get(o),h=Ix(i);this.state.numBytes+=h-c.bytes,c.bytes=h}return a}makeTensorFromDataId(e,t,n,s){n=n||"float32";const i=new ee(t,n,e,this.nextTensorId());return this.incRef(i,s),i}makeVariable(e,t=!0,n,s){n=n||this.nextVariableId().toString(),s!=null&&s!==e.dtype&&(e=e.cast(s));const i=new Ql(e,t,n,this.nextTensorId());if(this.state.registeredVariables[i.name]!=null)throw new Error(`Variable with name ${i.name} was already registered`);return this.state.registeredVariables[i.name]=i,this.incRef(i,this.backend),i}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 s=0;e.dtype!=="complex64"&&e.dtype!=="string"&&(s=e.size*Bg(e.dtype)),this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:s,refCount:0}),this.state.numBytes+=s}this.state.tensorInfo.get(e.dataId).refCount++,e instanceof Ql||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(s=>s.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(const s of this.state.activeProfile.kernels)s.kernelTimeMs=await s.kernelTimeMs,s.extraInfo=await s.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(e,t,n,s,i,o){const a={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:i},c=Ey(e);c!=null&&(s=c.gradFunc),s!=null&&(a.gradient=h=>(h=h.map((d,m)=>{if(d==null){const f=n[m],b=La(f.size,f.dtype);return this.makeTensor(b,f.shape,f.dtype)}return d}),s(h.length>1?h:h[0],i,o))),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=Hi(e),n=new Set(t.map(i=>i.id));for(let i=0;i<this.state.activeScope.track.length;i++){const o=this.state.activeScope.track[i];!o.kept&&!n.has(o.id)&&o.dispose()}const s=this.state.scopeStack.pop();this.state.activeScope=this.state.scopeStack.length===0?null:this.state.scopeStack[this.state.scopeStack.length-1],t.forEach(i=>{!i.kept&&i.scopeId===s.id&&this.track(i)})}gradients(e,t,n,s=!1){if(A(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 i=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));A(i instanceof ee,()=>"The result y returned by f() must be a tensor.");const o=nk(this.state.activeTape,t,i);if(!s&&o.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[i.id]=n==null?dk(i.shape):n,sk(a,o,h=>this.tidy(h),pk);const c=t.map(h=>a[h.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(h=>{for(const d of h.saved)d.dispose()}),this.state.activeTape=null),{value:i,grads:c}})}customGrad(e){return A(Rr(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{A(t.every(i=>i instanceof ee),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let n;const s={};return t.forEach((i,o)=>{s[o]=i}),this.runKernelFunc((i,o)=>(n=e(...t,o),A(n.value instanceof ee,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),A(Rr(n.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),n.value),s,(i,o)=>{const a=n.gradFunc(i,o),c=Array.isArray(a)?a:[a];A(c.length===t.length,()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."),A(c.every(d=>d instanceof ee),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");const h={};return c.forEach((d,m)=>{h[m]=()=>d}),h})}}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=jn(),n=await this.backend.time(e);return n.wallMs=jn()-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 cT;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}}eh.nextTensorId=0,eh.nextVariableId=0;function dk(e){const t=Mg(P(e),"float32");return G.makeTensor(t,e,"float32")}function lT(){const e=Nx();if(e._tfengine==null){const t=new vx(e);e._tfengine=new eh(t)}return YD(e._tfengine.ENV),ok(()=>e._tfengine),e._tfengine}const G=lT();function pk(e,t){const n={a:e,b:t};return G.runKernelFunc((s,i)=>{const o=s.add(e,t);return i([e,t]),o},n,null,wo)}function mk(){return typeof navigator!="undefined"&&navigator!=null}function hT(){if(mk()){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 Uy(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var fk=Object.freeze({__proto__:null,isMobile:hT,isBrowser:Uy});const qi=oe();qi.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.")}),qi.registerFlag("IS_BROWSER",()=>Uy()),qi.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined"),qi.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)),qi.registerFlag("PROD",()=>!1),qi.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>qi.getBool("DEBUG")),qi.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0),qi.registerFlag("IS_TEST",()=>!1);function Ii(e,t){let n=e;if(hn(e))return t==="string"?[]:[e.length];if(!Array.isArray(e))return[];const s=[];for(;Array.isArray(n)||hn(n)&&t!=="string";)s.push(n.length),n=n[0];return Array.isArray(e)&&oe().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&uT(e,s,[]),s}function uT(e,t,n){if(n=n||[],!Array.isArray(e)&&!hn(e)){A(t.length===0,()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}A(t.length>0,()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`),A(e.length===t[0],()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`);const s=t.slice(1);for(let i=0;i<e.length;++i)uT(e[i],s,n.concat(i))}function dT(e,t,n,s){if(e==null)return;if(e!=="numeric"&&e!==t||e==="numeric"&&t==="string")throw new Error(`Argument '${n}' passed to '${s}' must be ${e} tensor, but got ${t} tensor`)}function W(e,t,n,s="numeric"){if(e instanceof ee)return dT(s,e.dtype,t,n),e;let i=wa(e);if(i!=="string"&&["bool","int32","float32"].indexOf(s)>=0&&(i=s),dT(s,i,t,n),e==null||!hn(e)&&!Array.isArray(e)&&typeof e!="number"&&typeof e!="boolean"&&typeof e!="string"){const h=e==null?"null":e.constructor.name;throw new