From 5e027da545c6f83535254b43ad8ebc42556584b7 Mon Sep 17 00:00:00 2001 From: Vladimir Mandic Date: Mon, 12 Oct 2020 10:14:26 -0400 Subject: [PATCH] updated model path --- README.md | 3 ++- demo/demo-esm.js | 2 +- dist/human.esm.js | 2 +- dist/human.esm.js.map | 4 ++-- dist/human.js | 2 +- dist/human.js.map | 4 ++-- src/config.js | 14 +++++++------- 7 files changed, 16 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 094d7e7e..9a4c4f08 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,7 @@ # Human: 3D Face Detection, Body Pose, Hand & Finger Tracking, Iris Tracking and Age & Gender Prediction -URL: +Repository: +Live Demo: *Suggestions are welcome!* diff --git a/demo/demo-esm.js b/demo/demo-esm.js index 70d2f34e..80f6daaa 100644 --- a/demo/demo-esm.js +++ b/demo/demo-esm.js @@ -12,7 +12,7 @@ const config = { age: { enabled: false, skipFrames: 5 }, gender: { enabled: false }, }, - body: { enabled: false, maxDetections: 5, scoreThreshold: 0.75, nmsRadius: 20 }, + body: { enabled: false, maxDetections: 5, scoreThreshold: 0.75, nmsRadius: 20, }, hand: { enabled: false, skipFrames: 5, minConfidence: 0.8, iouThreshold: 0.3, scoreThreshold: 0.75 }, }; let settings; diff --git a/dist/human.esm.js b/dist/human.esm.js index 146584a0..0f8e4eef 100644 --- a/dist/human.esm.js +++ b/dist/human.esm.js @@ -3814,7 +3814,7 @@ return a / b;`,b6=` } `}return n}();var $6={kernelName:N.RotateWithOffset,backendName:"webgl",kernelFunc:function(n){var t=n.inputs,e=n.attrs,i=n.backend,r=t.image,a=e,s=a.radians,o=a.fillValue,l=a.center,u=i,c=new j6(r.shape,s,o,l),h=u.runWebGLProgram(c,[r],r.dtype);return h}};var X6=$S+` return sin(x); -`,J6=jo(X6),Z6={kernelName:N.Sin,backendName:"webgl",kernelFunc:J6};var Q6="return x * x;",e8=jo(Q6),t8={kernelName:N.Square,backendName:"webgl",kernelFunc:e8};var JS="return (a - b) * (a - b);",n8=Gd(JS,JS),i8={kernelName:N.SquaredDifference,backendName:"webgl",kernelFunc:n8};var r8="return tan(x);",a8=jo(r8),s8={kernelName:N.Tan,backendName:"webgl",kernelFunc:a8};var o8={kernelName:N.Transpose,backendName:"webgl",kernelFunc:function(n){for(var t=n.inputs,e=n.attrs,i=n.backend,r=t.x,a=e.perm,s=i,o=r.shape.length,l=new Array(o),u=0;u{"use strict";Object.defineProperty(cr,"__esModule",{value:!0});var $d=Yi(),Xd=Kb(),Jd=lw(),eL=Ow(),d8=v0(),p8=QS();var f8="2.6.0";var m8={"tfjs-core":$d.version_core,"tfjs-backend-cpu":d8.version_cpu,"tfjs-backend-webgl":p8.version_webgl,"tfjs-data":eL.version_data,"tfjs-layers":Xd.version_layers,"tfjs-converter":Jd.version_converter,tfjs:f8};Object.keys($d).forEach(function(n){n!=="default"&&Object.defineProperty(cr,n,{enumerable:!0,get:function(){return $d[n]}})});Object.keys(Xd).forEach(function(n){n!=="default"&&Object.defineProperty(cr,n,{enumerable:!0,get:function(){return Xd[n]}})});Object.keys(Jd).forEach(function(n){n!=="default"&&Object.defineProperty(cr,n,{enumerable:!0,get:function(){return Jd[n]}})});cr.data=eL;cr.version=m8});var tL=ge(os=>{const ls=Ct();os.disposeBox=n=>{n.startEndTensor.dispose(),n.startPoint.dispose(),n.endPoint.dispose()};os.createBox=n=>({startEndTensor:n,startPoint:ls.slice(n,[0,0],[-1,2]),endPoint:ls.slice(n,[0,2],[-1,2])});os.scaleBox=(n,t)=>{const e=ls.mul(n.startPoint,t),i=ls.mul(n.endPoint,t),r=ls.concat2d([e,i],1);return os.createBox(r)}});var Zd=ge(nL=>{const Ve=Ct(),$o=tL(),g8={strides:[8,16],anchors:[2,6]},iL=6;function v8(n,t,e){const i=[];for(let r=0;r{const e=n.box?n.box:n;return $o.scaleBox(e,t).startEndTensor.squeeze()})}class b8{constructor(n,t){this.blazeFaceModel=n,this.width=t.detector.inputSize,this.height=t.detector.inputSize,this.maxFaces=t.detector.maxFaces,this.anchorsData=v8(t.detector.inputSize,t.detector.inputSize,g8),this.anchors=Ve.tensor2d(this.anchorsData),this.inputSizeData=[t.detector.inputSize,t.detector.inputSize],this.inputSize=Ve.tensor1d([t.detector.inputSize,t.detector.inputSize]),this.iouThreshold=t.detector.iouThreshold,this.scoreThreshold=t.detector.scoreThreshold}async getBoundingBoxes(n,t,e=!0){const[i,r,a]=Ve.tidy(()=>{const p=n.resizeBilinear([this.width,this.height]),f=Ve.mul(Ve.sub(p.div(255),.5),2),m=this.blazeFaceModel.predict(f),g=m.squeeze(),v=y8(g,this.anchors,this.inputSize),b=Ve.slice(g,[0,0],[-1,1]),w=Ve.sigmoid(b).squeeze();return[g,v,w]}),s=await Ve.image.nonMaxSuppressionAsync(r,a,this.maxFaces,this.iouThreshold,this.scoreThreshold),o=await s.array();s.dispose();let l=o.map(p=>Ve.slice(r,[p,0],[1,-1]));t||(l=await Promise.all(l.map(async p=>{const f=await p.array();return p.dispose(),f})));const u=n.shape[1],c=n.shape[2];let h;t?h=Ve.div([c,u],this.inputSize):h=[c/this.inputSizeData[0],u/this.inputSizeData[1]];const d=[];for(let p=0;p{const g=f instanceof Ve.Tensor?$o.createBox(f):$o.createBox(Ve.tensor2d(f));if(!e)return g;const v=o[p];let b;t?b=this.anchors.slice([v,0],[1,2]):b=this.anchorsData[v];const w=Ve.slice(i,[v,iL-1],[1,-1]).squeeze().reshape([iL,-1]),S=Ve.slice(a,[v],[1]);return{box:g,landmarks:w,probability:S,anchor:b}});d.push(m)}return r.dispose(),a.dispose(),i.dispose(),{boxes:d,scaleFactor:h}}async estimateFaces(n,t=!1,e=!0){const i=Ve.tidy(()=>(n instanceof Ve.Tensor||(n=Ve.browser.fromPixels(n)),n.toFloat().expandDims(0))),{boxes:r,scaleFactor:a}=await this.getBoundingBoxes(i,t,e);return i.dispose(),t?r.map(s=>{const o=rL(s,a),l={topLeft:o.slice([0],[2]),bottomRight:o.slice([2],[2])};if(e){const{landmarks:u,probability:c,anchor:h}=s,d=u.add(h).mul(a);l.landmarks=d,l.probability=c}return l}):Promise.all(r.map(async s=>{const o=rL(s,a);let l;if(e){const[u,c,h]=await Promise.all([s.landmarks,o,s.probability].map(async g=>g.array())),d=s.anchor,[p,f]=a,m=u.map(g=>[(g[0]+d[0])*p,(g[1]+d[1])*f]);l={topLeft:c.slice(0,2),bottomRight:c.slice(2),landmarks:m,probability:h},$o.disposeBox(s.box),s.landmarks.dispose(),s.probability.dispose()}else{const u=await o.array();l={topLeft:u.slice(0,2),bottomRight:u.slice(2)}}return o.dispose(),l}))}}nL.BlazeFaceModel=b8});var aL=ge(Qd=>{const w8=Ct(),S8=Zd();async function L8(n){const t=await w8.loadGraphModel(n.detector.modelPath,{fromTFHub:n.detector.modelPath.includes("tfhub.dev")}),e=new S8.BlazeFaceModel(t,n);return e}Qd.load=L8;const I8=Zd();Object.defineProperty(Qd,"BlazeFaceModel",{enumerable:!0,get(){return I8.BlazeFaceModel}})});var ep=ge(sL=>{sL.MESH_ANNOTATIONS={silhouette:[10,338,297,332,284,251,389,356,454,323,361,288,397,365,379,378,400,377,152,148,176,149,150,136,172,58,132,93,234,127,162,21,54,103,67,109],lipsUpperOuter:[61,185,40,39,37,0,267,269,270,409,291],lipsLowerOuter:[146,91,181,84,17,314,405,321,375,291],lipsUpperInner:[78,191,80,81,82,13,312,311,310,415,308],lipsLowerInner:[78,95,88,178,87,14,317,402,318,324,308],rightEyeUpper0:[246,161,160,159,158,157,173],rightEyeLower0:[33,7,163,144,145,153,154,155,133],rightEyeUpper1:[247,30,29,27,28,56,190],rightEyeLower1:[130,25,110,24,23,22,26,112,243],rightEyeUpper2:[113,225,224,223,222,221,189],rightEyeLower2:[226,31,228,229,230,231,232,233,244],rightEyeLower3:[143,111,117,118,119,120,121,128,245],rightEyebrowUpper:[156,70,63,105,66,107,55,193],rightEyebrowLower:[35,124,46,53,52,65],rightEyeIris:[473,474,475,476,477],leftEyeUpper0:[466,388,387,386,385,384,398],leftEyeLower0:[263,249,390,373,374,380,381,382,362],leftEyeUpper1:[467,260,259,257,258,286,414],leftEyeLower1:[359,255,339,254,253,252,256,341,463],leftEyeUpper2:[342,445,444,443,442,441,413],leftEyeLower2:[446,261,448,449,450,451,452,453,464],leftEyeLower3:[372,340,346,347,348,349,350,357,465],leftEyebrowUpper:[383,300,293,334,296,336,285,417],leftEyebrowLower:[265,353,276,283,282,295],leftEyeIris:[468,469,470,471,472],midwayBetweenEyes:[168],noseTip:[1],noseBottom:[2],noseRightCorner:[98],noseLeftCorner:[327],rightCheek:[205],leftCheek:[425]}});var oL=ge(hr=>{const A8=Ct();function T8(n,t){const e=[n.startPoint[0]*t[0],n.startPoint[1]*t[1]],i=[n.endPoint[0]*t[0],n.endPoint[1]*t[1]];return{startPoint:e,endPoint:i}}hr.scaleBoxCoordinates=T8;function tp(n){return[Math.abs(n.endPoint[0]-n.startPoint[0]),Math.abs(n.endPoint[1]-n.startPoint[1])]}hr.getBoxSize=tp;function np(n){return[n.startPoint[0]+(n.endPoint[0]-n.startPoint[0])/2,n.startPoint[1]+(n.endPoint[1]-n.startPoint[1])/2]}hr.getBoxCenter=np;function N8(n,t,e){const i=t.shape[1],r=t.shape[2],a=[[n.startPoint[1]/i,n.startPoint[0]/r,n.endPoint[1]/i,n.endPoint[0]/r]];return A8.image.cropAndResize(t,a,[0],e)}hr.cutBoxFromImageAndResize=N8;function x8(n,t=1.5){const e=np(n),i=tp(n),r=[t*i[0]/2,t*i[1]/2],a=[e[0]-r[0],e[1]-r[1]],s=[e[0]+r[0],e[1]+r[1]];return{startPoint:a,endPoint:s,landmarks:n.landmarks}}hr.enlargeBox=x8;function C8(n){const t=np(n),e=tp(n),i=Math.max(...e),r=i/2,a=[t[0]-r,t[1]-r],s=[t[0]+r,t[1]+r];return{startPoint:a,endPoint:s,landmarks:n.landmarks}}hr.squarifyBox=C8});var dL=ge(wn=>{wn.IDENTITY_MATRIX=[[1,0,0],[0,1,0],[0,0,1]];function lL(n){return n-2*Math.PI*Math.floor((n+Math.PI)/(2*Math.PI))}wn.normalizeRadians=lL;function R8(n,t){const e=Math.PI/2-Math.atan2(-(t[1]-n[1]),t[0]-n[0]);return lL(e)}wn.computeRotation=R8;function O8(n){return n*180/Math.PI}wn.radToDegrees=O8;function uL(n,t){return[[1,0,n],[0,1,t],[0,0,1]]}function ra(n,t){let e=0;for(let i=0;i{const Ai=Ct(),Bn=oL(),aa=ep(),Ti=dL(),W8=468,U8=.25,B8=13,z8=[B8,aa.MESH_ANNOTATIONS.midwayBetweenEyes[0]],P8=3,_8=2,M8=[P8,_8],ip=aa.MESH_ANNOTATIONS.leftEyeLower0,rp=[ip[0],ip[ip.length-1]],ap=aa.MESH_ANNOTATIONS.rightEyeLower0,sp=[ap[0],ap[ap.length-1]],H8=3,V8=4,q8=71,op=76,G8=2.3,us=64,fL=[{key:"EyeUpper0",indices:[9,10,11,12,13,14,15]},{key:"EyeUpper1",indices:[25,26,27,28,29,30,31]},{key:"EyeUpper2",indices:[41,42,43,44,45,46,47]},{key:"EyeLower0",indices:[0,1,2,3,4,5,6,7,8]},{key:"EyeLower1",indices:[16,17,18,19,20,21,22,23,24]},{key:"EyeLower2",indices:[32,33,34,35,36,37,38,39,40]},{key:"EyeLower3",indices:[54,55,56,57,58,59,60,61,62]},{key:"EyebrowUpper",indices:[63,64,65,66,67,68,69,70]},{key:"EyebrowLower",indices:[48,49,50,51,52,53]}];function Xo(n,t,e,i){for(let r=0;r[a[0]*(d[0]-this.meshWidth/2),a[1]*(d[1]-this.meshHeight/2),d[2]]),o=Ti.buildRotationMatrix(e,[0,0]),l=s.map(d=>[...Ti.rotatePoint(d,o),d[2]]),u=Ti.invertTransformMatrix(i),c=[...Bn.getBoxCenter({startPoint:t.startPoint,endPoint:t.endPoint}),1],h=[Ti.dot(c,u[0]),Ti.dot(c,u[1])];return l.map(d=>[d[0]+h[0],d[1]+h[1],d[2]])}getLeftToRightEyeDepthDifference(n){const t=n[rp[0]][2],e=n[sp[0]][2];return t-e}getEyeBox(n,t,e,i,r=!1){const a=Bn.squarifyBox(Bn.enlargeBox(this.calculateLandmarksBoundingBox([n[e],n[i]]),G8)),s=Bn.getBoxSize(a);let o=Ai.image.cropAndResize(t,[[a.startPoint[1]/this.meshHeight,a.startPoint[0]/this.meshWidth,a.endPoint[1]/this.meshHeight,a.endPoint[0]/this.meshWidth]],[0],[us,us]);return r&&(o=Ai.image.flipLeftRight(o)),{box:a,boxSize:s,crop:o}}getEyeCoords(n,t,e,i=!1){const r=[];for(let a=0;a{let l=a;return o===2?l=i:o===4&&(l=r),[s[0],s[1],l]})}async predict(n,t,e){if(this.shouldUpdateRegionsOfInterest()){const i=!1,r=!0,{boxes:a,scaleFactor:s}=await this.boundingBoxDetector.getBoundingBoxes(n,i,r);if(a.length===0)return this.regionsOfInterest=[],null;const o=a.map(l=>{const u={startPoint:l.box.startPoint.squeeze().arraySync(),endPoint:l.box.endPoint.squeeze().arraySync()},c=Bn.scaleBoxCoordinates(u,s),h=Bn.enlargeBox(c);return{...h,landmarks:l.landmarks.arraySync()}});a.forEach(l=>{l!=null&&l.startPoint!=null&&(l.startEndTensor.dispose(),l.startPoint.dispose(),l.endPoint.dispose())}),this.updateRegionsOfInterest(o),this.runsWithoutFaceDetector=0}else this.runsWithoutFaceDetector++;return Ai.tidy(()=>this.regionsOfInterest.map((i,r)=>{let a=0;const s=i.landmarks.length>=W8;let[o,l]=z8;s===!1&&([o,l]=M8),a=Ti.computeRotation(i.landmarks[o],i.landmarks[l]);const u=Bn.getBoxCenter({startPoint:i.startPoint,endPoint:i.endPoint}),c=[u[0]/n.shape[2],u[1]/n.shape[1]];let h=n,d=Ti.IDENTITY_MATRIX;a!==0&&(h=Ai.image.rotateWithOffset(n,a,0,c),d=Ti.buildRotationMatrix(-a,u));const p={startPoint:i.startPoint,endPoint:i.endPoint},f=Bn.cutBoxFromImageAndResize(p,h,[this.meshHeight,this.meshWidth]).div(255),[,m,g]=this.meshDetector.predict(f),v=Ai.reshape(g,[-1,3]);let b=v.arraySync();if(t){const{box:x,boxSize:C,crop:R}=this.getEyeBox(b,f,rp[0],rp[1],!0),{box:D,boxSize:k,crop:W}=this.getEyeBox(b,f,sp[0],sp[1]),F=this.irisModel.predict(Ai.concat([R,W])),P=F.dataSync(),H=P.slice(0,op*3),{rawCoords:_,iris:K}=this.getEyeCoords(H,x,C,!0),j=P.slice(op*3),{rawCoords:q,iris:G}=this.getEyeCoords(j,D,k),Z=this.getLeftToRightEyeDepthDifference(b);Math.abs(Z)<30?(Xo(b,_,"left"),Xo(b,q,"right")):Z<1?Xo(b,_,"left",["EyeUpper0","EyeLower0"]):Xo(b,q,"right",["EyeUpper0","EyeLower0"]);const X=this.getAdjustedIrisCoords(b,K,"left"),ee=this.getAdjustedIrisCoords(b,G,"right");b=b.concat(X).concat(ee)}const w=this.transformRawCoords(b,i,a,d);Ai.dispose(b);const S=Bn.enlargeBox(this.calculateLandmarksBoundingBox(w));if(e){const x=Ai.tensor2d(w);this.regionsOfInterest[r]={...S,landmarks:x.arraySync()};const C={coords:x,box:S,confidence:m.squeeze(),image:f};return C}const L={coords:null,box:S,confidence:m.squeeze(),image:f};return L}))}updateRegionsOfInterest(n){for(let t=0;t=this.skipFrames}calculateLandmarksBoundingBox(n){const t=n.map(a=>a[0]),e=n.map(a=>a[1]),i=[Math.min(...t),Math.min(...e)],r=[Math.max(...t),Math.max(...e)];return{startPoint:i,endPoint:r}}}pL.Pipeline=Y8});var vL=ge(gL=>{gL.UV_COORDS=[[.499976992607117,.652534008026123],[.500025987625122,.547487020492554],[.499974012374878,.602371990680695],[.482113003730774,.471979022026062],[.500150978565216,.527155995368958],[.499909996986389,.498252987861633],[.499523013830185,.40106201171875],[.289712011814117,.380764007568359],[.499954998493195,.312398016452789],[.499987006187439,.269918978214264],[.500023007392883,.107050001621246],[.500023007392883,.666234016418457],[.5000159740448,.679224014282227],[.500023007392883,.692348003387451],[.499976992607117,.695277988910675],[.499976992607117,.70593398809433],[.499976992607117,.719385027885437],[.499976992607117,.737019002437592],[.499967992305756,.781370997428894],[.499816000461578,.562981009483337],[.473773002624512,.573909997940063],[.104906998574734,.254140973091125],[.365929991006851,.409575998783112],[.338757991790771,.41302502155304],[.311120003461838,.409460008144379],[.274657994508743,.389131009578705],[.393361985683441,.403706014156342],[.345234006643295,.344011008739471],[.370094001293182,.346076011657715],[.319321990013123,.347265005111694],[.297903001308441,.353591024875641],[.24779200553894,.410809993743896],[.396889001131058,.842755019664764],[.280097991228104,.375599980354309],[.106310002505779,.399955987930298],[.2099249958992,.391353011131287],[.355807989835739,.534406006336212],[.471751004457474,.65040397644043],[.474155008792877,.680191993713379],[.439785003662109,.657229006290436],[.414617002010345,.66654098033905],[.450374007225037,.680860996246338],[.428770989179611,.682690978050232],[.374971002340317,.727805018424988],[.486716985702515,.547628998756409],[.485300987958908,.527395009994507],[.257764995098114,.314490020275116],[.401223003864288,.455172002315521],[.429818987846375,.548614978790283],[.421351999044418,.533740997314453],[.276895999908447,.532056987285614],[.483370006084442,.499586999416351],[.33721199631691,.282882988452911],[.296391993761063,.293242990970612],[.169294998049736,.193813979625702],[.447580009698868,.302609980106354],[.392390012741089,.353887975215912],[.354490011930466,.696784019470215],[.067304998636246,.730105042457581],[.442739009857178,.572826027870178],[.457098007202148,.584792017936707],[.381974011659622,.694710969924927],[.392388999462128,.694203019142151],[.277076005935669,.271932005882263],[.422551989555359,.563233017921448],[.385919004678726,.281364023685455],[.383103013038635,.255840003490448],[.331431001424789,.119714021682739],[.229923993349075,.232002973556519],[.364500999450684,.189113974571228],[.229622006416321,.299540996551514],[.173287004232407,.278747975826263],[.472878992557526,.666198015213013],[.446828007698059,.668527007102966],[.422762006521225,.673889994621277],[.445307999849319,.580065965652466],[.388103008270264,.693961024284363],[.403039008378983,.706539988517761],[.403629004955292,.693953037261963],[.460041999816895,.557139039039612],[.431158006191254,.692366003990173],[.452181994915009,.692366003990173],[.475387006998062,.692366003990173],[.465828001499176,.779190003871918],[.472328990697861,.736225962638855],[.473087012767792,.717857003211975],[.473122000694275,.704625964164734],[.473033010959625,.695277988910675],[.427942007780075,.695277988910675],[.426479011774063,.703539967536926],[.423162013292313,.711845993995667],[.4183090031147,.720062971115112],[.390094995498657,.639572978019714],[.013953999616206,.560034036636353],[.499913990497589,.58014702796936],[.413199990987778,.69539999961853],[.409626007080078,.701822996139526],[.468080013990402,.601534962654114],[.422728985548019,.585985004901886],[.463079988956451,.593783974647522],[.37211999297142,.47341400384903],[.334562003612518,.496073007583618],[.411671012639999,.546965003013611],[.242175996303558,.14767599105835],[.290776997804642,.201445996761322],[.327338010072708,.256527006626129],[.399509996175766,.748921036720276],[.441727995872498,.261676013469696],[.429764986038208,.187834024429321],[.412198007106781,.108901023864746],[.288955003023148,.398952007293701],[.218936994671822,.435410976409912],[.41278201341629,.398970007896423],[.257135003805161,.355440020561218],[.427684992551804,.437960982322693],[.448339998722076,.536936044692993],[.178560003638268,.45755398273468],[.247308000922203,.457193970680237],[.286267012357712,.467674970626831],[.332827985286713,.460712015628815],[.368755996227264,.447206974029541],[.398963987827301,.432654976844788],[.476410001516342,.405806005001068],[.189241006970406,.523923993110657],[.228962004184723,.348950982093811],[.490725994110107,.562400996685028],[.404670000076294,.485132992267609],[.019469000399113,.401564002037048],[.426243007183075,.420431017875671],[.396993011236191,.548797011375427],[.266469985246658,.376977026462555],[.439121007919312,.51895797252655],[.032313998788595,.644356966018677],[.419054001569748,.387154996395111],[.462783008813858,.505746960639954],[.238978996872902,.779744982719421],[.198220998048782,.831938028335571],[.107550002634525,.540755033493042],[.183610007166862,.740257024765015],[.134409993886948,.333683013916016],[.385764002799988,.883153975009918],[.490967005491257,.579378008842468],[.382384985685349,.508572995662689],[.174399003386497,.397670984268188],[.318785011768341,.39623498916626],[.343364000320435,.400596976280212],[.396100014448166,.710216999053955],[.187885001301765,.588537991046906],[.430987000465393,.944064974784851],[.318993002176285,.898285031318665],[.266247987747192,.869701027870178],[.500023007392883,.190576016902924],[.499976992607117,.954452991485596],[.366169989109039,.398822009563446],[.393207013607025,.39553701877594],[.410373002290726,.391080021858215],[.194993004202843,.342101991176605],[.388664990663528,.362284004688263],[.365961998701096,.355970978736877],[.343364000320435,.355356991291046],[.318785011768341,.35834002494812],[.301414996385574,.363156020641327],[.058132998645306,.319076001644135],[.301414996385574,.387449026107788],[.499987989664078,.618434011936188],[.415838003158569,.624195992946625],[.445681989192963,.566076993942261],[.465844005346298,.620640993118286],[.49992299079895,.351523995399475],[.288718998432159,.819945991039276],[.335278987884521,.852819979190826],[.440512001514435,.902418971061707],[.128294005990028,.791940987110138],[.408771991729736,.373893976211548],[.455606997013092,.451801002025604],[.499877005815506,.908990025520325],[.375436991453171,.924192011356354],[.11421000212431,.615022003650665],[.448662012815475,.695277988910675],[.4480200111866,.704632043838501],[.447111994028091,.715808033943176],[.444831997156143,.730794012546539],[.430011987686157,.766808986663818],[.406787008047104,.685672998428345],[.400738000869751,.681069016456604],[.392399996519089,.677703022956848],[.367855995893478,.663918972015381],[.247923001646996,.601333022117615],[.452769994735718,.420849978923798],[.43639200925827,.359887003898621],[.416164010763168,.368713974952698],[.413385987281799,.692366003990173],[.228018000721931,.683571994304657],[.468268007040024,.352671027183533],[.411361992359161,.804327011108398],[.499989002943039,.469825029373169],[.479153990745544,.442654013633728],[.499974012374878,.439637005329132],[.432112008333206,.493588984012604],[.499886006116867,.866917014122009],[.49991300702095,.821729004383087],[.456548988819122,.819200992584229],[.344549000263214,.745438992977142],[.37890899181366,.574010014533997],[.374292999505997,.780184984207153],[.319687992334366,.570737957954407],[.357154995203018,.604269981384277],[.295284003019333,.621580958366394],[.447750002145767,.862477004528046],[.410986006259918,.508723020553589],[.31395098567009,.775308012962341],[.354128003120422,.812552988529205],[.324548006057739,.703992962837219],[.189096003770828,.646299958229065],[.279776990413666,.71465802192688],[.1338230073452,.682700991630554],[.336768001317978,.644733011722565],[.429883986711502,.466521978378296],[.455527991056442,.548622965812683],[.437114000320435,.558896005153656],[.467287987470627,.529924988746643],[.414712011814117,.335219979286194],[.37704598903656,.322777986526489],[.344107985496521,.320150971412659],[.312875986099243,.32233202457428],[.283526003360748,.333190023899078],[.241245999932289,.382785975933075],[.102986000478268,.468762993812561],[.267612010240555,.424560010433197],[.297879010438919,.433175981044769],[.333433985710144,.433878004550934],[.366427004337311,.426115989685059],[.396012008190155,.416696012020111],[.420121014118195,.41022801399231],[.007561000064015,.480777025222778],[.432949006557465,.569517970085144],[.458638995885849,.479089021682739],[.473466008901596,.545744001865387],[.476087987422943,.563830018043518],[.468472003936768,.555056989192963],[.433990985155106,.582361996173859],[.483518004417419,.562983989715576],[.482482999563217,.57784903049469],[.42645001411438,.389798998832703],[.438998997211456,.39649498462677],[.450067013502121,.400434017181396],[.289712011814117,.368252992630005],[.276670008897781,.363372981548309],[.517862021923065,.471948027610779],[.710287988185883,.380764007568359],[.526226997375488,.573909997940063],[.895093023777008,.254140973091125],[.634069979190826,.409575998783112],[.661242008209229,.41302502155304],[.688880026340485,.409460008144379],[.725341975688934,.389131009578705],[.606630027294159,.40370500087738],[.654766023159027,.344011008739471],[.629905998706818,.346076011657715],[.680678009986877,.347265005111694],[.702096998691559,.353591024875641],[.75221198797226,.410804986953735],[.602918028831482,.842862963676453],[.719901978969574,.375599980354309],[.893692970275879,.399959981441498],[.790081977844238,.391354024410248],[.643998026847839,.534487962722778],[.528249025344849,.65040397644043],[.525849997997284,.680191040039062],[.560214996337891,.657229006290436],[.585384011268616,.66654098033905],[.549625992774963,.680860996246338],[.57122802734375,.682691991329193],[.624852001667023,.72809898853302],[.513050019741058,.547281980514526],[.51509702205658,.527251958847046],[.742246985435486,.314507007598877],[.598631024360657,.454979002475739],[.570338010787964,.548575043678284],[.578631997108459,.533622980117798],[.723087012767792,.532054007053375],[.516445994377136,.499638974666595],[.662801027297974,.282917976379395],[.70362401008606,.293271005153656],[.830704987049103,.193813979625702],[.552385985851288,.302568018436432],[.607609987258911,.353887975215912],[.645429015159607,.696707010269165],[.932694971561432,.730105042457581],[.557260990142822,.572826027870178],[.542901992797852,.584792017936707],[.6180260181427,.694710969924927],[.607590973377228,.694203019142151],[.722943007946014,.271963000297546],[.577413976192474,.563166975975037],[.614082992076874,.281386971473694],[.616907000541687,.255886018276215],[.668509006500244,.119913995265961],[.770092010498047,.232020974159241],[.635536015033722,.189248979091644],[.77039098739624,.299556016921997],[.826722025871277,.278755009174347],[.527121007442474,.666198015213013],[.553171992301941,.668527007102966],[.577238023281097,.673889994621277],[.554691970348358,.580065965652466],[.611896991729736,.693961024284363],[.59696102142334,.706539988517761],[.596370995044708,.693953037261963],[.539958000183105,.557139039039612],[.568841993808746,.692366003990173],[.547818005084991,.692366003990173],[.52461302280426,.692366003990173],[.534089982509613,.779141008853912],[.527670979499817,.736225962638855],[.526912987232208,.717857003211975],[.526877999305725,.704625964164734],[.526966989040375,.695277988910675],[.572058022022247,.695277988910675],[.573521018028259,.703539967536926],[.57683801651001,.711845993995667],[.581691026687622,.720062971115112],[.609944999217987,.639909982681274],[.986046016216278,.560034036636353],[.5867999792099,.69539999961853],[.590372025966644,.701822996139526],[.531915009021759,.601536989212036],[.577268004417419,.585934996604919],[.536915004253387,.593786001205444],[.627542972564697,.473352015018463],[.665585994720459,.495950996875763],[.588353991508484,.546862006187439],[.757824003696442,.14767599105835],[.709249973297119,.201507985591888],[.672684013843536,.256581008434296],[.600408971309662,.74900496006012],[.55826598405838,.261672019958496],[.570303976535797,.187870979309082],[.588165998458862,.109044015407562],[.711045026779175,.398952007293701],[.781069993972778,.435405015945435],[.587247014045715,.398931980133057],[.742869973182678,.355445981025696],[.572156012058258,.437651991844177],[.55186802148819,.536570012569427],[.821442008018494,.457556009292603],[.752701997756958,.457181990146637],[.71375697851181,.467626988887787],[.66711300611496,.460672974586487],[.631101012229919,.447153985500336],[.6008620262146,.432473003864288],[.523481011390686,.405627012252808],[.810747981071472,.523926019668579],[.771045982837677,.348959028720856],[.509127020835876,.562718033790588],[.595292985439301,.485023975372314],[.980530977249146,.401564002037048],[.573499977588654,.420000016689301],[.602994978427887,.548687994480133],[.733529984951019,.376977026462555],[.560611009597778,.519016981124878],[.967685997486115,.644356966018677],[.580985009670258,.387160003185272],[.537728011608124,.505385041236877],[.760966002941132,.779752969741821],[.801778972148895,.831938028335571],[.892440974712372,.54076099395752],[.816350996494293,.740260004997253],[.865594983100891,.333687007427216],[.614073991775513,.883246004581451],[.508952975273132,.579437971115112],[.617941975593567,.508316040039062],[.825608015060425,.397674977779388],[.681214988231659,.39623498916626],[.656635999679565,.400596976280212],[.603900015354156,.710216999053955],[.81208598613739,.588539004325867],[.56801301240921,.944564998149872],[.681007981300354,.898285031318665],[.733752012252808,.869701027870178],[.633830010890961,.398822009563446],[.606792986392975,.39553701877594],[.589659988880157,.391062021255493],[.805015981197357,.342108011245728],[.611334979534149,.362284004688263],[.634037971496582,.355970978736877],[.656635999679565,.355356991291046],[.681214988231659,.35834002494812],[.698584973812103,.363156020641327],[.941866993904114,.319076001644135],[.698584973812103,.387449026107788],[.584177017211914,.624107003211975],[.554318010807037,.566076993942261],[.534153997898102,.62064003944397],[.711217999458313,.819975018501282],[.664629995822906,.852871000766754],[.559099972248077,.902631998062134],[.871706008911133,.791940987110138],[.591234028339386,.373893976211548],[.544341027736664,.451583981513977],[.624562978744507,.924192011356354],[.88577002286911,.615028977394104],[.551338016986847,.695277988910675],[.551980018615723,.704632043838501],[.552887976169586,.715808033943176],[.555167973041534,.730794012546539],[.569944024085999,.767035007476807],[.593203008174896,.685675978660583],[.599261999130249,.681069016456604],[.607599973678589,.677703022956848],[.631937980651855,.663500010967255],[.752032995223999,.601315021514893],[.547226011753082,.420395016670227],[.563543975353241,.359827995300293],[.583841025829315,.368713974952698],[.586614012718201,.692366003990173],[.771915018558502,.683578014373779],[.531597018241882,.352482974529266],[.588370978832245,.804440975189209],[.52079701423645,.442565023899078],[.567984998226166,.493479013442993],[.543282985687256,.819254994392395],[.655317008495331,.745514988899231],[.621008992195129,.574018001556396],[.625559985637665,.78031200170517],[.680198013782501,.570719003677368],[.64276397228241,.604337990283966],[.704662978649139,.621529996395111],[.552012026309967,.862591981887817],[.589071989059448,.508637011051178],[.685944974422455,.775357007980347],[.645735025405884,.812640011310577],[.675342977046967,.703978002071381],[.810858011245728,.646304965019226],[.72012197971344,.714666962623596],[.866151988506317,.682704985141754],[.663187026977539,.644596993923187],[.570082008838654,.466325998306274],[.544561982154846,.548375964164734],[.562758982181549,.558784961700439],[.531987011432648,.530140042304993],[.585271000862122,.335177004337311],[.622952997684479,.32277899980545],[.655896008014679,.320163011550903],[.687132000923157,.322345972061157],[.716481983661652,.333200991153717],[.758756995201111,.382786989212036],[.897013008594513,.468769013881683],[.732392013072968,.424547016620636],[.70211398601532,.433162987232208],[.66652500629425,.433866024017334],[.633504986763,.426087975502014],[.603875994682312,.416586995124817],[.579657971858978,.409945011138916],[.992439985275269,.480777025222778],[.567192018032074,.569419980049133],[.54136598110199,.478899002075195],[.526564002037048,.546118021011353],[.523913025856018,.563830018043518],[.531529009342194,.555056989192963],[.566035985946655,.582329034805298],[.51631098985672,.563053965568542],[.5174720287323,.577877044677734],[.573594987392426,.389806985855103],[.560697972774506,.395331978797913],[.549755990505219,.399751007556915],[.710287988185883,.368252992630005],[.723330020904541,.363372981548309]]});var yL=ge(K8=>{Cp(K8,{default:()=>j8});var j8=[127,34,139,11,0,37,232,231,120,72,37,39,128,121,47,232,121,128,104,69,67,175,171,148,157,154,155,118,50,101,73,39,40,9,151,108,48,115,131,194,204,211,74,40,185,80,42,183,40,92,186,230,229,118,202,212,214,83,18,17,76,61,146,160,29,30,56,157,173,106,204,194,135,214,192,203,165,98,21,71,68,51,45,4,144,24,23,77,146,91,205,50,187,201,200,18,91,106,182,90,91,181,85,84,17,206,203,36,148,171,140,92,40,39,193,189,244,159,158,28,247,246,161,236,3,196,54,68,104,193,168,8,117,228,31,189,193,55,98,97,99,126,47,100,166,79,218,155,154,26,209,49,131,135,136,150,47,126,217,223,52,53,45,51,134,211,170,140,67,69,108,43,106,91,230,119,120,226,130,247,63,53,52,238,20,242,46,70,156,78,62,96,46,53,63,143,34,227,173,155,133,123,117,111,44,125,19,236,134,51,216,206,205,154,153,22,39,37,167,200,201,208,36,142,100,57,212,202,20,60,99,28,158,157,35,226,113,160,159,27,204,202,210,113,225,46,43,202,204,62,76,77,137,123,116,41,38,72,203,129,142,64,98,240,49,102,64,41,73,74,212,216,207,42,74,184,169,170,211,170,149,176,105,66,69,122,6,168,123,147,187,96,77,90,65,55,107,89,90,180,101,100,120,63,105,104,93,137,227,15,86,85,129,102,49,14,87,86,55,8,9,100,47,121,145,23,22,88,89,179,6,122,196,88,95,96,138,172,136,215,58,172,115,48,219,42,80,81,195,3,51,43,146,61,171,175,199,81,82,38,53,46,225,144,163,110,246,33,7,52,65,66,229,228,117,34,127,234,107,108,69,109,108,151,48,64,235,62,78,191,129,209,126,111,35,143,163,161,246,117,123,50,222,65,52,19,125,141,221,55,65,3,195,197,25,7,33,220,237,44,70,71,139,122,193,245,247,130,33,71,21,162,153,158,159,170,169,150,188,174,196,216,186,92,144,160,161,2,97,167,141,125,241,164,167,37,72,38,12,145,159,160,38,82,13,63,68,71,226,35,111,158,153,154,101,50,205,206,92,165,209,198,217,165,167,97,220,115,218,133,112,243,239,238,241,214,135,169,190,173,133,171,208,32,125,44,237,86,87,178,85,86,179,84,85,180,83,84,181,201,83,182,137,93,132,76,62,183,61,76,184,57,61,185,212,57,186,214,207,187,34,143,156,79,239,237,123,137,177,44,1,4,201,194,32,64,102,129,213,215,138,59,166,219,242,99,97,2,94,141,75,59,235,24,110,228,25,130,226,23,24,229,22,23,230,26,22,231,112,26,232,189,190,243,221,56,190,28,56,221,27,28,222,29,27,223,30,29,224,247,30,225,238,79,20,166,59,75,60,75,240,147,177,215,20,79,166,187,147,213,112,233,244,233,128,245,128,114,188,114,217,174,131,115,220,217,198,236,198,131,134,177,132,58,143,35,124,110,163,7,228,110,25,356,389,368,11,302,267,452,350,349,302,303,269,357,343,277,452,453,357,333,332,297,175,152,377,384,398,382,347,348,330,303,304,270,9,336,337,278,279,360,418,262,431,304,408,409,310,415,407,270,409,410,450,348,347,422,430,434,313,314,17,306,307,375,387,388,260,286,414,398,335,406,418,364,367,416,423,358,327,251,284,298,281,5,4,373,374,253,307,320,321,425,427,411,421,313,18,321,405,406,320,404,405,315,16,17,426,425,266,377,400,369,322,391,269,417,465,464,386,257,258,466,260,388,456,399,419,284,332,333,417,285,8,346,340,261,413,441,285,327,460,328,355,371,329,392,439,438,382,341,256,429,420,360,364,394,379,277,343,437,443,444,283,275,440,363,431,262,369,297,338,337,273,375,321,450,451,349,446,342,467,293,334,282,458,461,462,276,353,383,308,324,325,276,300,293,372,345,447,382,398,362,352,345,340,274,1,19,456,248,281,436,427,425,381,256,252,269,391,393,200,199,428,266,330,329,287,273,422,250,462,328,258,286,384,265,353,342,387,259,257,424,431,430,342,353,276,273,335,424,292,325,307,366,447,345,271,303,302,423,266,371,294,455,460,279,278,294,271,272,304,432,434,427,272,407,408,394,430,431,395,369,400,334,333,299,351,417,168,352,280,411,325,319,320,295,296,336,319,403,404,330,348,349,293,298,333,323,454,447,15,16,315,358,429,279,14,15,316,285,336,9,329,349,350,374,380,252,318,402,403,6,197,419,318,319,325,367,364,365,435,367,397,344,438,439,272,271,311,195,5,281,273,287,291,396,428,199,311,271,268,283,444,445,373,254,339,263,466,249,282,334,296,449,347,346,264,447,454,336,296,299,338,10,151,278,439,455,292,407,415,358,371,355,340,345,372,390,249,466,346,347,280,442,443,282,19,94,370,441,442,295,248,419,197,263,255,359,440,275,274,300,383,368,351,412,465,263,467,466,301,368,389,380,374,386,395,378,379,412,351,419,436,426,322,373,390,388,2,164,393,370,462,461,164,0,267,302,11,12,374,373,387,268,12,13,293,300,301,446,261,340,385,384,381,330,266,425,426,423,391,429,355,437,391,327,326,440,457,438,341,382,362,459,457,461,434,430,394,414,463,362,396,369,262,354,461,457,316,403,402,315,404,403,314,405,404,313,406,405,421,418,406,366,401,361,306,408,407,291,409,408,287,410,409,432,436,410,434,416,411,264,368,383,309,438,457,352,376,401,274,275,4,421,428,262,294,327,358,433,416,367,289,455,439,462,370,326,2,326,370,305,460,455,254,449,448,255,261,446,253,450,449,252,451,450,256,452,451,341,453,452,413,464,463,441,413,414,258,442,441,257,443,442,259,444,443,260,445,444,467,342,445,459,458,250,289,392,290,290,328,460,376,433,435,250,290,392,411,416,433,341,463,464,453,464,465,357,465,412,343,412,399,360,363,440,437,399,456,420,456,363,401,435,288,372,383,353,339,255,249,448,261,255,133,243,190,133,155,112,33,246,247,33,130,25,398,384,286,362,398,414,362,463,341,263,359,467,263,249,255,466,467,260,75,60,166,238,239,79,162,127,139,72,11,37,121,232,120,73,72,39,114,128,47,233,232,128,103,104,67,152,175,148,173,157,155,119,118,101,74,73,40,107,9,108,49,48,131,32,194,211,184,74,185,191,80,183,185,40,186,119,230,118,210,202,214,84,83,17,77,76,146,161,160,30,190,56,173,182,106,194,138,135,192,129,203,98,54,21,68,5,51,4,145,144,23,90,77,91,207,205,187,83,201,18,181,91,182,180,90,181,16,85,17,205,206,36,176,148,140,165,92,39,245,193,244,27,159,28,30,247,161,174,236,196,103,54,104,55,193,8,111,117,31,221,189,55,240,98,99,142,126,100,219,166,218,112,155,26,198,209,131,169,135,150,114,47,217,224,223,53,220,45,134,32,211,140,109,67,108,146,43,91,231,230,120,113,226,247,105,63,52,241,238,242,124,46,156,95,78,96,70,46,63,116,143,227,116,123,111,1,44,19,3,236,51,207,216,205,26,154,22,165,39,167,199,200,208,101,36,100,43,57,202,242,20,99,56,28,157,124,35,113,29,160,27,211,204,210,124,113,46,106,43,204,96,62,77,227,137,116,73,41,72,36,203,142,235,64,240,48,49,64,42,41,74,214,212,207,183,42,184,210,169,211,140,170,176,104,105,69,193,122,168,50,123,187,89,96,90,66,65,107,179,89,180,119,101,120,68,63,104,234,93,227,16,15,85,209,129,49,15,14,86,107,55,9,120,100,121,153,145,22,178,88,179,197,6,196,89,88,96,135,138,136,138,215,172,218,115,219,41,42,81,5,195,51,57,43,61,208,171,199,41,81,38,224,53,225,24,144,110,105,52,66,118,229,117,227,34,234,66,107,69,10,109,151,219,48,235,183,62,191,142,129,126,116,111,143,7,163,246,118,117,50,223,222,52,94,19,141,222,221,65,196,3,197,45,220,44,156,70,139,188,122,245,139,71,162,145,153,159,149,170,150,122,188,196,206,216,92,163,144,161,164,2,167,242,141,241,0,164,37,11,72,12,144,145,160,12,38,13,70,63,71,31,226,111,157,158,154,36,101,205,203,206,165,126,209,217,98,165,97,237,220,218,237,239,241,210,214,169,140,171,32,241,125,237,179,86,178,180,85,179,181,84,180,182,83,181,194,201,182,177,137,132,184,76,183,185,61,184,186,57,185,216,212,186,192,214,187,139,34,156,218,79,237,147,123,177,45,44,4,208,201,32,98,64,129,192,213,138,235,59,219,141,242,97,97,2,141,240,75,235,229,24,228,31,25,226,230,23,229,231,22,230,232,26,231,233,112,232,244,189,243,189,221,190,222,28,221,223,27,222,224,29,223,225,30,224,113,247,225,99,60,240,213,147,215,60,20,166,192,187,213,243,112,244,244,233,245,245,128,188,188,114,174,134,131,220,174,217,236,236,198,134,215,177,58,156,143,124,25,110,7,31,228,25,264,356,368,0,11,267,451,452,349,267,302,269,350,357,277,350,452,357,299,333,297,396,175,377,381,384,382,280,347,330,269,303,270,151,9,337,344,278,360,424,418,431,270,304,409,272,310,407,322,270,410,449,450,347,432,422,434,18,313,17,291,306,375,259,387,260,424,335,418,434,364,416,391,423,327,301,251,298,275,281,4,254,373,253,375,307,321,280,425,411,200,421,18,335,321,406,321,320,405,314,315,17,423,426,266,396,377,369,270,322,269,413,417,464,385,386,258,248,456,419,298,284,333,168,417,8,448,346,261,417,413,285,326,327,328,277,355,329,309,392,438,381,382,256,279,429,360,365,364,379,355,277,437,282,443,283,281,275,363,395,431,369,299,297,337,335,273,321,348,450,349,359,446,467,283,293,282,250,458,462,300,276,383,292,308,325,283,276,293,264,372,447,346,352,340,354,274,19,363,456,281,426,436,425,380,381,252,267,269,393,421,200,428,371,266,329,432,287,422,290,250,328,385,258,384,446,265,342,386,387,257,422,424,430,445,342,276,422,273,424,306,292,307,352,366,345,268,271,302,358,423,371,327,294,460,331,279,294,303,271,304,436,432,427,304,272,408,395,394,431,378,395,400,296,334,299,6,351,168,376,352,411,307,325,320,285,295,336,320,319,404,329,330,349,334,293,333,366,323,447,316,15,315,331,358,279,317,14,316,8,285,9,277,329,350,253,374,252,319,318,403,351,6,419,324,318,325,397,367,365,288,435,397,278,344,439,310,272,311,248,195,281,375,273,291,175,396,199,312,311,268,276,283,445,390,373,339,295,282,296,448,449,346,356,264,454,337,336,299,337,338,151,294,278,455,308,292,415,429,358,355,265,340,372,388,390,466,352,346,280,295,442,282,354,19,370,285,441,295,195,248,197,457,440,274,301,300,368,417,351,465,251,301,389,385,380,386,394,395,379,399,412,419,410,436,322,387,373,388,326,2,393,354,370,461,393,164,267,268,302,12,386,374,387,312,268,13,298,293,301,265,446,340,380,385,381,280,330,425,322,426,391,420,429,437,393,391,326,344,440,438,458,459,461,364,434,394,428,396,262,274,354,457,317,316,402,316,315,403,315,314,404,314,313,405,313,421,406,323,366,361,292,306,407,306,291,408,291,287,409,287,432,410,427,434,411,372,264,383,459,309,457,366,352,401,1,274,4,418,421,262,331,294,358,435,433,367,392,289,439,328,462,326,94,2,370,289,305,455,339,254,448,359,255,446,254,253,449,253,252,450,252,256,451,256,341,452,414,413,463,286,441,414,286,258,441,258,257,442,257,259,443,259,260,444,260,467,445,309,459,250,305,289,290,305,290,460,401,376,435,309,250,392,376,411,433,453,341,464,357,453,465,343,357,412,437,343,399,344,360,440,420,437,456,360,420,363,361,401,288,265,372,353,390,339,249,339,448,255]});var SL=ge(cs=>{const Sn=Ct(),$8=aL(),bL=ep(),X8=mL(),J8=vL(),Z8=yL().default;cs.uv_coords=J8;cs.triangulation=Z8;async function Q8(n){return $8.load(n)}async function e7(n){return Sn.loadGraphModel(n,{fromTFHub:n.includes("tfhub.dev")})}async function t7(n){return Sn.loadGraphModel(n,{fromTFHub:n.includes("tfhub.dev")})}async function n7(n){const t=await Promise.all([Q8(n),e7(n.mesh.modelPath),t7(n.iris.modelPath)]),e=new wL(t[0],t[1],t[2],n);return e}cs.load=n7;class wL{constructor(n,t,e,i){this.pipeline=new X8.Pipeline(n,t,e,i),this.config=i}async estimateFaces(n,t){t&&(this.config=t);const e=Sn.tidy(()=>(n instanceof Sn.Tensor||(n=Sn.browser.fromPixels(n)),n.toFloat().expandDims(0))),i=[],r=await this.pipeline.predict(e,this.config.iris.enabled,this.config.mesh.enabled);if(e.dispose(),!r)return i;for(const a of r){const s=a.confidence.arraySync();if(s>=this.config.detector.minConfidence){const o={confidence:s||0,box:a.box?[a.box.startPoint[0],a.box.startPoint[1],a.box.endPoint[0]-a.box.startPoint[0],a.box.endPoint[1]-a.box.startPoint[1]]:0,mesh:a.coords?a.coords.arraySync():null,image:a.image?Sn.clone(a.image):null},l={};if(o.mesh&&o.mesh.length>0)for(const u in bL.MESH_ANNOTATIONS)(this.config.iris.enabled||u.includes("Iris")===!1)&&(l[u]=bL.MESH_ANNOTATIONS[u].map(c=>o.mesh[c]));o.annotations=l,i.push(o)}Sn.dispose(a.confidence),Sn.dispose(a.image),Sn.dispose(a.coords),Sn.dispose(a)}return Sn.dispose(r),i}}cs.MediaPipeFaceMesh=wL});var AL=ge(LL=>{const $t=Ct(),sa={};let IL={age:0,gender:""},lp=0;async function i7(n,t){const e=$t.tidy(()=>{const i=$t.browser.fromPixels(n),r=$t.image.resizeBilinear(i,[t,t]),a=$t.cast($t.expandDims(r,0),"float32");return a});return e}async function r7(n,t){if(lp+=1,lp>=t.face.age.skipFrames)return lp=0,IL;!sa.age&&t.face.age.enabled&&(sa.age=await $t.loadGraphModel(t.face.age.modelPath)),!sa.gender&&t.face.gender.enabled&&(sa.gender=await $t.loadGraphModel(t.face.gender.modelPath));let e;if(n instanceof $t.Tensor){const r=$t.image.resizeBilinear(n,[t.face.age.inputSize,t.face.age.inputSize],!1);e=$t.mul(r,[255]),$t.dispose(r)}else e=await i7(n,t.face.age.inputSize);const i={};if(t.face.age.enabled){const r=await sa.age.predict(e);i.age=Math.trunc(10*r.dataSync()[0])/10,$t.dispose(r)}if(t.face.gender.enabled){const r=await sa.gender.predict(e);i.gender=Math.trunc(100*r.dataSync()[0])<50?"female":"male",$t.dispose(r)}return $t.dispose(e),IL=i,i}LL.predict=r7});var xL=ge(TL=>{const NL=Ct();class a7{constructor(n,t){this.model=n,this.outputStride=t;const e=this.model.inputs[0].shape;NL.util.assert(e[1]===-1&&e[2]===-1,()=>`Input shape [${e[1]}, ${e[2]}] must both be equal to or -1`)}predict(n){return NL.tidy(()=>{const t=this.preprocessInput(n.toFloat()),e=t.expandDims(0),i=this.model.predict(e),r=i.map(s=>s.squeeze([0])),a=this.nameOutputResults(r);return{heatmapScores:a.heatmap.sigmoid(),offsets:a.offsets,displacementFwd:a.displacementFwd,displacementBwd:a.displacementBwd}})}dispose(){this.model.dispose()}}TL.BaseModel=a7});var up=ge(CL=>{const RL=Ct(),s7=xL();class o7 extends s7.BaseModel{preprocessInput(n){return RL.tidy(()=>RL.div(n,127.5).sub(1))}nameOutputResults(n){const[t,e,i,r]=n;return{offsets:t,heatmap:e,displacementFwd:i,displacementBwd:r}}}CL.MobileNet=o7});var EL=ge(OL=>{function cp(n){return Math.floor(n/2)}class l7{constructor(n,t){this.priorityQueue=new Array(n),this.numberOfElements=-1,this.getElementValue=t}enqueue(n){this.priorityQueue[++this.numberOfElements]=n,this.swim(this.numberOfElements)}dequeue(){const n=this.priorityQueue[0];return this.exchange(0,this.numberOfElements--),this.sink(0),this.priorityQueue[this.numberOfElements+1]=null,n}empty(){return this.numberOfElements===-1}size(){return this.numberOfElements+1}all(){return this.priorityQueue.slice(0,this.numberOfElements+1)}max(){return this.priorityQueue[0]}swim(n){for(;n>0&&this.less(cp(n),n);)this.exchange(n,cp(n)),n=cp(n)}sink(n){for(;2*n<=this.numberOfElements;){let t=2*n;if(t{const u7=EL();function c7(n,t,e,i,r,a){const[s,o]=a.shape;let l=!0;const u=Math.max(e-r,0),c=Math.min(e+r+1,s);for(let h=u;ht){l=!1;break}if(!l)break}return l}function h7(n,t,e){const[i,r,a]=e.shape,s=new u7.MaxHeap(i*r*a,({score:o})=>o);for(let o=0;o{Ln.partNames=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"];Ln.NUM_KEYPOINTS=Ln.partNames.length;Ln.partIds=Ln.partNames.reduce((n,t,e)=>(n[t]=e,n),{});const d7=[["leftHip","leftShoulder"],["leftElbow","leftShoulder"],["leftElbow","leftWrist"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["rightHip","rightShoulder"],["rightElbow","rightShoulder"],["rightElbow","rightWrist"],["rightHip","rightKnee"],["rightKnee","rightAnkle"],["leftShoulder","rightShoulder"],["leftHip","rightHip"]];Ln.poseChain=[["nose","leftEye"],["leftEye","leftEar"],["nose","rightEye"],["rightEye","rightEar"],["nose","leftShoulder"],["leftShoulder","leftElbow"],["leftElbow","leftWrist"],["leftShoulder","leftHip"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["nose","rightShoulder"],["rightShoulder","rightElbow"],["rightElbow","rightWrist"],["rightShoulder","rightHip"],["rightHip","rightKnee"],["rightKnee","rightAnkle"]];Ln.connectedPartIndices=d7.map(([n,t])=>[Ln.partIds[n],Ln.partIds[t]]);Ln.partChannels=["left_face","right_face","right_upper_leg_front","right_lower_leg_back","right_upper_leg_back","left_lower_leg_front","left_upper_leg_front","left_upper_leg_back","left_lower_leg_back","right_feet","right_lower_leg_front","left_feet","torso_front","torso_back","right_upper_arm_front","right_upper_arm_back","right_lower_arm_back","left_lower_arm_front","left_upper_arm_front","left_upper_arm_back","left_lower_arm_back","right_hand","right_lower_arm_front","left_hand"]});var dp=ge(Ni=>{const p7=dr();function FL(n,t,e,i){return{y:i.get(n,t,e),x:i.get(n,t,e+p7.NUM_KEYPOINTS)}}Ni.getOffsetPoint=FL;function f7(n,t,e){const{heatmapY:i,heatmapX:r,id:a}=n,{y:s,x:o}=FL(i,r,a,e);return{x:n.heatmapX*t+o,y:n.heatmapY*t+s}}Ni.getImageCoords=f7;function m7(n,t){const e=new Array(t);for(let i=0;ie?e:n}Ni.clamp=hp;function g7(n,t,e,i){const r=e-n,a=i-t;return r*r+a*a}Ni.squaredDistance=g7;function v7(n,t){return{x:n.x+t.x,y:n.y+t.y}}Ni.addVectors=v7;function y7(n,t,e){return{y:hp(n.y,t,e),x:hp(n.x,t,e)}}Ni.clampVector=y7});var PL=ge(WL=>{const hs=dr(),oa=dp(),UL=hs.poseChain.map(([n,t])=>[hs.partIds[n],hs.partIds[t]]),pp=UL.map(([,n])=>n),BL=UL.map(([n])=>n);function b7(n,t,e){const i=e.shape[2]/2;return{y:e.get(t.y,t.x,n),x:e.get(t.y,t.x,i+n)}}function fp(n,t,e,i){return{y:oa.clamp(Math.round(n.y/t),0,e-1),x:oa.clamp(Math.round(n.x/t),0,i-1)}}function zL(n,t,e,i,r,a,s,o=2){const[l,u]=i.shape,c=fp(t.position,a,l,u),h=b7(n,c,s),d=oa.addVectors(t.position,h);let p=d;for(let g=0;g=0;--d){const p=pp[d],f=BL[d];l[p]&&!l[f]&&(l[f]=zL(d,l[p],f,t,e,i,a))}for(let d=0;d{const S7=kL(),L7=PL(),ML=dp();function HL(n,t,{x:e,y:i},r){return n.some(({keypoints:a})=>{const s=a[r].position;return ML.squaredDistance(i,e,s.y,s.x)<=t})}function I7(n,t,e){const i=e.reduce((r,{position:a,score:s},o)=>(HL(n,t,a,o)||(r+=s),r),0);return i/e.length}const A7=1;function T7(n,t,e,i,r,a,s=.5,o=20){const l=[],u=S7.buildPartWithScoreQueue(s,A7,n),c=o*o;for(;l.length{const Zn=Ct(),gp=dr();function N7(n,t){const e=t.shape[0],i=new Float32Array(e);for(let r=0;r{const i=VL(n,e);return n.toTensor().mul(Zn.scalar(t,"int32")).toFloat().add(i)})}ds.getOffsetPoints=C7;function R7(n,t){return Zn.tidy(()=>{const e=n.div(Zn.scalar(t,"int32"));return n.sub(e.mul(Zn.scalar(t,"int32")))})}function O7(n){const[t,e,i]=n.shape;return Zn.tidy(()=>{const r=n.reshape([t*e,i]),a=r.argMax(0),s=a.div(Zn.scalar(e,"int32")).expandDims(1),o=R7(a,e).expandDims(1);return Zn.concat([s,o],1)})}ds.argmax2d=O7});var yp=ge(GL=>{const E7=dr(),vp=qL();async function D7(n,t,e){let i=0;const r=vp.argmax2d(n),a=await Promise.all([n.buffer(),t.buffer(),r.buffer()]),s=a[0],o=a[1],l=a[2],u=vp.getOffsetPoints(l,e,o),c=await u.buffer(),h=Array.from(vp.getPointsConfidence(s,l)),d=h.map((p,f)=>(i+=p,{position:{y:c.get(f,0),x:c.get(f,1)},part:E7.partNames[f],score:p}));return r.dispose(),u.dispose(),{keypoints:d,score:i/d.length}}GL.decodeSinglePose=D7});var wp=ge(ln=>{const la=Ct(),k7=dr();function F7(n,t,e){return n(F7(n[i].score,n[r].score,t)||e.push([n[i],n[r]]),e),[])}ln.getAdjacentKeyPoints=W7;const{NEGATIVE_INFINITY:YL,POSITIVE_INFINITY:KL}=Number;function jL(n){return n.reduce(({maxX:t,maxY:e,minX:i,minY:r},{position:{x:a,y:s}})=>({maxX:Math.max(t,a),maxY:Math.max(e,s),minX:Math.min(i,a),minY:Math.min(r,s)}),{maxX:YL,maxY:YL,minX:KL,minY:KL})}ln.getBoundingBox=jL;function U7(n){const{minX:t,minY:e,maxX:i,maxY:r}=jL(n);return[{x:t,y:e},{x:i,y:e},{x:i,y:r},{x:t,y:r}]}ln.getBoundingBoxPoints=U7;async function B7(n){return Promise.all(n.map(t=>t.buffer()))}ln.toTensorBuffers3D=B7;function $L(n,t,e,i=0,r=0){return{score:n.score,keypoints:n.keypoints.map(({score:a,part:s,position:o})=>({score:a,part:s,position:{x:o.x*e+r,y:o.y*t+i}}))}}ln.scalePose=$L;function XL(n,t,e,i=0,r=0){return e===1&&t===1&&i===0&&r===0?n:n.map(a=>$L(a,t,e,i,r))}ln.scalePoses=XL;function JL(n){return n instanceof la.Tensor?[n.shape[0],n.shape[1]]:[n.height,n.width]}ln.getInputTensorDimensions=JL;function bp(n){return n instanceof la.Tensor?n:la.browser.fromPixels(n)}ln.toInputTensor=bp;function z7(n,t,e){return la.tidy(()=>{const i=bp(n);return i.resizeBilinear([t,e])})}ln.toResizedInputTensor=z7;function P7(n,[t,e]){const[i,r]=JL(n),a=e/t,s=r/i;let[o,l,u,c]=[0,0,0,0];s{let d=bp(n);return d=la.pad3d(d,[[o,l],[u,c],[0,0]]),d.resizeBilinear([t,e])});return{resized:h,padding:{top:o,left:u,right:c,bottom:l}}}ln.padAndResizeTo=P7;function _7(n,[t,e],[i,r],a){const s=(t+a.top+a.bottom)/i,o=(e+a.left+a.right)/r,l=XL(n,s,o,-a.top,-a.left);return l}ln.scaleAndFlipPoses=_7});var QL=ge(Sp=>{const M7=Ct(),H7=up(),V7=mp(),q7=yp(),pr=wp();class ZL{constructor(n,t){this.baseModel=n,this.inputResolution=t}async estimateMultiplePoses(n,t){const e=this.baseModel.outputStride,i=this.inputResolution,[r,a]=pr.getInputTensorDimensions(n),{resized:s,padding:o}=pr.padAndResizeTo(n,[i,i]),{heatmapScores:l,offsets:u,displacementFwd:c,displacementBwd:h}=this.baseModel.predict(s),d=await pr.toTensorBuffers3D([l,u,c,h]),p=d[0],f=d[1],m=d[2],g=d[3],v=await V7.decodeMultiplePoses(p,f,m,g,e,t.maxDetections,t.scoreThreshold,t.nmsRadius),b=pr.scaleAndFlipPoses(v,[r,a],[i,i],o);return l.dispose(),u.dispose(),c.dispose(),h.dispose(),s.dispose(),b}async estimateSinglePose(n){const t=this.baseModel.outputStride,e=this.inputResolution,[i,r]=pr.getInputTensorDimensions(n),{resized:a,padding:s}=pr.padAndResizeTo(n,e),{heatmapScores:o,offsets:l,displacementFwd:u,displacementBwd:c}=this.baseModel.predict(a),h=await q7.decodeSinglePose(o,l,t),d=[h],p=pr.scaleAndFlipPoses(d,[i,r],[e,e],s);return o.dispose(),l.dispose(),u.dispose(),c.dispose(),a.dispose(),p[0]}dispose(){this.baseModel.dispose()}}Sp.PoseNet=ZL;async function G7(n){const t=n.outputStride,e=await M7.loadGraphModel(n.modelPath),i=new H7.MobileNet(e,t);return new ZL(i,n.inputResolution)}async function Y7(n){return G7(n)}Sp.load=Y7});var tI=ge(Mt=>{const K7=up(),eI=QL(),j7=mp(),$7=yp(),Jo=dr(),ps=wp();Mt.load=eI.load;Mt.PoseNet=eI.PoseNet;Mt.MobileNet=K7.MobileNet;Mt.decodeMultiplePoses=j7.decodeMultiplePoses;Mt.decodeSinglePose=$7.decodeSinglePose;Mt.partChannels=Jo.partChannels;Mt.partIds=Jo.partIds;Mt.partNames=Jo.partNames;Mt.poseChain=Jo.poseChain;Mt.getAdjacentKeyPoints=ps.getAdjacentKeyPoints;Mt.getBoundingBox=ps.getBoundingBox;Mt.getBoundingBoxPoints=ps.getBoundingBoxPoints;Mt.scaleAndFlipPoses=ps.scaleAndFlipPoses;Mt.scalePose=ps.scalePose});var Ap=ge(xi=>{const X7=Ct();function Lp(n){return[Math.abs(n.endPoint[0]-n.startPoint[0]),Math.abs(n.endPoint[1]-n.startPoint[1])]}xi.getBoxSize=Lp;function Ip(n){return[n.startPoint[0]+(n.endPoint[0]-n.startPoint[0])/2,n.startPoint[1]+(n.endPoint[1]-n.startPoint[1])/2]}xi.getBoxCenter=Ip;function J7(n,t,e){const i=t.shape[1],r=t.shape[2],a=[[n.startPoint[1]/i,n.startPoint[0]/r,n.endPoint[1]/i,n.endPoint[0]/r]];return X7.image.cropAndResize(t,a,[0],e)}xi.cutBoxFromImageAndResize=J7;function Z7(n,t){const e=[n.startPoint[0]*t[0],n.startPoint[1]*t[1]],i=[n.endPoint[0]*t[0],n.endPoint[1]*t[1]],r=n.palmLandmarks.map(a=>{const s=[a[0]*t[0],a[1]*t[1]];return s});return{startPoint:e,endPoint:i,palmLandmarks:r}}xi.scaleBoxCoordinates=Z7;function Q7(n,t=1.5){const e=Ip(n),i=Lp(n),r=[t*i[0]/2,t*i[1]/2],a=[e[0]-r[0],e[1]-r[1]],s=[e[0]+r[0],e[1]+r[1]];return{startPoint:a,endPoint:s,palmLandmarks:n.palmLandmarks}}xi.enlargeBox=Q7;function eH(n){const t=Ip(n),e=Lp(n),i=Math.max(...e),r=i/2,a=[t[0]-r,t[1]-r],s=[t[0]+r,t[1]+r];return{startPoint:a,endPoint:s,palmLandmarks:n.palmLandmarks}}xi.squarifyBox=eH;function tH(n,t){const e=[n.endPoint[0]-n.startPoint[0],n.endPoint[1]-n.startPoint[1]],i=[e[0]*t[0],e[1]*t[1]],r=[n.startPoint[0]+i[0],n.startPoint[1]+i[1]],a=[n.endPoint[0]+i[0],n.endPoint[1]+i[1]];return{startPoint:r,endPoint:a,palmLandmarks:n.palmLandmarks}}xi.shiftBox=tH});var iI=ge(nI=>{const Ue=Ct(),nH=Ap();class iH{constructor(n,t,e,i,r,a){this.model=n,this.width=t,this.height=e,this.iouThreshold=r,this.scoreThreshold=a,this.anchors=i.map(s=>[s.x_center,s.y_center]),this.anchorsTensor=Ue.tensor2d(this.anchors),this.inputSizeTensor=Ue.tensor1d([t,e]),this.doubleInputSizeTensor=Ue.tensor1d([t*2,e*2])}normalizeBoxes(n){return Ue.tidy(()=>{const t=Ue.slice(n,[0,0],[-1,2]),e=Ue.slice(n,[0,2],[-1,2]),i=Ue.add(Ue.div(t,this.inputSizeTensor),this.anchorsTensor),r=Ue.div(e,this.doubleInputSizeTensor),a=Ue.mul(Ue.sub(i,r),this.inputSizeTensor),s=Ue.mul(Ue.add(i,r),this.inputSizeTensor);return Ue.concat2d([a,s],1)})}normalizeLandmarks(n,t){return Ue.tidy(()=>{const e=Ue.add(Ue.div(n.reshape([-1,7,2]),this.inputSizeTensor),this.anchors[t]);return Ue.mul(e,this.inputSizeTensor)})}async getBoundingBoxes(n){const t=Ue.tidy(()=>Ue.mul(Ue.sub(n,.5),2));let e;if(Ue.getBackend()==="webgl"){const f=Ue.env().get("WEBGL_PACK_DEPTHWISECONV");Ue.env().set("WEBGL_PACK_DEPTHWISECONV",!0),e=this.model.predict(t),Ue.env().set("WEBGL_PACK_DEPTHWISECONV",f)}else e=this.model.predict(t);const i=e.squeeze(),r=Ue.tidy(()=>Ue.sigmoid(Ue.slice(i,[0,0],[-1,1])).squeeze()),a=Ue.slice(i,[0,1],[-1,4]),s=this.normalizeBoxes(a),o=await Ue.image.nonMaxSuppressionAsync(s,r,1,this.iouThreshold,this.scoreThreshold),l=await o.array(),u=[t,e,o,i,s,a,r];if(l.length===0)return u.forEach(f=>f.dispose()),null;const c=l[0],h=Ue.slice(s,[c,0],[1,-1]),d=Ue.slice(i,[c,5],[1,14]),p=Ue.tidy(()=>this.normalizeLandmarks(d,c).reshape([-1,2]));return u.push(d),u.forEach(f=>f.dispose()),{boxes:h,palmLandmarks:p}}async estimateHandBounds(n){const t=n.shape[1],e=n.shape[2],i=Ue.tidy(()=>n.resizeBilinear([this.width,this.height]).div(255)),r=await this.getBoundingBoxes(i);if(r===null)return i.dispose(),null;const a=r.boxes.arraySync(),s=a[0].slice(0,2),o=a[0].slice(2,4),l=r.palmLandmarks.arraySync();return i.dispose(),r.boxes.dispose(),r.palmLandmarks.dispose(),nH.scaleBoxCoordinates({startPoint:s,endPoint:o,palmLandmarks:l},[e/this.width,t/this.height])}}nI.HandDetector=iH});var aI=ge(rI=>{rI.MESH_ANNOTATIONS={thumb:[1,2,3,4],indexFinger:[5,6,7,8],middleFinger:[9,10,11,12],ringFinger:[13,14,15,16],pinky:[17,18,19,20],palmBase:[0]}});var cI=ge(Ci=>{function sI(n){return n-2*Math.PI*Math.floor((n+Math.PI)/(2*Math.PI))}Ci.normalizeRadians=sI;function rH(n,t){const e=Math.PI/2-Math.atan2(-(t[1]-n[1]),t[0]-n[0]);return sI(e)}Ci.computeRotation=rH;const oI=(n,t)=>[[1,0,n],[0,1,t],[0,0,1]];function ua(n,t){let e=0;for(let i=0;i{const ca=Ct(),zn=Ap(),Ri=cI(),lH=.8,uH=[0,-.4],cH=3,hH=[0,-.1],dH=1.65,dI=[0,5,9,13,17,1,2],pH=0,fH=2;class mH{constructor(n,t,e,i,r,a){this.regionsOfInterest=[],this.runsWithoutHandDetector=0,this.boundingBoxDetector=n,this.meshDetector=t,this.maxContinuousChecks=r,this.detectionConfidence=a,this.meshWidth=e,this.meshHeight=i,this.maxHandsNumber=1}getBoxForPalmLandmarks(n,t){const e=n.map(r=>{const a=[...r,1];return Ri.rotatePoint(a,t)}),i=this.calculateLandmarksBoundingBox(e);return zn.enlargeBox(zn.squarifyBox(zn.shiftBox(i,uH)),cH)}getBoxForHandLandmarks(n){const t=this.calculateLandmarksBoundingBox(n),e=zn.enlargeBox(zn.squarifyBox(zn.shiftBox(t,hH)),dH),i=[];for(let r=0;r[a[0]*(d[0]-this.meshWidth/2),a[1]*(d[1]-this.meshHeight/2),d[2]]),o=Ri.buildRotationMatrix(e,[0,0]),l=s.map(d=>{const p=Ri.rotatePoint(d,o);return[...p,d[2]]}),u=Ri.invertTransformMatrix(i),c=[...zn.getBoxCenter(t),1],h=[Ri.dot(c,u[0]),Ri.dot(c,u[1])];return l.map(d=>[d[0]+h[0],d[1]+h[1],d[2]])}async estimateHand(n,t){const e=this.shouldUpdateRegionsOfInterest();if(e===!0){const L=await this.boundingBoxDetector.estimateHandBounds(n);if(L===null)return n.dispose(),this.regionsOfInterest=[],null;this.updateRegionsOfInterest(L,!0),this.runsWithoutHandDetector=0}else this.runsWithoutHandDetector++;const i=this.regionsOfInterest[0],r=Ri.computeRotation(i.palmLandmarks[pH],i.palmLandmarks[fH]),a=zn.getBoxCenter(i),s=[a[0]/n.shape[2],a[1]/n.shape[1]],o=ca.image.rotateWithOffset(n,r,0,s),l=Ri.buildRotationMatrix(-r,a),u=e?this.getBoxForPalmLandmarks(i.palmLandmarks,l):i,c=zn.cutBoxFromImageAndResize(u,o,[this.meshWidth,this.meshHeight]),h=c.div(255);c.dispose(),o.dispose();let d;if(ca.getBackend()==="webgl"){const L=ca.env().get("WEBGL_PACK_DEPTHWISECONV");ca.env().set("WEBGL_PACK_DEPTHWISECONV",!0),d=this.meshDetector.predict(h),ca.env().set("WEBGL_PACK_DEPTHWISECONV",L)}else d=this.meshDetector.predict(h);const[p,f]=d;h.dispose();const m=p.dataSync()[0];if(p.dispose(),ma[0]),e=n.map(a=>a[1]),i=[Math.min(...t),Math.min(...e)],r=[Math.max(...t),Math.max(...e)];return{startPoint:i,endPoint:r}}updateRegionsOfInterest(n,t){if(t)this.regionsOfInterest=[n];else{const e=this.regionsOfInterest[0];let i=0;if(e!=null&&e.startPoint!=null){const[r,a]=n.startPoint,[s,o]=n.endPoint,[l,u]=e.startPoint,[c,h]=e.endPoint,d=Math.max(r,l),p=Math.max(a,u),f=Math.min(s,c),m=Math.min(o,h),g=(f-d)*(m-p),v=(s-r)*(o-a),b=(c-l)*(h-a);i=g/(v+b-g)}this.regionsOfInterest[0]=i>lH?e:n}}shouldUpdateRegionsOfInterest(){const n=this.regionsOfInterest.length;return n!==this.maxHandsNumber||this.runsWithoutHandDetector>=this.maxContinuousChecks}}hI.HandPipeline=mH});var mI=ge(Tp=>{const ha=Ct(),gH=iI(),Np=aI(),vH=pI();async function yH(n){return ha.loadGraphModel(n,{fromTFHub:n.includes("tfhub.dev")})}async function bH(n){return ha.loadGraphModel(n,{fromTFHub:n.includes("tfhub.dev")})}async function wH(n){return ha.util.fetch(n).then(t=>t.json())}async function SH(n){const[t,e,i]=await Promise.all([wH(n.detector.anchors),yH(n.detector.modelPath),bH(n.skeleton.modelPath)]),r=new gH.HandDetector(e,n.inputSize,n.inputSize,t,n.iouThreshold,n.scoreThreshold),a=new vH.HandPipeline(r,i,n.inputSize,n.inputSize,n.skipFrames,n.minConfidence),s=new fI(a);return s}Tp.load=SH;class fI{constructor(n){this.pipeline=n}static getAnnotations(){return Np.MESH_ANNOTATIONS}async estimateHands(n,t){const e=ha.tidy(()=>(n instanceof ha.Tensor||(n=ha.browser.fromPixels(n)),n.toFloat().expandDims(0))),i=await this.pipeline.estimateHand(e,t);if(e.dispose(),!i)return[];const r={};for(const a of Object.keys(Np.MESH_ANNOTATIONS))r[a]=Np.MESH_ANNOTATIONS[a].map(s=>i.landmarks[s]);return[{confidence:i.confidence||0,box:i.box?[i.box.topLeft[0],i.box.topLeft[1],i.box.bottomRight[0]-i.box.topLeft[0],i.box.bottomRight[1]-i.box.topLeft[1]]:0,landmarks:i.landmarks,annotations:r}]}}Tp.HandPose=fI});var gI=ge(LH=>{Cp(LH,{default:()=>IH});var IH={face:{enabled:!0,detector:{modelPath:"/models/blazeface/model.json",inputSize:128,maxFaces:10,skipFrames:5,minConfidence:.8,iouThreshold:.3,scoreThreshold:.75},mesh:{enabled:!0,modelPath:"/models/facemesh/model.json",inputSize:192},iris:{enabled:!0,modelPath:"/models/iris/model.json",inputSize:192},age:{enabled:!0,modelPath:"/models/ssrnet-age/imdb/model.json",inputSize:64,skipFrames:5},gender:{enabled:!0,modelPath:"/models/ssrnet-gender/imdb/model.json"}},body:{enabled:!0,modelPath:"/models/posenet/model.json",inputResolution:257,outputStride:16,maxDetections:5,scoreThreshold:.75,nmsRadius:20},hand:{enabled:!0,inputSize:256,skipFrames:5,minConfidence:.8,iouThreshold:.3,scoreThreshold:.75,detector:{anchors:"/models/handdetect/anchors.json",modelPath:"/models/handdetect/model.json"},skeleton:{modelPath:"/models/handskeleton/model.json"}}}});var II=ge(Qn=>{const AH=Ct(),vI=SL(),yI=AL(),bI=tI(),wI=mI(),SI=gI().default,Pn={facemesh:null,blazeface:null,ssrnet:null,iris:null};function LI(...n){const t=e=>e&&typeof e=="object";return n.reduce((e,i)=>(Object.keys(i||{}).forEach(r=>{const a=e[r],s=i[r];Array.isArray(a)&&Array.isArray(s)?e[r]=a.concat(...s):t(a)&&t(s)?e[r]=LI(a,s):e[r]=s}),e),{})}async function TH(n,t){const e=LI(SI,t);let i=[];e.body.enabled&&(Pn.posenet||(Pn.posenet=await bI.load(e.body)),i=await Pn.posenet.estimateMultiplePoses(n,e.body));let r=[];e.hand.enabled&&(Pn.handpose||(Pn.handpose=await wI.load(e.hand)),r=await Pn.handpose.estimateHands(n,e.hand));const a=[];if(e.face.enabled){Pn.facemesh||(Pn.facemesh=await vI.load(e.face));const s=await Pn.facemesh.estimateFaces(n,e.face);for(const o of s){const l=e.face.age.enabled||e.face.gender.enabled?await yI.predict(o.image,e):{},u=o.annotations.leftEyeIris&&o.annotations.rightEyeIris?Math.max(o.annotations.leftEyeIris[3][0]-o.annotations.leftEyeIris[1][0],o.annotations.rightEyeIris[3][0]-o.annotations.rightEyeIris[1][0]):0;a.push({confidence:o.confidence,box:o.box,mesh:o.mesh,annotations:o.annotations,age:l.age,gender:l.gender,iris:u!==0?Math.trunc(100*11.7/u)/100:0})}}return{face:a,body:i,hand:r}}Qn.detect=TH;Qn.defaults=SI;Qn.models=Pn;Qn.facemesh=vI;Qn.ssrnet=yI;Qn.posenet=bI;Qn.handpose=wI;Qn.tf=AH});export default II(); +`,J6=jo(X6),Z6={kernelName:N.Sin,backendName:"webgl",kernelFunc:J6};var Q6="return x * x;",e8=jo(Q6),t8={kernelName:N.Square,backendName:"webgl",kernelFunc:e8};var JS="return (a - b) * (a - b);",n8=Gd(JS,JS),i8={kernelName:N.SquaredDifference,backendName:"webgl",kernelFunc:n8};var r8="return tan(x);",a8=jo(r8),s8={kernelName:N.Tan,backendName:"webgl",kernelFunc:a8};var o8={kernelName:N.Transpose,backendName:"webgl",kernelFunc:function(n){for(var t=n.inputs,e=n.attrs,i=n.backend,r=t.x,a=e.perm,s=i,o=r.shape.length,l=new Array(o),u=0;u{"use strict";Object.defineProperty(cr,"__esModule",{value:!0});var $d=Yi(),Xd=Kb(),Jd=lw(),eL=Ow(),d8=v0(),p8=QS();var f8="2.6.0";var m8={"tfjs-core":$d.version_core,"tfjs-backend-cpu":d8.version_cpu,"tfjs-backend-webgl":p8.version_webgl,"tfjs-data":eL.version_data,"tfjs-layers":Xd.version_layers,"tfjs-converter":Jd.version_converter,tfjs:f8};Object.keys($d).forEach(function(n){n!=="default"&&Object.defineProperty(cr,n,{enumerable:!0,get:function(){return $d[n]}})});Object.keys(Xd).forEach(function(n){n!=="default"&&Object.defineProperty(cr,n,{enumerable:!0,get:function(){return Xd[n]}})});Object.keys(Jd).forEach(function(n){n!=="default"&&Object.defineProperty(cr,n,{enumerable:!0,get:function(){return Jd[n]}})});cr.data=eL;cr.version=m8});var tL=ge(os=>{const ls=Ct();os.disposeBox=n=>{n.startEndTensor.dispose(),n.startPoint.dispose(),n.endPoint.dispose()};os.createBox=n=>({startEndTensor:n,startPoint:ls.slice(n,[0,0],[-1,2]),endPoint:ls.slice(n,[0,2],[-1,2])});os.scaleBox=(n,t)=>{const e=ls.mul(n.startPoint,t),i=ls.mul(n.endPoint,t),r=ls.concat2d([e,i],1);return os.createBox(r)}});var Zd=ge(nL=>{const Ve=Ct(),$o=tL(),g8={strides:[8,16],anchors:[2,6]},iL=6;function v8(n,t,e){const i=[];for(let r=0;r{const e=n.box?n.box:n;return $o.scaleBox(e,t).startEndTensor.squeeze()})}class b8{constructor(n,t){this.blazeFaceModel=n,this.width=t.detector.inputSize,this.height=t.detector.inputSize,this.maxFaces=t.detector.maxFaces,this.anchorsData=v8(t.detector.inputSize,t.detector.inputSize,g8),this.anchors=Ve.tensor2d(this.anchorsData),this.inputSizeData=[t.detector.inputSize,t.detector.inputSize],this.inputSize=Ve.tensor1d([t.detector.inputSize,t.detector.inputSize]),this.iouThreshold=t.detector.iouThreshold,this.scoreThreshold=t.detector.scoreThreshold}async getBoundingBoxes(n,t,e=!0){const[i,r,a]=Ve.tidy(()=>{const p=n.resizeBilinear([this.width,this.height]),f=Ve.mul(Ve.sub(p.div(255),.5),2),m=this.blazeFaceModel.predict(f),g=m.squeeze(),v=y8(g,this.anchors,this.inputSize),b=Ve.slice(g,[0,0],[-1,1]),w=Ve.sigmoid(b).squeeze();return[g,v,w]}),s=await Ve.image.nonMaxSuppressionAsync(r,a,this.maxFaces,this.iouThreshold,this.scoreThreshold),o=await s.array();s.dispose();let l=o.map(p=>Ve.slice(r,[p,0],[1,-1]));t||(l=await Promise.all(l.map(async p=>{const f=await p.array();return p.dispose(),f})));const u=n.shape[1],c=n.shape[2];let h;t?h=Ve.div([c,u],this.inputSize):h=[c/this.inputSizeData[0],u/this.inputSizeData[1]];const d=[];for(let p=0;p{const g=f instanceof Ve.Tensor?$o.createBox(f):$o.createBox(Ve.tensor2d(f));if(!e)return g;const v=o[p];let b;t?b=this.anchors.slice([v,0],[1,2]):b=this.anchorsData[v];const w=Ve.slice(i,[v,iL-1],[1,-1]).squeeze().reshape([iL,-1]),S=Ve.slice(a,[v],[1]);return{box:g,landmarks:w,probability:S,anchor:b}});d.push(m)}return r.dispose(),a.dispose(),i.dispose(),{boxes:d,scaleFactor:h}}async estimateFaces(n,t=!1,e=!0){const i=Ve.tidy(()=>(n instanceof Ve.Tensor||(n=Ve.browser.fromPixels(n)),n.toFloat().expandDims(0))),{boxes:r,scaleFactor:a}=await this.getBoundingBoxes(i,t,e);return i.dispose(),t?r.map(s=>{const o=rL(s,a),l={topLeft:o.slice([0],[2]),bottomRight:o.slice([2],[2])};if(e){const{landmarks:u,probability:c,anchor:h}=s,d=u.add(h).mul(a);l.landmarks=d,l.probability=c}return l}):Promise.all(r.map(async s=>{const o=rL(s,a);let l;if(e){const[u,c,h]=await Promise.all([s.landmarks,o,s.probability].map(async g=>g.array())),d=s.anchor,[p,f]=a,m=u.map(g=>[(g[0]+d[0])*p,(g[1]+d[1])*f]);l={topLeft:c.slice(0,2),bottomRight:c.slice(2),landmarks:m,probability:h},$o.disposeBox(s.box),s.landmarks.dispose(),s.probability.dispose()}else{const u=await o.array();l={topLeft:u.slice(0,2),bottomRight:u.slice(2)}}return o.dispose(),l}))}}nL.BlazeFaceModel=b8});var aL=ge(Qd=>{const w8=Ct(),S8=Zd();async function L8(n){const t=await w8.loadGraphModel(n.detector.modelPath,{fromTFHub:n.detector.modelPath.includes("tfhub.dev")}),e=new S8.BlazeFaceModel(t,n);return e}Qd.load=L8;const I8=Zd();Object.defineProperty(Qd,"BlazeFaceModel",{enumerable:!0,get(){return I8.BlazeFaceModel}})});var ep=ge(sL=>{sL.MESH_ANNOTATIONS={silhouette:[10,338,297,332,284,251,389,356,454,323,361,288,397,365,379,378,400,377,152,148,176,149,150,136,172,58,132,93,234,127,162,21,54,103,67,109],lipsUpperOuter:[61,185,40,39,37,0,267,269,270,409,291],lipsLowerOuter:[146,91,181,84,17,314,405,321,375,291],lipsUpperInner:[78,191,80,81,82,13,312,311,310,415,308],lipsLowerInner:[78,95,88,178,87,14,317,402,318,324,308],rightEyeUpper0:[246,161,160,159,158,157,173],rightEyeLower0:[33,7,163,144,145,153,154,155,133],rightEyeUpper1:[247,30,29,27,28,56,190],rightEyeLower1:[130,25,110,24,23,22,26,112,243],rightEyeUpper2:[113,225,224,223,222,221,189],rightEyeLower2:[226,31,228,229,230,231,232,233,244],rightEyeLower3:[143,111,117,118,119,120,121,128,245],rightEyebrowUpper:[156,70,63,105,66,107,55,193],rightEyebrowLower:[35,124,46,53,52,65],rightEyeIris:[473,474,475,476,477],leftEyeUpper0:[466,388,387,386,385,384,398],leftEyeLower0:[263,249,390,373,374,380,381,382,362],leftEyeUpper1:[467,260,259,257,258,286,414],leftEyeLower1:[359,255,339,254,253,252,256,341,463],leftEyeUpper2:[342,445,444,443,442,441,413],leftEyeLower2:[446,261,448,449,450,451,452,453,464],leftEyeLower3:[372,340,346,347,348,349,350,357,465],leftEyebrowUpper:[383,300,293,334,296,336,285,417],leftEyebrowLower:[265,353,276,283,282,295],leftEyeIris:[468,469,470,471,472],midwayBetweenEyes:[168],noseTip:[1],noseBottom:[2],noseRightCorner:[98],noseLeftCorner:[327],rightCheek:[205],leftCheek:[425]}});var oL=ge(hr=>{const A8=Ct();function T8(n,t){const e=[n.startPoint[0]*t[0],n.startPoint[1]*t[1]],i=[n.endPoint[0]*t[0],n.endPoint[1]*t[1]];return{startPoint:e,endPoint:i}}hr.scaleBoxCoordinates=T8;function tp(n){return[Math.abs(n.endPoint[0]-n.startPoint[0]),Math.abs(n.endPoint[1]-n.startPoint[1])]}hr.getBoxSize=tp;function np(n){return[n.startPoint[0]+(n.endPoint[0]-n.startPoint[0])/2,n.startPoint[1]+(n.endPoint[1]-n.startPoint[1])/2]}hr.getBoxCenter=np;function N8(n,t,e){const i=t.shape[1],r=t.shape[2],a=[[n.startPoint[1]/i,n.startPoint[0]/r,n.endPoint[1]/i,n.endPoint[0]/r]];return A8.image.cropAndResize(t,a,[0],e)}hr.cutBoxFromImageAndResize=N8;function x8(n,t=1.5){const e=np(n),i=tp(n),r=[t*i[0]/2,t*i[1]/2],a=[e[0]-r[0],e[1]-r[1]],s=[e[0]+r[0],e[1]+r[1]];return{startPoint:a,endPoint:s,landmarks:n.landmarks}}hr.enlargeBox=x8;function C8(n){const t=np(n),e=tp(n),i=Math.max(...e),r=i/2,a=[t[0]-r,t[1]-r],s=[t[0]+r,t[1]+r];return{startPoint:a,endPoint:s,landmarks:n.landmarks}}hr.squarifyBox=C8});var dL=ge(wn=>{wn.IDENTITY_MATRIX=[[1,0,0],[0,1,0],[0,0,1]];function lL(n){return n-2*Math.PI*Math.floor((n+Math.PI)/(2*Math.PI))}wn.normalizeRadians=lL;function R8(n,t){const e=Math.PI/2-Math.atan2(-(t[1]-n[1]),t[0]-n[0]);return lL(e)}wn.computeRotation=R8;function O8(n){return n*180/Math.PI}wn.radToDegrees=O8;function uL(n,t){return[[1,0,n],[0,1,t],[0,0,1]]}function ra(n,t){let e=0;for(let i=0;i{const Ai=Ct(),Bn=oL(),aa=ep(),Ti=dL(),W8=468,U8=.25,B8=13,z8=[B8,aa.MESH_ANNOTATIONS.midwayBetweenEyes[0]],P8=3,_8=2,M8=[P8,_8],ip=aa.MESH_ANNOTATIONS.leftEyeLower0,rp=[ip[0],ip[ip.length-1]],ap=aa.MESH_ANNOTATIONS.rightEyeLower0,sp=[ap[0],ap[ap.length-1]],H8=3,V8=4,q8=71,op=76,G8=2.3,us=64,fL=[{key:"EyeUpper0",indices:[9,10,11,12,13,14,15]},{key:"EyeUpper1",indices:[25,26,27,28,29,30,31]},{key:"EyeUpper2",indices:[41,42,43,44,45,46,47]},{key:"EyeLower0",indices:[0,1,2,3,4,5,6,7,8]},{key:"EyeLower1",indices:[16,17,18,19,20,21,22,23,24]},{key:"EyeLower2",indices:[32,33,34,35,36,37,38,39,40]},{key:"EyeLower3",indices:[54,55,56,57,58,59,60,61,62]},{key:"EyebrowUpper",indices:[63,64,65,66,67,68,69,70]},{key:"EyebrowLower",indices:[48,49,50,51,52,53]}];function Xo(n,t,e,i){for(let r=0;r[a[0]*(d[0]-this.meshWidth/2),a[1]*(d[1]-this.meshHeight/2),d[2]]),o=Ti.buildRotationMatrix(e,[0,0]),l=s.map(d=>[...Ti.rotatePoint(d,o),d[2]]),u=Ti.invertTransformMatrix(i),c=[...Bn.getBoxCenter({startPoint:t.startPoint,endPoint:t.endPoint}),1],h=[Ti.dot(c,u[0]),Ti.dot(c,u[1])];return l.map(d=>[d[0]+h[0],d[1]+h[1],d[2]])}getLeftToRightEyeDepthDifference(n){const t=n[rp[0]][2],e=n[sp[0]][2];return t-e}getEyeBox(n,t,e,i,r=!1){const a=Bn.squarifyBox(Bn.enlargeBox(this.calculateLandmarksBoundingBox([n[e],n[i]]),G8)),s=Bn.getBoxSize(a);let o=Ai.image.cropAndResize(t,[[a.startPoint[1]/this.meshHeight,a.startPoint[0]/this.meshWidth,a.endPoint[1]/this.meshHeight,a.endPoint[0]/this.meshWidth]],[0],[us,us]);return r&&(o=Ai.image.flipLeftRight(o)),{box:a,boxSize:s,crop:o}}getEyeCoords(n,t,e,i=!1){const r=[];for(let a=0;a{let l=a;return o===2?l=i:o===4&&(l=r),[s[0],s[1],l]})}async predict(n,t,e){if(this.shouldUpdateRegionsOfInterest()){const i=!1,r=!0,{boxes:a,scaleFactor:s}=await this.boundingBoxDetector.getBoundingBoxes(n,i,r);if(a.length===0)return this.regionsOfInterest=[],null;const o=a.map(l=>{const u={startPoint:l.box.startPoint.squeeze().arraySync(),endPoint:l.box.endPoint.squeeze().arraySync()},c=Bn.scaleBoxCoordinates(u,s),h=Bn.enlargeBox(c);return{...h,landmarks:l.landmarks.arraySync()}});a.forEach(l=>{l!=null&&l.startPoint!=null&&(l.startEndTensor.dispose(),l.startPoint.dispose(),l.endPoint.dispose())}),this.updateRegionsOfInterest(o),this.runsWithoutFaceDetector=0}else this.runsWithoutFaceDetector++;return Ai.tidy(()=>this.regionsOfInterest.map((i,r)=>{let a=0;const s=i.landmarks.length>=W8;let[o,l]=z8;s===!1&&([o,l]=M8),a=Ti.computeRotation(i.landmarks[o],i.landmarks[l]);const u=Bn.getBoxCenter({startPoint:i.startPoint,endPoint:i.endPoint}),c=[u[0]/n.shape[2],u[1]/n.shape[1]];let h=n,d=Ti.IDENTITY_MATRIX;a!==0&&(h=Ai.image.rotateWithOffset(n,a,0,c),d=Ti.buildRotationMatrix(-a,u));const p={startPoint:i.startPoint,endPoint:i.endPoint},f=Bn.cutBoxFromImageAndResize(p,h,[this.meshHeight,this.meshWidth]).div(255),[,m,g]=this.meshDetector.predict(f),v=Ai.reshape(g,[-1,3]);let b=v.arraySync();if(t){const{box:x,boxSize:C,crop:R}=this.getEyeBox(b,f,rp[0],rp[1],!0),{box:D,boxSize:k,crop:W}=this.getEyeBox(b,f,sp[0],sp[1]),F=this.irisModel.predict(Ai.concat([R,W])),P=F.dataSync(),H=P.slice(0,op*3),{rawCoords:_,iris:K}=this.getEyeCoords(H,x,C,!0),j=P.slice(op*3),{rawCoords:q,iris:G}=this.getEyeCoords(j,D,k),Z=this.getLeftToRightEyeDepthDifference(b);Math.abs(Z)<30?(Xo(b,_,"left"),Xo(b,q,"right")):Z<1?Xo(b,_,"left",["EyeUpper0","EyeLower0"]):Xo(b,q,"right",["EyeUpper0","EyeLower0"]);const X=this.getAdjustedIrisCoords(b,K,"left"),ee=this.getAdjustedIrisCoords(b,G,"right");b=b.concat(X).concat(ee)}const w=this.transformRawCoords(b,i,a,d);Ai.dispose(b);const S=Bn.enlargeBox(this.calculateLandmarksBoundingBox(w));if(e){const x=Ai.tensor2d(w);this.regionsOfInterest[r]={...S,landmarks:x.arraySync()};const C={coords:x,box:S,confidence:m.squeeze(),image:f};return C}const L={coords:null,box:S,confidence:m.squeeze(),image:f};return L}))}updateRegionsOfInterest(n){for(let t=0;t=this.skipFrames}calculateLandmarksBoundingBox(n){const t=n.map(a=>a[0]),e=n.map(a=>a[1]),i=[Math.min(...t),Math.min(...e)],r=[Math.max(...t),Math.max(...e)];return{startPoint:i,endPoint:r}}}pL.Pipeline=Y8});var vL=ge(gL=>{gL.UV_COORDS=[[.499976992607117,.652534008026123],[.500025987625122,.547487020492554],[.499974012374878,.602371990680695],[.482113003730774,.471979022026062],[.500150978565216,.527155995368958],[.499909996986389,.498252987861633],[.499523013830185,.40106201171875],[.289712011814117,.380764007568359],[.499954998493195,.312398016452789],[.499987006187439,.269918978214264],[.500023007392883,.107050001621246],[.500023007392883,.666234016418457],[.5000159740448,.679224014282227],[.500023007392883,.692348003387451],[.499976992607117,.695277988910675],[.499976992607117,.70593398809433],[.499976992607117,.719385027885437],[.499976992607117,.737019002437592],[.499967992305756,.781370997428894],[.499816000461578,.562981009483337],[.473773002624512,.573909997940063],[.104906998574734,.254140973091125],[.365929991006851,.409575998783112],[.338757991790771,.41302502155304],[.311120003461838,.409460008144379],[.274657994508743,.389131009578705],[.393361985683441,.403706014156342],[.345234006643295,.344011008739471],[.370094001293182,.346076011657715],[.319321990013123,.347265005111694],[.297903001308441,.353591024875641],[.24779200553894,.410809993743896],[.396889001131058,.842755019664764],[.280097991228104,.375599980354309],[.106310002505779,.399955987930298],[.2099249958992,.391353011131287],[.355807989835739,.534406006336212],[.471751004457474,.65040397644043],[.474155008792877,.680191993713379],[.439785003662109,.657229006290436],[.414617002010345,.66654098033905],[.450374007225037,.680860996246338],[.428770989179611,.682690978050232],[.374971002340317,.727805018424988],[.486716985702515,.547628998756409],[.485300987958908,.527395009994507],[.257764995098114,.314490020275116],[.401223003864288,.455172002315521],[.429818987846375,.548614978790283],[.421351999044418,.533740997314453],[.276895999908447,.532056987285614],[.483370006084442,.499586999416351],[.33721199631691,.282882988452911],[.296391993761063,.293242990970612],[.169294998049736,.193813979625702],[.447580009698868,.302609980106354],[.392390012741089,.353887975215912],[.354490011930466,.696784019470215],[.067304998636246,.730105042457581],[.442739009857178,.572826027870178],[.457098007202148,.584792017936707],[.381974011659622,.694710969924927],[.392388999462128,.694203019142151],[.277076005935669,.271932005882263],[.422551989555359,.563233017921448],[.385919004678726,.281364023685455],[.383103013038635,.255840003490448],[.331431001424789,.119714021682739],[.229923993349075,.232002973556519],[.364500999450684,.189113974571228],[.229622006416321,.299540996551514],[.173287004232407,.278747975826263],[.472878992557526,.666198015213013],[.446828007698059,.668527007102966],[.422762006521225,.673889994621277],[.445307999849319,.580065965652466],[.388103008270264,.693961024284363],[.403039008378983,.706539988517761],[.403629004955292,.693953037261963],[.460041999816895,.557139039039612],[.431158006191254,.692366003990173],[.452181994915009,.692366003990173],[.475387006998062,.692366003990173],[.465828001499176,.779190003871918],[.472328990697861,.736225962638855],[.473087012767792,.717857003211975],[.473122000694275,.704625964164734],[.473033010959625,.695277988910675],[.427942007780075,.695277988910675],[.426479011774063,.703539967536926],[.423162013292313,.711845993995667],[.4183090031147,.720062971115112],[.390094995498657,.639572978019714],[.013953999616206,.560034036636353],[.499913990497589,.58014702796936],[.413199990987778,.69539999961853],[.409626007080078,.701822996139526],[.468080013990402,.601534962654114],[.422728985548019,.585985004901886],[.463079988956451,.593783974647522],[.37211999297142,.47341400384903],[.334562003612518,.496073007583618],[.411671012639999,.546965003013611],[.242175996303558,.14767599105835],[.290776997804642,.201445996761322],[.327338010072708,.256527006626129],[.399509996175766,.748921036720276],[.441727995872498,.261676013469696],[.429764986038208,.187834024429321],[.412198007106781,.108901023864746],[.288955003023148,.398952007293701],[.218936994671822,.435410976409912],[.41278201341629,.398970007896423],[.257135003805161,.355440020561218],[.427684992551804,.437960982322693],[.448339998722076,.536936044692993],[.178560003638268,.45755398273468],[.247308000922203,.457193970680237],[.286267012357712,.467674970626831],[.332827985286713,.460712015628815],[.368755996227264,.447206974029541],[.398963987827301,.432654976844788],[.476410001516342,.405806005001068],[.189241006970406,.523923993110657],[.228962004184723,.348950982093811],[.490725994110107,.562400996685028],[.404670000076294,.485132992267609],[.019469000399113,.401564002037048],[.426243007183075,.420431017875671],[.396993011236191,.548797011375427],[.266469985246658,.376977026462555],[.439121007919312,.51895797252655],[.032313998788595,.644356966018677],[.419054001569748,.387154996395111],[.462783008813858,.505746960639954],[.238978996872902,.779744982719421],[.198220998048782,.831938028335571],[.107550002634525,.540755033493042],[.183610007166862,.740257024765015],[.134409993886948,.333683013916016],[.385764002799988,.883153975009918],[.490967005491257,.579378008842468],[.382384985685349,.508572995662689],[.174399003386497,.397670984268188],[.318785011768341,.39623498916626],[.343364000320435,.400596976280212],[.396100014448166,.710216999053955],[.187885001301765,.588537991046906],[.430987000465393,.944064974784851],[.318993002176285,.898285031318665],[.266247987747192,.869701027870178],[.500023007392883,.190576016902924],[.499976992607117,.954452991485596],[.366169989109039,.398822009563446],[.393207013607025,.39553701877594],[.410373002290726,.391080021858215],[.194993004202843,.342101991176605],[.388664990663528,.362284004688263],[.365961998701096,.355970978736877],[.343364000320435,.355356991291046],[.318785011768341,.35834002494812],[.301414996385574,.363156020641327],[.058132998645306,.319076001644135],[.301414996385574,.387449026107788],[.499987989664078,.618434011936188],[.415838003158569,.624195992946625],[.445681989192963,.566076993942261],[.465844005346298,.620640993118286],[.49992299079895,.351523995399475],[.288718998432159,.819945991039276],[.335278987884521,.852819979190826],[.440512001514435,.902418971061707],[.128294005990028,.791940987110138],[.408771991729736,.373893976211548],[.455606997013092,.451801002025604],[.499877005815506,.908990025520325],[.375436991453171,.924192011356354],[.11421000212431,.615022003650665],[.448662012815475,.695277988910675],[.4480200111866,.704632043838501],[.447111994028091,.715808033943176],[.444831997156143,.730794012546539],[.430011987686157,.766808986663818],[.406787008047104,.685672998428345],[.400738000869751,.681069016456604],[.392399996519089,.677703022956848],[.367855995893478,.663918972015381],[.247923001646996,.601333022117615],[.452769994735718,.420849978923798],[.43639200925827,.359887003898621],[.416164010763168,.368713974952698],[.413385987281799,.692366003990173],[.228018000721931,.683571994304657],[.468268007040024,.352671027183533],[.411361992359161,.804327011108398],[.499989002943039,.469825029373169],[.479153990745544,.442654013633728],[.499974012374878,.439637005329132],[.432112008333206,.493588984012604],[.499886006116867,.866917014122009],[.49991300702095,.821729004383087],[.456548988819122,.819200992584229],[.344549000263214,.745438992977142],[.37890899181366,.574010014533997],[.374292999505997,.780184984207153],[.319687992334366,.570737957954407],[.357154995203018,.604269981384277],[.295284003019333,.621580958366394],[.447750002145767,.862477004528046],[.410986006259918,.508723020553589],[.31395098567009,.775308012962341],[.354128003120422,.812552988529205],[.324548006057739,.703992962837219],[.189096003770828,.646299958229065],[.279776990413666,.71465802192688],[.1338230073452,.682700991630554],[.336768001317978,.644733011722565],[.429883986711502,.466521978378296],[.455527991056442,.548622965812683],[.437114000320435,.558896005153656],[.467287987470627,.529924988746643],[.414712011814117,.335219979286194],[.37704598903656,.322777986526489],[.344107985496521,.320150971412659],[.312875986099243,.32233202457428],[.283526003360748,.333190023899078],[.241245999932289,.382785975933075],[.102986000478268,.468762993812561],[.267612010240555,.424560010433197],[.297879010438919,.433175981044769],[.333433985710144,.433878004550934],[.366427004337311,.426115989685059],[.396012008190155,.416696012020111],[.420121014118195,.41022801399231],[.007561000064015,.480777025222778],[.432949006557465,.569517970085144],[.458638995885849,.479089021682739],[.473466008901596,.545744001865387],[.476087987422943,.563830018043518],[.468472003936768,.555056989192963],[.433990985155106,.582361996173859],[.483518004417419,.562983989715576],[.482482999563217,.57784903049469],[.42645001411438,.389798998832703],[.438998997211456,.39649498462677],[.450067013502121,.400434017181396],[.289712011814117,.368252992630005],[.276670008897781,.363372981548309],[.517862021923065,.471948027610779],[.710287988185883,.380764007568359],[.526226997375488,.573909997940063],[.895093023777008,.254140973091125],[.634069979190826,.409575998783112],[.661242008209229,.41302502155304],[.688880026340485,.409460008144379],[.725341975688934,.389131009578705],[.606630027294159,.40370500087738],[.654766023159027,.344011008739471],[.629905998706818,.346076011657715],[.680678009986877,.347265005111694],[.702096998691559,.353591024875641],[.75221198797226,.410804986953735],[.602918028831482,.842862963676453],[.719901978969574,.375599980354309],[.893692970275879,.399959981441498],[.790081977844238,.391354024410248],[.643998026847839,.534487962722778],[.528249025344849,.65040397644043],[.525849997997284,.680191040039062],[.560214996337891,.657229006290436],[.585384011268616,.66654098033905],[.549625992774963,.680860996246338],[.57122802734375,.682691991329193],[.624852001667023,.72809898853302],[.513050019741058,.547281980514526],[.51509702205658,.527251958847046],[.742246985435486,.314507007598877],[.598631024360657,.454979002475739],[.570338010787964,.548575043678284],[.578631997108459,.533622980117798],[.723087012767792,.532054007053375],[.516445994377136,.499638974666595],[.662801027297974,.282917976379395],[.70362401008606,.293271005153656],[.830704987049103,.193813979625702],[.552385985851288,.302568018436432],[.607609987258911,.353887975215912],[.645429015159607,.696707010269165],[.932694971561432,.730105042457581],[.557260990142822,.572826027870178],[.542901992797852,.584792017936707],[.6180260181427,.694710969924927],[.607590973377228,.694203019142151],[.722943007946014,.271963000297546],[.577413976192474,.563166975975037],[.614082992076874,.281386971473694],[.616907000541687,.255886018276215],[.668509006500244,.119913995265961],[.770092010498047,.232020974159241],[.635536015033722,.189248979091644],[.77039098739624,.299556016921997],[.826722025871277,.278755009174347],[.527121007442474,.666198015213013],[.553171992301941,.668527007102966],[.577238023281097,.673889994621277],[.554691970348358,.580065965652466],[.611896991729736,.693961024284363],[.59696102142334,.706539988517761],[.596370995044708,.693953037261963],[.539958000183105,.557139039039612],[.568841993808746,.692366003990173],[.547818005084991,.692366003990173],[.52461302280426,.692366003990173],[.534089982509613,.779141008853912],[.527670979499817,.736225962638855],[.526912987232208,.717857003211975],[.526877999305725,.704625964164734],[.526966989040375,.695277988910675],[.572058022022247,.695277988910675],[.573521018028259,.703539967536926],[.57683801651001,.711845993995667],[.581691026687622,.720062971115112],[.609944999217987,.639909982681274],[.986046016216278,.560034036636353],[.5867999792099,.69539999961853],[.590372025966644,.701822996139526],[.531915009021759,.601536989212036],[.577268004417419,.585934996604919],[.536915004253387,.593786001205444],[.627542972564697,.473352015018463],[.665585994720459,.495950996875763],[.588353991508484,.546862006187439],[.757824003696442,.14767599105835],[.709249973297119,.201507985591888],[.672684013843536,.256581008434296],[.600408971309662,.74900496006012],[.55826598405838,.261672019958496],[.570303976535797,.187870979309082],[.588165998458862,.109044015407562],[.711045026779175,.398952007293701],[.781069993972778,.435405015945435],[.587247014045715,.398931980133057],[.742869973182678,.355445981025696],[.572156012058258,.437651991844177],[.55186802148819,.536570012569427],[.821442008018494,.457556009292603],[.752701997756958,.457181990146637],[.71375697851181,.467626988887787],[.66711300611496,.460672974586487],[.631101012229919,.447153985500336],[.6008620262146,.432473003864288],[.523481011390686,.405627012252808],[.810747981071472,.523926019668579],[.771045982837677,.348959028720856],[.509127020835876,.562718033790588],[.595292985439301,.485023975372314],[.980530977249146,.401564002037048],[.573499977588654,.420000016689301],[.602994978427887,.548687994480133],[.733529984951019,.376977026462555],[.560611009597778,.519016981124878],[.967685997486115,.644356966018677],[.580985009670258,.387160003185272],[.537728011608124,.505385041236877],[.760966002941132,.779752969741821],[.801778972148895,.831938028335571],[.892440974712372,.54076099395752],[.816350996494293,.740260004997253],[.865594983100891,.333687007427216],[.614073991775513,.883246004581451],[.508952975273132,.579437971115112],[.617941975593567,.508316040039062],[.825608015060425,.397674977779388],[.681214988231659,.39623498916626],[.656635999679565,.400596976280212],[.603900015354156,.710216999053955],[.81208598613739,.588539004325867],[.56801301240921,.944564998149872],[.681007981300354,.898285031318665],[.733752012252808,.869701027870178],[.633830010890961,.398822009563446],[.606792986392975,.39553701877594],[.589659988880157,.391062021255493],[.805015981197357,.342108011245728],[.611334979534149,.362284004688263],[.634037971496582,.355970978736877],[.656635999679565,.355356991291046],[.681214988231659,.35834002494812],[.698584973812103,.363156020641327],[.941866993904114,.319076001644135],[.698584973812103,.387449026107788],[.584177017211914,.624107003211975],[.554318010807037,.566076993942261],[.534153997898102,.62064003944397],[.711217999458313,.819975018501282],[.664629995822906,.852871000766754],[.559099972248077,.902631998062134],[.871706008911133,.791940987110138],[.591234028339386,.373893976211548],[.544341027736664,.451583981513977],[.624562978744507,.924192011356354],[.88577002286911,.615028977394104],[.551338016986847,.695277988910675],[.551980018615723,.704632043838501],[.552887976169586,.715808033943176],[.555167973041534,.730794012546539],[.569944024085999,.767035007476807],[.593203008174896,.685675978660583],[.599261999130249,.681069016456604],[.607599973678589,.677703022956848],[.631937980651855,.663500010967255],[.752032995223999,.601315021514893],[.547226011753082,.420395016670227],[.563543975353241,.359827995300293],[.583841025829315,.368713974952698],[.586614012718201,.692366003990173],[.771915018558502,.683578014373779],[.531597018241882,.352482974529266],[.588370978832245,.804440975189209],[.52079701423645,.442565023899078],[.567984998226166,.493479013442993],[.543282985687256,.819254994392395],[.655317008495331,.745514988899231],[.621008992195129,.574018001556396],[.625559985637665,.78031200170517],[.680198013782501,.570719003677368],[.64276397228241,.604337990283966],[.704662978649139,.621529996395111],[.552012026309967,.862591981887817],[.589071989059448,.508637011051178],[.685944974422455,.775357007980347],[.645735025405884,.812640011310577],[.675342977046967,.703978002071381],[.810858011245728,.646304965019226],[.72012197971344,.714666962623596],[.866151988506317,.682704985141754],[.663187026977539,.644596993923187],[.570082008838654,.466325998306274],[.544561982154846,.548375964164734],[.562758982181549,.558784961700439],[.531987011432648,.530140042304993],[.585271000862122,.335177004337311],[.622952997684479,.32277899980545],[.655896008014679,.320163011550903],[.687132000923157,.322345972061157],[.716481983661652,.333200991153717],[.758756995201111,.382786989212036],[.897013008594513,.468769013881683],[.732392013072968,.424547016620636],[.70211398601532,.433162987232208],[.66652500629425,.433866024017334],[.633504986763,.426087975502014],[.603875994682312,.416586995124817],[.579657971858978,.409945011138916],[.992439985275269,.480777025222778],[.567192018032074,.569419980049133],[.54136598110199,.478899002075195],[.526564002037048,.546118021011353],[.523913025856018,.563830018043518],[.531529009342194,.555056989192963],[.566035985946655,.582329034805298],[.51631098985672,.563053965568542],[.5174720287323,.577877044677734],[.573594987392426,.389806985855103],[.560697972774506,.395331978797913],[.549755990505219,.399751007556915],[.710287988185883,.368252992630005],[.723330020904541,.363372981548309]]});var yL=ge(K8=>{Cp(K8,{default:()=>j8});var j8=[127,34,139,11,0,37,232,231,120,72,37,39,128,121,47,232,121,128,104,69,67,175,171,148,157,154,155,118,50,101,73,39,40,9,151,108,48,115,131,194,204,211,74,40,185,80,42,183,40,92,186,230,229,118,202,212,214,83,18,17,76,61,146,160,29,30,56,157,173,106,204,194,135,214,192,203,165,98,21,71,68,51,45,4,144,24,23,77,146,91,205,50,187,201,200,18,91,106,182,90,91,181,85,84,17,206,203,36,148,171,140,92,40,39,193,189,244,159,158,28,247,246,161,236,3,196,54,68,104,193,168,8,117,228,31,189,193,55,98,97,99,126,47,100,166,79,218,155,154,26,209,49,131,135,136,150,47,126,217,223,52,53,45,51,134,211,170,140,67,69,108,43,106,91,230,119,120,226,130,247,63,53,52,238,20,242,46,70,156,78,62,96,46,53,63,143,34,227,173,155,133,123,117,111,44,125,19,236,134,51,216,206,205,154,153,22,39,37,167,200,201,208,36,142,100,57,212,202,20,60,99,28,158,157,35,226,113,160,159,27,204,202,210,113,225,46,43,202,204,62,76,77,137,123,116,41,38,72,203,129,142,64,98,240,49,102,64,41,73,74,212,216,207,42,74,184,169,170,211,170,149,176,105,66,69,122,6,168,123,147,187,96,77,90,65,55,107,89,90,180,101,100,120,63,105,104,93,137,227,15,86,85,129,102,49,14,87,86,55,8,9,100,47,121,145,23,22,88,89,179,6,122,196,88,95,96,138,172,136,215,58,172,115,48,219,42,80,81,195,3,51,43,146,61,171,175,199,81,82,38,53,46,225,144,163,110,246,33,7,52,65,66,229,228,117,34,127,234,107,108,69,109,108,151,48,64,235,62,78,191,129,209,126,111,35,143,163,161,246,117,123,50,222,65,52,19,125,141,221,55,65,3,195,197,25,7,33,220,237,44,70,71,139,122,193,245,247,130,33,71,21,162,153,158,159,170,169,150,188,174,196,216,186,92,144,160,161,2,97,167,141,125,241,164,167,37,72,38,12,145,159,160,38,82,13,63,68,71,226,35,111,158,153,154,101,50,205,206,92,165,209,198,217,165,167,97,220,115,218,133,112,243,239,238,241,214,135,169,190,173,133,171,208,32,125,44,237,86,87,178,85,86,179,84,85,180,83,84,181,201,83,182,137,93,132,76,62,183,61,76,184,57,61,185,212,57,186,214,207,187,34,143,156,79,239,237,123,137,177,44,1,4,201,194,32,64,102,129,213,215,138,59,166,219,242,99,97,2,94,141,75,59,235,24,110,228,25,130,226,23,24,229,22,23,230,26,22,231,112,26,232,189,190,243,221,56,190,28,56,221,27,28,222,29,27,223,30,29,224,247,30,225,238,79,20,166,59,75,60,75,240,147,177,215,20,79,166,187,147,213,112,233,244,233,128,245,128,114,188,114,217,174,131,115,220,217,198,236,198,131,134,177,132,58,143,35,124,110,163,7,228,110,25,356,389,368,11,302,267,452,350,349,302,303,269,357,343,277,452,453,357,333,332,297,175,152,377,384,398,382,347,348,330,303,304,270,9,336,337,278,279,360,418,262,431,304,408,409,310,415,407,270,409,410,450,348,347,422,430,434,313,314,17,306,307,375,387,388,260,286,414,398,335,406,418,364,367,416,423,358,327,251,284,298,281,5,4,373,374,253,307,320,321,425,427,411,421,313,18,321,405,406,320,404,405,315,16,17,426,425,266,377,400,369,322,391,269,417,465,464,386,257,258,466,260,388,456,399,419,284,332,333,417,285,8,346,340,261,413,441,285,327,460,328,355,371,329,392,439,438,382,341,256,429,420,360,364,394,379,277,343,437,443,444,283,275,440,363,431,262,369,297,338,337,273,375,321,450,451,349,446,342,467,293,334,282,458,461,462,276,353,383,308,324,325,276,300,293,372,345,447,382,398,362,352,345,340,274,1,19,456,248,281,436,427,425,381,256,252,269,391,393,200,199,428,266,330,329,287,273,422,250,462,328,258,286,384,265,353,342,387,259,257,424,431,430,342,353,276,273,335,424,292,325,307,366,447,345,271,303,302,423,266,371,294,455,460,279,278,294,271,272,304,432,434,427,272,407,408,394,430,431,395,369,400,334,333,299,351,417,168,352,280,411,325,319,320,295,296,336,319,403,404,330,348,349,293,298,333,323,454,447,15,16,315,358,429,279,14,15,316,285,336,9,329,349,350,374,380,252,318,402,403,6,197,419,318,319,325,367,364,365,435,367,397,344,438,439,272,271,311,195,5,281,273,287,291,396,428,199,311,271,268,283,444,445,373,254,339,263,466,249,282,334,296,449,347,346,264,447,454,336,296,299,338,10,151,278,439,455,292,407,415,358,371,355,340,345,372,390,249,466,346,347,280,442,443,282,19,94,370,441,442,295,248,419,197,263,255,359,440,275,274,300,383,368,351,412,465,263,467,466,301,368,389,380,374,386,395,378,379,412,351,419,436,426,322,373,390,388,2,164,393,370,462,461,164,0,267,302,11,12,374,373,387,268,12,13,293,300,301,446,261,340,385,384,381,330,266,425,426,423,391,429,355,437,391,327,326,440,457,438,341,382,362,459,457,461,434,430,394,414,463,362,396,369,262,354,461,457,316,403,402,315,404,403,314,405,404,313,406,405,421,418,406,366,401,361,306,408,407,291,409,408,287,410,409,432,436,410,434,416,411,264,368,383,309,438,457,352,376,401,274,275,4,421,428,262,294,327,358,433,416,367,289,455,439,462,370,326,2,326,370,305,460,455,254,449,448,255,261,446,253,450,449,252,451,450,256,452,451,341,453,452,413,464,463,441,413,414,258,442,441,257,443,442,259,444,443,260,445,444,467,342,445,459,458,250,289,392,290,290,328,460,376,433,435,250,290,392,411,416,433,341,463,464,453,464,465,357,465,412,343,412,399,360,363,440,437,399,456,420,456,363,401,435,288,372,383,353,339,255,249,448,261,255,133,243,190,133,155,112,33,246,247,33,130,25,398,384,286,362,398,414,362,463,341,263,359,467,263,249,255,466,467,260,75,60,166,238,239,79,162,127,139,72,11,37,121,232,120,73,72,39,114,128,47,233,232,128,103,104,67,152,175,148,173,157,155,119,118,101,74,73,40,107,9,108,49,48,131,32,194,211,184,74,185,191,80,183,185,40,186,119,230,118,210,202,214,84,83,17,77,76,146,161,160,30,190,56,173,182,106,194,138,135,192,129,203,98,54,21,68,5,51,4,145,144,23,90,77,91,207,205,187,83,201,18,181,91,182,180,90,181,16,85,17,205,206,36,176,148,140,165,92,39,245,193,244,27,159,28,30,247,161,174,236,196,103,54,104,55,193,8,111,117,31,221,189,55,240,98,99,142,126,100,219,166,218,112,155,26,198,209,131,169,135,150,114,47,217,224,223,53,220,45,134,32,211,140,109,67,108,146,43,91,231,230,120,113,226,247,105,63,52,241,238,242,124,46,156,95,78,96,70,46,63,116,143,227,116,123,111,1,44,19,3,236,51,207,216,205,26,154,22,165,39,167,199,200,208,101,36,100,43,57,202,242,20,99,56,28,157,124,35,113,29,160,27,211,204,210,124,113,46,106,43,204,96,62,77,227,137,116,73,41,72,36,203,142,235,64,240,48,49,64,42,41,74,214,212,207,183,42,184,210,169,211,140,170,176,104,105,69,193,122,168,50,123,187,89,96,90,66,65,107,179,89,180,119,101,120,68,63,104,234,93,227,16,15,85,209,129,49,15,14,86,107,55,9,120,100,121,153,145,22,178,88,179,197,6,196,89,88,96,135,138,136,138,215,172,218,115,219,41,42,81,5,195,51,57,43,61,208,171,199,41,81,38,224,53,225,24,144,110,105,52,66,118,229,117,227,34,234,66,107,69,10,109,151,219,48,235,183,62,191,142,129,126,116,111,143,7,163,246,118,117,50,223,222,52,94,19,141,222,221,65,196,3,197,45,220,44,156,70,139,188,122,245,139,71,162,145,153,159,149,170,150,122,188,196,206,216,92,163,144,161,164,2,167,242,141,241,0,164,37,11,72,12,144,145,160,12,38,13,70,63,71,31,226,111,157,158,154,36,101,205,203,206,165,126,209,217,98,165,97,237,220,218,237,239,241,210,214,169,140,171,32,241,125,237,179,86,178,180,85,179,181,84,180,182,83,181,194,201,182,177,137,132,184,76,183,185,61,184,186,57,185,216,212,186,192,214,187,139,34,156,218,79,237,147,123,177,45,44,4,208,201,32,98,64,129,192,213,138,235,59,219,141,242,97,97,2,141,240,75,235,229,24,228,31,25,226,230,23,229,231,22,230,232,26,231,233,112,232,244,189,243,189,221,190,222,28,221,223,27,222,224,29,223,225,30,224,113,247,225,99,60,240,213,147,215,60,20,166,192,187,213,243,112,244,244,233,245,245,128,188,188,114,174,134,131,220,174,217,236,236,198,134,215,177,58,156,143,124,25,110,7,31,228,25,264,356,368,0,11,267,451,452,349,267,302,269,350,357,277,350,452,357,299,333,297,396,175,377,381,384,382,280,347,330,269,303,270,151,9,337,344,278,360,424,418,431,270,304,409,272,310,407,322,270,410,449,450,347,432,422,434,18,313,17,291,306,375,259,387,260,424,335,418,434,364,416,391,423,327,301,251,298,275,281,4,254,373,253,375,307,321,280,425,411,200,421,18,335,321,406,321,320,405,314,315,17,423,426,266,396,377,369,270,322,269,413,417,464,385,386,258,248,456,419,298,284,333,168,417,8,448,346,261,417,413,285,326,327,328,277,355,329,309,392,438,381,382,256,279,429,360,365,364,379,355,277,437,282,443,283,281,275,363,395,431,369,299,297,337,335,273,321,348,450,349,359,446,467,283,293,282,250,458,462,300,276,383,292,308,325,283,276,293,264,372,447,346,352,340,354,274,19,363,456,281,426,436,425,380,381,252,267,269,393,421,200,428,371,266,329,432,287,422,290,250,328,385,258,384,446,265,342,386,387,257,422,424,430,445,342,276,422,273,424,306,292,307,352,366,345,268,271,302,358,423,371,327,294,460,331,279,294,303,271,304,436,432,427,304,272,408,395,394,431,378,395,400,296,334,299,6,351,168,376,352,411,307,325,320,285,295,336,320,319,404,329,330,349,334,293,333,366,323,447,316,15,315,331,358,279,317,14,316,8,285,9,277,329,350,253,374,252,319,318,403,351,6,419,324,318,325,397,367,365,288,435,397,278,344,439,310,272,311,248,195,281,375,273,291,175,396,199,312,311,268,276,283,445,390,373,339,295,282,296,448,449,346,356,264,454,337,336,299,337,338,151,294,278,455,308,292,415,429,358,355,265,340,372,388,390,466,352,346,280,295,442,282,354,19,370,285,441,295,195,248,197,457,440,274,301,300,368,417,351,465,251,301,389,385,380,386,394,395,379,399,412,419,410,436,322,387,373,388,326,2,393,354,370,461,393,164,267,268,302,12,386,374,387,312,268,13,298,293,301,265,446,340,380,385,381,280,330,425,322,426,391,420,429,437,393,391,326,344,440,438,458,459,461,364,434,394,428,396,262,274,354,457,317,316,402,316,315,403,315,314,404,314,313,405,313,421,406,323,366,361,292,306,407,306,291,408,291,287,409,287,432,410,427,434,411,372,264,383,459,309,457,366,352,401,1,274,4,418,421,262,331,294,358,435,433,367,392,289,439,328,462,326,94,2,370,289,305,455,339,254,448,359,255,446,254,253,449,253,252,450,252,256,451,256,341,452,414,413,463,286,441,414,286,258,441,258,257,442,257,259,443,259,260,444,260,467,445,309,459,250,305,289,290,305,290,460,401,376,435,309,250,392,376,411,433,453,341,464,357,453,465,343,357,412,437,343,399,344,360,440,420,437,456,360,420,363,361,401,288,265,372,353,390,339,249,339,448,255]});var SL=ge(cs=>{const Sn=Ct(),$8=aL(),bL=ep(),X8=mL(),J8=vL(),Z8=yL().default;cs.uv_coords=J8;cs.triangulation=Z8;async function Q8(n){return $8.load(n)}async function e7(n){return Sn.loadGraphModel(n,{fromTFHub:n.includes("tfhub.dev")})}async function t7(n){return Sn.loadGraphModel(n,{fromTFHub:n.includes("tfhub.dev")})}async function n7(n){const t=await Promise.all([Q8(n),e7(n.mesh.modelPath),t7(n.iris.modelPath)]),e=new wL(t[0],t[1],t[2],n);return e}cs.load=n7;class wL{constructor(n,t,e,i){this.pipeline=new X8.Pipeline(n,t,e,i),this.config=i}async estimateFaces(n,t){t&&(this.config=t);const e=Sn.tidy(()=>(n instanceof Sn.Tensor||(n=Sn.browser.fromPixels(n)),n.toFloat().expandDims(0))),i=[],r=await this.pipeline.predict(e,this.config.iris.enabled,this.config.mesh.enabled);if(e.dispose(),!r)return i;for(const a of r){const s=a.confidence.arraySync();if(s>=this.config.detector.minConfidence){const o={confidence:s||0,box:a.box?[a.box.startPoint[0],a.box.startPoint[1],a.box.endPoint[0]-a.box.startPoint[0],a.box.endPoint[1]-a.box.startPoint[1]]:0,mesh:a.coords?a.coords.arraySync():null,image:a.image?Sn.clone(a.image):null},l={};if(o.mesh&&o.mesh.length>0)for(const u in bL.MESH_ANNOTATIONS)(this.config.iris.enabled||u.includes("Iris")===!1)&&(l[u]=bL.MESH_ANNOTATIONS[u].map(c=>o.mesh[c]));o.annotations=l,i.push(o)}Sn.dispose(a.confidence),Sn.dispose(a.image),Sn.dispose(a.coords),Sn.dispose(a)}return Sn.dispose(r),i}}cs.MediaPipeFaceMesh=wL});var AL=ge(LL=>{const $t=Ct(),sa={};let IL={age:0,gender:""},lp=0;async function i7(n,t){const e=$t.tidy(()=>{const i=$t.browser.fromPixels(n),r=$t.image.resizeBilinear(i,[t,t]),a=$t.cast($t.expandDims(r,0),"float32");return a});return e}async function r7(n,t){if(lp+=1,lp>=t.face.age.skipFrames)return lp=0,IL;!sa.age&&t.face.age.enabled&&(sa.age=await $t.loadGraphModel(t.face.age.modelPath)),!sa.gender&&t.face.gender.enabled&&(sa.gender=await $t.loadGraphModel(t.face.gender.modelPath));let e;if(n instanceof $t.Tensor){const r=$t.image.resizeBilinear(n,[t.face.age.inputSize,t.face.age.inputSize],!1);e=$t.mul(r,[255]),$t.dispose(r)}else e=await i7(n,t.face.age.inputSize);const i={};if(t.face.age.enabled){const r=await sa.age.predict(e);i.age=Math.trunc(10*r.dataSync()[0])/10,$t.dispose(r)}if(t.face.gender.enabled){const r=await sa.gender.predict(e);i.gender=Math.trunc(100*r.dataSync()[0])<50?"female":"male",$t.dispose(r)}return $t.dispose(e),IL=i,i}LL.predict=r7});var xL=ge(TL=>{const NL=Ct();class a7{constructor(n,t){this.model=n,this.outputStride=t;const e=this.model.inputs[0].shape;NL.util.assert(e[1]===-1&&e[2]===-1,()=>`Input shape [${e[1]}, ${e[2]}] must both be equal to or -1`)}predict(n){return NL.tidy(()=>{const t=this.preprocessInput(n.toFloat()),e=t.expandDims(0),i=this.model.predict(e),r=i.map(s=>s.squeeze([0])),a=this.nameOutputResults(r);return{heatmapScores:a.heatmap.sigmoid(),offsets:a.offsets,displacementFwd:a.displacementFwd,displacementBwd:a.displacementBwd}})}dispose(){this.model.dispose()}}TL.BaseModel=a7});var up=ge(CL=>{const RL=Ct(),s7=xL();class o7 extends s7.BaseModel{preprocessInput(n){return RL.tidy(()=>RL.div(n,127.5).sub(1))}nameOutputResults(n){const[t,e,i,r]=n;return{offsets:t,heatmap:e,displacementFwd:i,displacementBwd:r}}}CL.MobileNet=o7});var EL=ge(OL=>{function cp(n){return Math.floor(n/2)}class l7{constructor(n,t){this.priorityQueue=new Array(n),this.numberOfElements=-1,this.getElementValue=t}enqueue(n){this.priorityQueue[++this.numberOfElements]=n,this.swim(this.numberOfElements)}dequeue(){const n=this.priorityQueue[0];return this.exchange(0,this.numberOfElements--),this.sink(0),this.priorityQueue[this.numberOfElements+1]=null,n}empty(){return this.numberOfElements===-1}size(){return this.numberOfElements+1}all(){return this.priorityQueue.slice(0,this.numberOfElements+1)}max(){return this.priorityQueue[0]}swim(n){for(;n>0&&this.less(cp(n),n);)this.exchange(n,cp(n)),n=cp(n)}sink(n){for(;2*n<=this.numberOfElements;){let t=2*n;if(t{const u7=EL();function c7(n,t,e,i,r,a){const[s,o]=a.shape;let l=!0;const u=Math.max(e-r,0),c=Math.min(e+r+1,s);for(let h=u;ht){l=!1;break}if(!l)break}return l}function h7(n,t,e){const[i,r,a]=e.shape,s=new u7.MaxHeap(i*r*a,({score:o})=>o);for(let o=0;o{Ln.partNames=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"];Ln.NUM_KEYPOINTS=Ln.partNames.length;Ln.partIds=Ln.partNames.reduce((n,t,e)=>(n[t]=e,n),{});const d7=[["leftHip","leftShoulder"],["leftElbow","leftShoulder"],["leftElbow","leftWrist"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["rightHip","rightShoulder"],["rightElbow","rightShoulder"],["rightElbow","rightWrist"],["rightHip","rightKnee"],["rightKnee","rightAnkle"],["leftShoulder","rightShoulder"],["leftHip","rightHip"]];Ln.poseChain=[["nose","leftEye"],["leftEye","leftEar"],["nose","rightEye"],["rightEye","rightEar"],["nose","leftShoulder"],["leftShoulder","leftElbow"],["leftElbow","leftWrist"],["leftShoulder","leftHip"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["nose","rightShoulder"],["rightShoulder","rightElbow"],["rightElbow","rightWrist"],["rightShoulder","rightHip"],["rightHip","rightKnee"],["rightKnee","rightAnkle"]];Ln.connectedPartIndices=d7.map(([n,t])=>[Ln.partIds[n],Ln.partIds[t]]);Ln.partChannels=["left_face","right_face","right_upper_leg_front","right_lower_leg_back","right_upper_leg_back","left_lower_leg_front","left_upper_leg_front","left_upper_leg_back","left_lower_leg_back","right_feet","right_lower_leg_front","left_feet","torso_front","torso_back","right_upper_arm_front","right_upper_arm_back","right_lower_arm_back","left_lower_arm_front","left_upper_arm_front","left_upper_arm_back","left_lower_arm_back","right_hand","right_lower_arm_front","left_hand"]});var dp=ge(Ni=>{const p7=dr();function FL(n,t,e,i){return{y:i.get(n,t,e),x:i.get(n,t,e+p7.NUM_KEYPOINTS)}}Ni.getOffsetPoint=FL;function f7(n,t,e){const{heatmapY:i,heatmapX:r,id:a}=n,{y:s,x:o}=FL(i,r,a,e);return{x:n.heatmapX*t+o,y:n.heatmapY*t+s}}Ni.getImageCoords=f7;function m7(n,t){const e=new Array(t);for(let i=0;ie?e:n}Ni.clamp=hp;function g7(n,t,e,i){const r=e-n,a=i-t;return r*r+a*a}Ni.squaredDistance=g7;function v7(n,t){return{x:n.x+t.x,y:n.y+t.y}}Ni.addVectors=v7;function y7(n,t,e){return{y:hp(n.y,t,e),x:hp(n.x,t,e)}}Ni.clampVector=y7});var PL=ge(WL=>{const hs=dr(),oa=dp(),UL=hs.poseChain.map(([n,t])=>[hs.partIds[n],hs.partIds[t]]),pp=UL.map(([,n])=>n),BL=UL.map(([n])=>n);function b7(n,t,e){const i=e.shape[2]/2;return{y:e.get(t.y,t.x,n),x:e.get(t.y,t.x,i+n)}}function fp(n,t,e,i){return{y:oa.clamp(Math.round(n.y/t),0,e-1),x:oa.clamp(Math.round(n.x/t),0,i-1)}}function zL(n,t,e,i,r,a,s,o=2){const[l,u]=i.shape,c=fp(t.position,a,l,u),h=b7(n,c,s),d=oa.addVectors(t.position,h);let p=d;for(let g=0;g=0;--d){const p=pp[d],f=BL[d];l[p]&&!l[f]&&(l[f]=zL(d,l[p],f,t,e,i,a))}for(let d=0;d{const S7=kL(),L7=PL(),ML=dp();function HL(n,t,{x:e,y:i},r){return n.some(({keypoints:a})=>{const s=a[r].position;return ML.squaredDistance(i,e,s.y,s.x)<=t})}function I7(n,t,e){const i=e.reduce((r,{position:a,score:s},o)=>(HL(n,t,a,o)||(r+=s),r),0);return i/e.length}const A7=1;function T7(n,t,e,i,r,a,s=.5,o=20){const l=[],u=S7.buildPartWithScoreQueue(s,A7,n),c=o*o;for(;l.length{const Zn=Ct(),gp=dr();function N7(n,t){const e=t.shape[0],i=new Float32Array(e);for(let r=0;r{const i=VL(n,e);return n.toTensor().mul(Zn.scalar(t,"int32")).toFloat().add(i)})}ds.getOffsetPoints=C7;function R7(n,t){return Zn.tidy(()=>{const e=n.div(Zn.scalar(t,"int32"));return n.sub(e.mul(Zn.scalar(t,"int32")))})}function O7(n){const[t,e,i]=n.shape;return Zn.tidy(()=>{const r=n.reshape([t*e,i]),a=r.argMax(0),s=a.div(Zn.scalar(e,"int32")).expandDims(1),o=R7(a,e).expandDims(1);return Zn.concat([s,o],1)})}ds.argmax2d=O7});var yp=ge(GL=>{const E7=dr(),vp=qL();async function D7(n,t,e){let i=0;const r=vp.argmax2d(n),a=await Promise.all([n.buffer(),t.buffer(),r.buffer()]),s=a[0],o=a[1],l=a[2],u=vp.getOffsetPoints(l,e,o),c=await u.buffer(),h=Array.from(vp.getPointsConfidence(s,l)),d=h.map((p,f)=>(i+=p,{position:{y:c.get(f,0),x:c.get(f,1)},part:E7.partNames[f],score:p}));return r.dispose(),u.dispose(),{keypoints:d,score:i/d.length}}GL.decodeSinglePose=D7});var wp=ge(ln=>{const la=Ct(),k7=dr();function F7(n,t,e){return n(F7(n[i].score,n[r].score,t)||e.push([n[i],n[r]]),e),[])}ln.getAdjacentKeyPoints=W7;const{NEGATIVE_INFINITY:YL,POSITIVE_INFINITY:KL}=Number;function jL(n){return n.reduce(({maxX:t,maxY:e,minX:i,minY:r},{position:{x:a,y:s}})=>({maxX:Math.max(t,a),maxY:Math.max(e,s),minX:Math.min(i,a),minY:Math.min(r,s)}),{maxX:YL,maxY:YL,minX:KL,minY:KL})}ln.getBoundingBox=jL;function U7(n){const{minX:t,minY:e,maxX:i,maxY:r}=jL(n);return[{x:t,y:e},{x:i,y:e},{x:i,y:r},{x:t,y:r}]}ln.getBoundingBoxPoints=U7;async function B7(n){return Promise.all(n.map(t=>t.buffer()))}ln.toTensorBuffers3D=B7;function $L(n,t,e,i=0,r=0){return{score:n.score,keypoints:n.keypoints.map(({score:a,part:s,position:o})=>({score:a,part:s,position:{x:o.x*e+r,y:o.y*t+i}}))}}ln.scalePose=$L;function XL(n,t,e,i=0,r=0){return e===1&&t===1&&i===0&&r===0?n:n.map(a=>$L(a,t,e,i,r))}ln.scalePoses=XL;function JL(n){return n instanceof la.Tensor?[n.shape[0],n.shape[1]]:[n.height,n.width]}ln.getInputTensorDimensions=JL;function bp(n){return n instanceof la.Tensor?n:la.browser.fromPixels(n)}ln.toInputTensor=bp;function z7(n,t,e){return la.tidy(()=>{const i=bp(n);return i.resizeBilinear([t,e])})}ln.toResizedInputTensor=z7;function P7(n,[t,e]){const[i,r]=JL(n),a=e/t,s=r/i;let[o,l,u,c]=[0,0,0,0];s{let d=bp(n);return d=la.pad3d(d,[[o,l],[u,c],[0,0]]),d.resizeBilinear([t,e])});return{resized:h,padding:{top:o,left:u,right:c,bottom:l}}}ln.padAndResizeTo=P7;function _7(n,[t,e],[i,r],a){const s=(t+a.top+a.bottom)/i,o=(e+a.left+a.right)/r,l=XL(n,s,o,-a.top,-a.left);return l}ln.scaleAndFlipPoses=_7});var QL=ge(Sp=>{const M7=Ct(),H7=up(),V7=mp(),q7=yp(),pr=wp();class ZL{constructor(n,t){this.baseModel=n,this.inputResolution=t}async estimateMultiplePoses(n,t){const e=this.baseModel.outputStride,i=this.inputResolution,[r,a]=pr.getInputTensorDimensions(n),{resized:s,padding:o}=pr.padAndResizeTo(n,[i,i]),{heatmapScores:l,offsets:u,displacementFwd:c,displacementBwd:h}=this.baseModel.predict(s),d=await pr.toTensorBuffers3D([l,u,c,h]),p=d[0],f=d[1],m=d[2],g=d[3],v=await V7.decodeMultiplePoses(p,f,m,g,e,t.maxDetections,t.scoreThreshold,t.nmsRadius),b=pr.scaleAndFlipPoses(v,[r,a],[i,i],o);return l.dispose(),u.dispose(),c.dispose(),h.dispose(),s.dispose(),b}async estimateSinglePose(n){const t=this.baseModel.outputStride,e=this.inputResolution,[i,r]=pr.getInputTensorDimensions(n),{resized:a,padding:s}=pr.padAndResizeTo(n,e),{heatmapScores:o,offsets:l,displacementFwd:u,displacementBwd:c}=this.baseModel.predict(a),h=await q7.decodeSinglePose(o,l,t),d=[h],p=pr.scaleAndFlipPoses(d,[i,r],[e,e],s);return o.dispose(),l.dispose(),u.dispose(),c.dispose(),a.dispose(),p[0]}dispose(){this.baseModel.dispose()}}Sp.PoseNet=ZL;async function G7(n){const t=n.outputStride,e=await M7.loadGraphModel(n.modelPath),i=new H7.MobileNet(e,t);return new ZL(i,n.inputResolution)}async function Y7(n){return G7(n)}Sp.load=Y7});var tI=ge(Mt=>{const K7=up(),eI=QL(),j7=mp(),$7=yp(),Jo=dr(),ps=wp();Mt.load=eI.load;Mt.PoseNet=eI.PoseNet;Mt.MobileNet=K7.MobileNet;Mt.decodeMultiplePoses=j7.decodeMultiplePoses;Mt.decodeSinglePose=$7.decodeSinglePose;Mt.partChannels=Jo.partChannels;Mt.partIds=Jo.partIds;Mt.partNames=Jo.partNames;Mt.poseChain=Jo.poseChain;Mt.getAdjacentKeyPoints=ps.getAdjacentKeyPoints;Mt.getBoundingBox=ps.getBoundingBox;Mt.getBoundingBoxPoints=ps.getBoundingBoxPoints;Mt.scaleAndFlipPoses=ps.scaleAndFlipPoses;Mt.scalePose=ps.scalePose});var Ap=ge(xi=>{const X7=Ct();function Lp(n){return[Math.abs(n.endPoint[0]-n.startPoint[0]),Math.abs(n.endPoint[1]-n.startPoint[1])]}xi.getBoxSize=Lp;function Ip(n){return[n.startPoint[0]+(n.endPoint[0]-n.startPoint[0])/2,n.startPoint[1]+(n.endPoint[1]-n.startPoint[1])/2]}xi.getBoxCenter=Ip;function J7(n,t,e){const i=t.shape[1],r=t.shape[2],a=[[n.startPoint[1]/i,n.startPoint[0]/r,n.endPoint[1]/i,n.endPoint[0]/r]];return X7.image.cropAndResize(t,a,[0],e)}xi.cutBoxFromImageAndResize=J7;function Z7(n,t){const e=[n.startPoint[0]*t[0],n.startPoint[1]*t[1]],i=[n.endPoint[0]*t[0],n.endPoint[1]*t[1]],r=n.palmLandmarks.map(a=>{const s=[a[0]*t[0],a[1]*t[1]];return s});return{startPoint:e,endPoint:i,palmLandmarks:r}}xi.scaleBoxCoordinates=Z7;function Q7(n,t=1.5){const e=Ip(n),i=Lp(n),r=[t*i[0]/2,t*i[1]/2],a=[e[0]-r[0],e[1]-r[1]],s=[e[0]+r[0],e[1]+r[1]];return{startPoint:a,endPoint:s,palmLandmarks:n.palmLandmarks}}xi.enlargeBox=Q7;function eH(n){const t=Ip(n),e=Lp(n),i=Math.max(...e),r=i/2,a=[t[0]-r,t[1]-r],s=[t[0]+r,t[1]+r];return{startPoint:a,endPoint:s,palmLandmarks:n.palmLandmarks}}xi.squarifyBox=eH;function tH(n,t){const e=[n.endPoint[0]-n.startPoint[0],n.endPoint[1]-n.startPoint[1]],i=[e[0]*t[0],e[1]*t[1]],r=[n.startPoint[0]+i[0],n.startPoint[1]+i[1]],a=[n.endPoint[0]+i[0],n.endPoint[1]+i[1]];return{startPoint:r,endPoint:a,palmLandmarks:n.palmLandmarks}}xi.shiftBox=tH});var iI=ge(nI=>{const Ue=Ct(),nH=Ap();class iH{constructor(n,t,e,i,r,a){this.model=n,this.width=t,this.height=e,this.iouThreshold=r,this.scoreThreshold=a,this.anchors=i.map(s=>[s.x_center,s.y_center]),this.anchorsTensor=Ue.tensor2d(this.anchors),this.inputSizeTensor=Ue.tensor1d([t,e]),this.doubleInputSizeTensor=Ue.tensor1d([t*2,e*2])}normalizeBoxes(n){return Ue.tidy(()=>{const t=Ue.slice(n,[0,0],[-1,2]),e=Ue.slice(n,[0,2],[-1,2]),i=Ue.add(Ue.div(t,this.inputSizeTensor),this.anchorsTensor),r=Ue.div(e,this.doubleInputSizeTensor),a=Ue.mul(Ue.sub(i,r),this.inputSizeTensor),s=Ue.mul(Ue.add(i,r),this.inputSizeTensor);return Ue.concat2d([a,s],1)})}normalizeLandmarks(n,t){return Ue.tidy(()=>{const e=Ue.add(Ue.div(n.reshape([-1,7,2]),this.inputSizeTensor),this.anchors[t]);return Ue.mul(e,this.inputSizeTensor)})}async getBoundingBoxes(n){const t=Ue.tidy(()=>Ue.mul(Ue.sub(n,.5),2));let e;if(Ue.getBackend()==="webgl"){const f=Ue.env().get("WEBGL_PACK_DEPTHWISECONV");Ue.env().set("WEBGL_PACK_DEPTHWISECONV",!0),e=this.model.predict(t),Ue.env().set("WEBGL_PACK_DEPTHWISECONV",f)}else e=this.model.predict(t);const i=e.squeeze(),r=Ue.tidy(()=>Ue.sigmoid(Ue.slice(i,[0,0],[-1,1])).squeeze()),a=Ue.slice(i,[0,1],[-1,4]),s=this.normalizeBoxes(a),o=await Ue.image.nonMaxSuppressionAsync(s,r,1,this.iouThreshold,this.scoreThreshold),l=await o.array(),u=[t,e,o,i,s,a,r];if(l.length===0)return u.forEach(f=>f.dispose()),null;const c=l[0],h=Ue.slice(s,[c,0],[1,-1]),d=Ue.slice(i,[c,5],[1,14]),p=Ue.tidy(()=>this.normalizeLandmarks(d,c).reshape([-1,2]));return u.push(d),u.forEach(f=>f.dispose()),{boxes:h,palmLandmarks:p}}async estimateHandBounds(n){const t=n.shape[1],e=n.shape[2],i=Ue.tidy(()=>n.resizeBilinear([this.width,this.height]).div(255)),r=await this.getBoundingBoxes(i);if(r===null)return i.dispose(),null;const a=r.boxes.arraySync(),s=a[0].slice(0,2),o=a[0].slice(2,4),l=r.palmLandmarks.arraySync();return i.dispose(),r.boxes.dispose(),r.palmLandmarks.dispose(),nH.scaleBoxCoordinates({startPoint:s,endPoint:o,palmLandmarks:l},[e/this.width,t/this.height])}}nI.HandDetector=iH});var aI=ge(rI=>{rI.MESH_ANNOTATIONS={thumb:[1,2,3,4],indexFinger:[5,6,7,8],middleFinger:[9,10,11,12],ringFinger:[13,14,15,16],pinky:[17,18,19,20],palmBase:[0]}});var cI=ge(Ci=>{function sI(n){return n-2*Math.PI*Math.floor((n+Math.PI)/(2*Math.PI))}Ci.normalizeRadians=sI;function rH(n,t){const e=Math.PI/2-Math.atan2(-(t[1]-n[1]),t[0]-n[0]);return sI(e)}Ci.computeRotation=rH;const oI=(n,t)=>[[1,0,n],[0,1,t],[0,0,1]];function ua(n,t){let e=0;for(let i=0;i{const ca=Ct(),zn=Ap(),Ri=cI(),lH=.8,uH=[0,-.4],cH=3,hH=[0,-.1],dH=1.65,dI=[0,5,9,13,17,1,2],pH=0,fH=2;class mH{constructor(n,t,e,i,r,a){this.regionsOfInterest=[],this.runsWithoutHandDetector=0,this.boundingBoxDetector=n,this.meshDetector=t,this.maxContinuousChecks=r,this.detectionConfidence=a,this.meshWidth=e,this.meshHeight=i,this.maxHandsNumber=1}getBoxForPalmLandmarks(n,t){const e=n.map(r=>{const a=[...r,1];return Ri.rotatePoint(a,t)}),i=this.calculateLandmarksBoundingBox(e);return zn.enlargeBox(zn.squarifyBox(zn.shiftBox(i,uH)),cH)}getBoxForHandLandmarks(n){const t=this.calculateLandmarksBoundingBox(n),e=zn.enlargeBox(zn.squarifyBox(zn.shiftBox(t,hH)),dH),i=[];for(let r=0;r[a[0]*(d[0]-this.meshWidth/2),a[1]*(d[1]-this.meshHeight/2),d[2]]),o=Ri.buildRotationMatrix(e,[0,0]),l=s.map(d=>{const p=Ri.rotatePoint(d,o);return[...p,d[2]]}),u=Ri.invertTransformMatrix(i),c=[...zn.getBoxCenter(t),1],h=[Ri.dot(c,u[0]),Ri.dot(c,u[1])];return l.map(d=>[d[0]+h[0],d[1]+h[1],d[2]])}async estimateHand(n,t){const e=this.shouldUpdateRegionsOfInterest();if(e===!0){const L=await this.boundingBoxDetector.estimateHandBounds(n);if(L===null)return n.dispose(),this.regionsOfInterest=[],null;this.updateRegionsOfInterest(L,!0),this.runsWithoutHandDetector=0}else this.runsWithoutHandDetector++;const i=this.regionsOfInterest[0],r=Ri.computeRotation(i.palmLandmarks[pH],i.palmLandmarks[fH]),a=zn.getBoxCenter(i),s=[a[0]/n.shape[2],a[1]/n.shape[1]],o=ca.image.rotateWithOffset(n,r,0,s),l=Ri.buildRotationMatrix(-r,a),u=e?this.getBoxForPalmLandmarks(i.palmLandmarks,l):i,c=zn.cutBoxFromImageAndResize(u,o,[this.meshWidth,this.meshHeight]),h=c.div(255);c.dispose(),o.dispose();let d;if(ca.getBackend()==="webgl"){const L=ca.env().get("WEBGL_PACK_DEPTHWISECONV");ca.env().set("WEBGL_PACK_DEPTHWISECONV",!0),d=this.meshDetector.predict(h),ca.env().set("WEBGL_PACK_DEPTHWISECONV",L)}else d=this.meshDetector.predict(h);const[p,f]=d;h.dispose();const m=p.dataSync()[0];if(p.dispose(),ma[0]),e=n.map(a=>a[1]),i=[Math.min(...t),Math.min(...e)],r=[Math.max(...t),Math.max(...e)];return{startPoint:i,endPoint:r}}updateRegionsOfInterest(n,t){if(t)this.regionsOfInterest=[n];else{const e=this.regionsOfInterest[0];let i=0;if(e!=null&&e.startPoint!=null){const[r,a]=n.startPoint,[s,o]=n.endPoint,[l,u]=e.startPoint,[c,h]=e.endPoint,d=Math.max(r,l),p=Math.max(a,u),f=Math.min(s,c),m=Math.min(o,h),g=(f-d)*(m-p),v=(s-r)*(o-a),b=(c-l)*(h-a);i=g/(v+b-g)}this.regionsOfInterest[0]=i>lH?e:n}}shouldUpdateRegionsOfInterest(){const n=this.regionsOfInterest.length;return n!==this.maxHandsNumber||this.runsWithoutHandDetector>=this.maxContinuousChecks}}hI.HandPipeline=mH});var mI=ge(Tp=>{const ha=Ct(),gH=iI(),Np=aI(),vH=pI();async function yH(n){return ha.loadGraphModel(n,{fromTFHub:n.includes("tfhub.dev")})}async function bH(n){return ha.loadGraphModel(n,{fromTFHub:n.includes("tfhub.dev")})}async function wH(n){return ha.util.fetch(n).then(t=>t.json())}async function SH(n){const[t,e,i]=await Promise.all([wH(n.detector.anchors),yH(n.detector.modelPath),bH(n.skeleton.modelPath)]),r=new gH.HandDetector(e,n.inputSize,n.inputSize,t,n.iouThreshold,n.scoreThreshold),a=new vH.HandPipeline(r,i,n.inputSize,n.inputSize,n.skipFrames,n.minConfidence),s=new fI(a);return s}Tp.load=SH;class fI{constructor(n){this.pipeline=n}static getAnnotations(){return Np.MESH_ANNOTATIONS}async estimateHands(n,t){const e=ha.tidy(()=>(n instanceof ha.Tensor||(n=ha.browser.fromPixels(n)),n.toFloat().expandDims(0))),i=await this.pipeline.estimateHand(e,t);if(e.dispose(),!i)return[];const r={};for(const a of Object.keys(Np.MESH_ANNOTATIONS))r[a]=Np.MESH_ANNOTATIONS[a].map(s=>i.landmarks[s]);return[{confidence:i.confidence||0,box:i.box?[i.box.topLeft[0],i.box.topLeft[1],i.box.bottomRight[0]-i.box.topLeft[0],i.box.bottomRight[1]-i.box.topLeft[1]]:0,landmarks:i.landmarks,annotations:r}]}}Tp.HandPose=fI});var gI=ge(LH=>{Cp(LH,{default:()=>IH});var IH={face:{enabled:!0,detector:{modelPath:"/models/blazeface/model.json",inputSize:128,maxFaces:10,skipFrames:5,minConfidence:.8,iouThreshold:.3,scoreThreshold:.75},mesh:{enabled:!0,modelPath:"/models/facemesh/model.json",inputSize:192},iris:{enabled:!0,modelPath:"../models/iris/model.json",inputSize:192},age:{enabled:!0,modelPath:"../models/ssrnet-age/imdb/model.json",inputSize:64,skipFrames:5},gender:{enabled:!0,modelPath:"../models/ssrnet-gender/imdb/model.json"}},body:{enabled:!0,modelPath:"../models/posenet/model.json",inputResolution:257,outputStride:16,maxDetections:5,scoreThreshold:.75,nmsRadius:20},hand:{enabled:!0,inputSize:256,skipFrames:5,minConfidence:.8,iouThreshold:.3,scoreThreshold:.75,detector:{anchors:"../models/handdetect/anchors.json",modelPath:"../models/handdetect/model.json"},skeleton:{modelPath:"../models/handskeleton/model.json"}}}});var II=ge(Qn=>{const AH=Ct(),vI=SL(),yI=AL(),bI=tI(),wI=mI(),SI=gI().default,Pn={facemesh:null,blazeface:null,ssrnet:null,iris:null};function LI(...n){const t=e=>e&&typeof e=="object";return n.reduce((e,i)=>(Object.keys(i||{}).forEach(r=>{const a=e[r],s=i[r];Array.isArray(a)&&Array.isArray(s)?e[r]=a.concat(...s):t(a)&&t(s)?e[r]=LI(a,s):e[r]=s}),e),{})}async function TH(n,t){const e=LI(SI,t);let i=[];e.body.enabled&&(Pn.posenet||(Pn.posenet=await bI.load(e.body)),i=await Pn.posenet.estimateMultiplePoses(n,e.body));let r=[];e.hand.enabled&&(Pn.handpose||(Pn.handpose=await wI.load(e.hand)),r=await Pn.handpose.estimateHands(n,e.hand));const a=[];if(e.face.enabled){Pn.facemesh||(Pn.facemesh=await vI.load(e.face));const s=await Pn.facemesh.estimateFaces(n,e.face);for(const o of s){const l=e.face.age.enabled||e.face.gender.enabled?await yI.predict(o.image,e):{},u=o.annotations.leftEyeIris&&o.annotations.rightEyeIris?Math.max(o.annotations.leftEyeIris[3][0]-o.annotations.leftEyeIris[1][0],o.annotations.rightEyeIris[3][0]-o.annotations.rightEyeIris[1][0]):0;a.push({confidence:o.confidence,box:o.box,mesh:o.mesh,annotations:o.annotations,age:l.age,gender:l.gender,iris:u!==0?Math.trunc(100*11.7/u)/100:0})}}return{face:a,body:i,hand:r}}Qn.detect=TH;Qn.defaults=SI;Qn.models=Pn;Qn.facemesh=vI;Qn.ssrnet=yI;Qn.posenet=bI;Qn.handpose=wI;Qn.tf=AH});export default II(); /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use diff --git a/dist/human.esm.js.map b/dist/human.esm.js.map index 0b55d0f7..6aee99dc 100644 --- a/dist/human.esm.js.map +++ b/dist/human.esm.js.map @@ -1,7 +1,7 @@ { "version": 3, "sources": ["empty:/home/vlado/dev/human/node_modules/node-fetch/browser.js", "empty:util", "empty:crypto", "node_modules/@tensorflow/tfjs-core/dist/../src/backends/backend.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/environment.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/global_util.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/kernel_names.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/kernel_registry.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/util.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/profiler.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/tape.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/tensor_format.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/tensor.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/types.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/tensor_util.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/engine.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/device_util.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/flags.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/tensor_util_env.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/operation.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/complex.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/tensor_ops_util.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/tensor.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/io/types.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/io/io_utils.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/io/router_registry.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/io/indexed_db.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/io/local_storage.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/io/model_management.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/platforms/platform_browser.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/platforms/platform_node.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/buffer.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/cast.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/clone.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/print.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/base_side_effects.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/io/browser_files.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/io/progress.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/io/weights_loader.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/io/http.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/io/passthrough.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/io/io.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/reshape.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/mat_mul.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/one_hot.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/transpose.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/confusion_matrix.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/math.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/tensor3d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/browser.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/gather_nd_util.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/scatter_nd_util.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/slice_util.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/serialization.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/test_util.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/version.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/globals.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/add.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/floorDiv.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/div.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/mul.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/abs.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/acos.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/acosh.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/add_n.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/axis_util.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/all.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/any.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/arg_max.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/arg_min.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/asin.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/asinh.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/atan.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/atan2.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/atanh.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/conv_util.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/avg_pool.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/avg_pool_3d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/concat_util.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/concat.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/sigmoid.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/slice.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/tanh.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/basic_lstm_cell.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/batch_to_space_nd.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/batchnorm_util.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/batchnorm.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/batchnorm2d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/batchnorm3d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/batchnorm4d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/broadcast_to.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/ceil.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/clip_by_value.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/concat_1d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/concat_2d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/concat_3d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/concat_4d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/conv2d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/conv1d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/conv2d_backprop_input.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/conv2d_transpose.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/conv3d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/conv3d_backprop_input.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/conv3d_transpose.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/cos.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/cosh.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/cumsum.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/depth_to_space.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/depthwise_conv2d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/diag.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/dilation2d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/broadcast_util.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/equal.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/where.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/zeros_like.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/div_no_nan.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/dot.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/elu.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/erf.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/exp.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/expand_dims.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/expm1.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/tile.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/eye.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/fill.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/floor.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/reduce_util.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/segment_util.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/gather.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/greater.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/greater_equal.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/imag.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/is_finite.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/is_inf.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/is_nan.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/maximum.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/scalar.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/leaky_relu.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/less.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/less_equal.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/linspace.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/local_response_normalization.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/log.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/log1p.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/neg.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/softplus.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/log_sigmoid.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/max.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/sub.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/sum.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/log_softmax.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/log_sum_exp.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/logical_and.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/logical_not.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/logical_or.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/logical_xor.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/max_pool.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/max_pool_3d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/max_pool_with_argmax.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/zeros.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/ones.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/mean.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/min.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/minimum.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/mod.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/square.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/moments.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/multi_rnn_cell.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/multinomial.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/not_equal.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/real.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/ones_like.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/outer_product.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/pad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/pad1d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/pad2d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/pad3d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/pad4d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/space_to_batch_nd.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/pool.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/pow.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/prelu.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/prod.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/rand.ts", "node_modules/@tensorflow/tfjs-core/dist/../node_modules/seedrandom/lib/alea.js", "node_modules/@tensorflow/tfjs-core/dist/../node_modules/seedrandom/lib/xor128.js", "node_modules/@tensorflow/tfjs-core/dist/../node_modules/seedrandom/lib/xorwow.js", "node_modules/@tensorflow/tfjs-core/dist/../node_modules/seedrandom/lib/xorshift7.js", "node_modules/@tensorflow/tfjs-core/dist/../node_modules/seedrandom/lib/xor4096.js", "node_modules/@tensorflow/tfjs-core/dist/../node_modules/seedrandom/lib/tychei.js", "node_modules/@tensorflow/tfjs-core/dist/../node_modules/seedrandom/seedrandom.js", "node_modules/@tensorflow/tfjs-core/dist/../node_modules/seedrandom/index.js", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/rand_util.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/random_gamma.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/random_normal.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/random_uniform.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/tensor1d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/range.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/reciprocal.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/relu.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/relu6.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/reverse.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/reverse_1d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/reverse_2d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/reverse_3d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/reverse_4d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/round.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/rsqrt.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/selu.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/separable_conv2d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/setdiff1d_async.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/sign.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/sin.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/sinh.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/slice1d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/slice2d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/slice3d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/slice4d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/softmax.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/spectral/fft.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/spectral/ifft.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/spectral/irfft.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/split_util.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/split.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/spectral/rfft.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/sqrt.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/squared_difference.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/squeeze.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/stack.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/step.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/strided_slice.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/tan.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/tensor2d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/tensor4d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/tensor5d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/tensor6d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/topk.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/truncated_normal.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/unique.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/unsorted_segment_sum.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/unstack.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/variable.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/backends/where_impl.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/where_async.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/boolean_mask.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/compare.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/binary_ops.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/norm.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/moving_average.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/scatter_nd.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/sparse_to_dense_util.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/sparse_to_dense.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/gather_nd.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/dropout_util.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/dropout.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/signal_ops_util.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/in_top_k.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/conv2d_backprop_filter.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/fused_util.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/fused/conv2d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/depthwise_conv2d_native_backprop_filter.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/depthwise_conv2d_native_backprop_input.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/fused/depthwise_conv2d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/fused/mat_mul.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/fused_ops.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/signal/hamming_window.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/signal/hann_window.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/signal/frame.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/signal/stft.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/image/crop_and_resize.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/image/flip_left_right.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/image/rotate_with_offset.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/nonmax_util.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/image/non_max_suppression.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/backends/array_util.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/backends/non_max_suppression_impl.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/image/non_max_suppression_async.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/image/non_max_suppression_with_score.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/image/non_max_suppression_with_score_async.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/image/non_max_suppression_padded.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/image/non_max_suppression_padded_async.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/image/resize_bilinear.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/image/resize_nearest_neighbor.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/linalg/band_part.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/linalg/gram_schmidt.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/linalg/qr.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/loss_ops_utils.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/losses/compute_weighted_loss.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/losses/absolute_difference.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/losses/cosine_distance.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/losses/hinge_loss.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/losses/huber_loss.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/losses/log_loss.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/losses/mean_squared_error.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/losses/sigmoid_cross_entropy.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/losses/softmax_cross_entropy.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/ops.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/optimizers/optimizer.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/optimizers/adadelta_optimizer.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/optimizers/adagrad_optimizer.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/optimizers/adam_optimizer.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/optimizers/adamax_optimizer.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/optimizers/sgd_optimizer.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/optimizers/momentum_optimizer.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/optimizers/rmsprop_optimizer.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/optimizers/optimizer_constructors.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/train.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/browser_util.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/rotate_util.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/array_ops_util.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/selu_util.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/erf_util.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/log.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/backends/complex_util.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/backends/backend_util.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/backends/split_shared.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/backends/tile_impl.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/backends/topk_impl.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/backends/kernel_impls.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Abs_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Acos_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Acosh_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Add_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/AddN_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/ArgMax_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/ArgMin_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Asin_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Asinh_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Atan2_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Atan_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Atanh_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/avg_pool_3d_backprop.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/AvgPool3D_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/avg_pool_backprop.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/AvgPool_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/BatchMatMul_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/BatchToSpaceND_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/BroadcastTo_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Cast_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Ceil_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/ClipByValue_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Concat_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Conv2D_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Conv2DBackpropInput_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/conv3d_backprop_filter.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Conv3D_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Cos_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Cosh_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Cumsum_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/DepthwiseConv2dNative_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Dilation2D_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Div_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Elu_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Erf_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Exp_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Expm1_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Floor_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/FloorDiv_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/FusedBatchNorm_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/GatherV2_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/GreaterEqual_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Identity_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/IsFinite_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/IsInf_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/IsNan_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Log1p_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Log_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/LogSoftmax_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/local_response_normalization_backprop.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/LRN_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/min_max_grad_util.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Max_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Maximum_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/max_pool_3d_backprop.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/MaxPool3D_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/ops/max_pool_backprop.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/MaxPool_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Min_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Minimum_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Mod_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Multiply_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Negate_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/OneHot_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/OnesLike_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/PadV2_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Pow_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Prelu_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Reciprocal_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Relu6_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Relu_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Reshape_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/ResizeBilinear_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/ResizeNearestNeighbor_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Reverse_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Round_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Rsqrt_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/SelectV2_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Selu_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Sigmoid_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Sign_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Sin_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Sinh_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Slice_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Softmax_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Softplus_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/SpaceToBatchND_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/SplitV_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Sqrt_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Square_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/SquaredDifference_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Step_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Sub_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Sum_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Tan_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Tanh_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Tile_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Transpose_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/Unpack_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/UnsortedSegmentSum_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/gradients/ZerosLike_grad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/register_all_gradients.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/abs.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/acos.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/acosh.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/add_strict.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/add.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/all.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/any.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/arg_max.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/arg_min.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/as_scalar.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/as_type.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/as1d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/as2d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/as3d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/as4d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/as5d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/asin.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/asinh.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/atan.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/atan2.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/atanh.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/avg_pool.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/batch_to_space_nd.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/batchnorm.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/broadcast_to.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/cast.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/ceil.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/clip_by_value.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/concat.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/conv1d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/conv2d_transpose.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/conv2d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/cos.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/cosh.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/cumsum.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/depth_to_space.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/depthwise_conv2D_deprecated.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/depthwise_conv2d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/dilation2d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/div_no_nan.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/div_strict.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/div.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/dot.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/elu.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/equal_strict.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/equal.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/erf.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/exp.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/expand_dims.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/expm1.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/fft.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/flatten.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/floor.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/floorDiv.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/gather.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/greater_equal_strict.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/greater_equal.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/greater_strict.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/greater.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/ifft.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/irfft.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/is_finite.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/is_inf.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/is_nan.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/leaky_relu.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/less_equal_strict.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/less_equal.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/less_strict.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/less.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/local_response_normalization.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/log_sigmoid.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/log_softmax.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/log_sum_exp.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/log.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/log1p.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/logical_and.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/logical_not.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/logical_or.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/logical_xor.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/mat_mul.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/max_pool.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/max.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/maximum_strict.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/maximum.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/mean.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/min.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/minimum_strict.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/minimum.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/mod_strict.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/mod.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/mul_strict.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/mul.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/neg.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/norm.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/not_equal_strict.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/not_equal.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/one_hot.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/ones_like.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/pad.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/pool.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/pow_strict.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/pow.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/prelu.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/prod.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/reciprocal.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/relu.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/relu6.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/reshape_as.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/reshape.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/resize_bilinear.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/resize_nearest_neighbor.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/reverse.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/rfft.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/round.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/rsqrt.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/selu.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/separable_conv2d.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/sigmoid.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/sign.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/sin.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/sinh.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/slice.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/softmax.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/softplus.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/space_to_batch_nd.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/split.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/sqrt.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/square.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/squared_difference.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/squared_difference_strict.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/squeeze.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/stack.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/step.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/strided_slice.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/sub_strict.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/sub.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/sum.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/tan.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/tanh.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/tile.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/to_bool.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/to_float.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/to_int.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/topk.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/transpose.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/unique.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/unsorted_segment_sum.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/unstack.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/where.ts", "node_modules/@tensorflow/tfjs-core/dist/../src/public/chained_ops/zeros_like.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/backend/common.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/errors.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/utils/generic_utils.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/constraints.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/exports_constraints.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/keras_format/common.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/common.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/utils/math_utils.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/backend/tfjs_backend.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/keras_format/initializer_config.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/initializers.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/exports_initializers.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/backend/state.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/utils/types_utils.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/utils/variable_utils.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/variables.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/engine/topology.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/engine/input_layer.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/logs.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/base_callbacks.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/layers/serialization.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/losses.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/metrics.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/optimizers.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/user_defined_metadata.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/utils/layer_utils.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/utils/serialization_utils.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/version.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/engine/executor.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/engine/container.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/engine/training_utils.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/engine/training_dataset.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/engine/training_tensors.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/engine/training.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/models.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/exports.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/activations.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/regularizers.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/layers/advanced_activations.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/utils/conv_utils.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/layers/convolutional.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/layers/convolutional_depthwise.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/layers/recurrent.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/layers/convolutional_recurrent.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/layers/core.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/layers/embeddings.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/layers/merge.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/layers/noise.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/layers/normalization.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/layers/padding.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/layers/pooling.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/layers/wrappers.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/exports_layers.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/exports_metrics.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/exports_models.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/exports_regularizers.ts", "node_modules/@tensorflow/tfjs-layers/dist/../src/callbacks.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/data/compiled_api.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/custom_op/register.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/executors/utils.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/op_list/arithmetic.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/op_list/basic_math.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/op_list/control.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/op_list/convolution.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/op_list/creation.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/op_list/dynamic.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/op_list/evaluation.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/op_list/graph.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/op_list/image.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/op_list/logical.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/op_list/matrices.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/op_list/normalization.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/op_list/reduction.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/op_list/slice_join.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/op_list/spectral.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/op_list/transformation.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/operation_mapper.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/custom_op/node_value_impl.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/executors/arithmetic_executor.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/executors/basic_math_executor.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/executor/tensor_utils.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/executor/tensor_array.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/executor/tensor_list.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/executors/control_executor.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/executors/convolution_executor.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/executors/creation_executor.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/executors/dynamic_executor.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/executors/evaluation_executor.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/executors/graph_executor.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/executors/image_executor.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/executors/logical_executor.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/executors/matrices_executor.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/executors/normalization_executor.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/executors/reduction_executor.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/executors/slice_join_executor.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/executors/spectral_executor.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/executors/transformation_executor.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/operations/operation_executor.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/executor/execution_context.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/executor/model_analysis.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/executor/graph_executor.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/executor/graph_model.ts", "node_modules/@tensorflow/tfjs-converter/dist/../src/version.ts", "empty:string_decoder", "empty:fs", "node_modules/@tensorflow/tfjs-data/dist/../node_modules/seedrandom/lib/alea.js", "node_modules/@tensorflow/tfjs-data/dist/../node_modules/seedrandom/lib/xor128.js", "node_modules/@tensorflow/tfjs-data/dist/../node_modules/seedrandom/lib/xorwow.js", "node_modules/@tensorflow/tfjs-data/dist/../node_modules/seedrandom/lib/xorshift7.js", "node_modules/@tensorflow/tfjs-data/dist/../node_modules/seedrandom/lib/xor4096.js", "node_modules/@tensorflow/tfjs-data/dist/../node_modules/seedrandom/lib/tychei.js", "node_modules/@tensorflow/tfjs-data/dist/../node_modules/seedrandom/seedrandom.js", "node_modules/@tensorflow/tfjs-data/dist/../node_modules/seedrandom/index.js", "node_modules/@tensorflow/tfjs-data/dist/../src/util/deep_map.ts", "node_modules/@tensorflow/tfjs-data/dist/../src/util/deep_clone.ts", "node_modules/@tensorflow/tfjs-data/dist/../src/util/ring_buffer.ts", "node_modules/@tensorflow/tfjs-data/dist/../src/util/growing_ring_buffer.ts", "node_modules/@tensorflow/tfjs-data/dist/../src/iterators/lazy_iterator.ts", "node_modules/@tensorflow/tfjs-data/dist/../src/dataset.ts", "node_modules/@tensorflow/tfjs-data/dist/../src/datasets/text_line_dataset.ts", "node_modules/@tensorflow/tfjs-data/dist/../src/datasets/csv_dataset.ts", "node_modules/@tensorflow/tfjs-data/dist/../src/iterators/microphone_iterator.ts", "node_modules/@tensorflow/tfjs-data/dist/../src/iterators/webcam_iterator.ts", "node_modules/@tensorflow/tfjs-data/dist/../src/datasource.ts", "node_modules/@tensorflow/tfjs-data/dist/../src/iterators/string_iterator.ts", "node_modules/@tensorflow/tfjs-data/dist/../src/iterators/byte_chunk_iterator.ts", "node_modules/@tensorflow/tfjs-data/dist/../src/iterators/file_chunk_iterator.ts", "node_modules/@tensorflow/tfjs-data/dist/../src/iterators/url_chunk_iterator.ts", "node_modules/@tensorflow/tfjs-data/dist/../src/util/source_util.ts", "node_modules/@tensorflow/tfjs-data/dist/../src/sources/file_data_source.ts", "node_modules/@tensorflow/tfjs-data/dist/../src/sources/url_data_source.ts", "node_modules/@tensorflow/tfjs-data/dist/../src/readers.ts", "node_modules/@tensorflow/tfjs-data/dist/../src/version.ts", "node_modules/seedrandom/lib/alea.js", "node_modules/seedrandom/lib/xor128.js", "node_modules/seedrandom/lib/xorwow.js", "node_modules/seedrandom/lib/xorshift7.js", "node_modules/seedrandom/lib/xor4096.js", "node_modules/seedrandom/lib/tychei.js", "node_modules/seedrandom/seedrandom.js", "node_modules/seedrandom/index.js", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/cpu_util.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/backend_cpu.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Abs.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/utils/binary_impl.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Complex.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Identity.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Real.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Cast.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/utils/kernel_utils.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Add.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/utils/unary_impl.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/utils/unary_utils.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Ceil.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Exp.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Expm1.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Floor.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Log.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Max_impl.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Multiply.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Rsqrt.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Slice.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Sub.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Transpose_impl.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Unique_impl.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/shared.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/version.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/base.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Acos.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Acosh.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Asin.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Asinh.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Atan.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Atanh.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/utils/pool_utils.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/AvgPool.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/AvgPoolBackprop.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/BatchNorm.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Clip.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Imag.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Reshape.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Concat.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Cos.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Cosh.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Dilation2D.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Dilation2DBackpropFilter.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Dilation2DBackpropInput.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Div.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Elu.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Erf.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/utils/fft_utils.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/FFT.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/FlipLeftRight.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/IFFT.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/IsFinite.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/IsInf.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/IsNaN.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Log1p.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/LogicalNot.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Max.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/MaxPool.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/MaxPoolBackprop.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/MaxPoolWithArgmax_impl.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/MaxPoolWithArgmax.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/NonMaxSuppressionV4.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/NonMaxSuppressionV5.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/NotEqual.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/PadV2.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Reciprocal.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/RotateWithOffset.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Round.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Selu.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Sigmoid.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Sign.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Sin.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Sinh.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Softplus.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Transpose.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/SpaceToBatchND.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Sqrt.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Square.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/SquaredDifference.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Step.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Tan.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Tanh.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/kernels/Unique.ts", "node_modules/@tensorflow/tfjs-backend-cpu/dist/../src/register_all_kernels.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/canvas_util.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/tex_util.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/webgl_util.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/flags_webgl.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Abs.js", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../node_modules/@tensorflow/tfjs-backend-cpu/dist/utils/binary_impl.js", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Add.js", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../node_modules/@tensorflow/tfjs-backend-cpu/dist/utils/unary_impl.js", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Ceil.js", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Exp.js", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Expm1.js", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Floor.js", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Log.js", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Max_impl.js", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Multiply.js", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Rsqrt.js", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Slice.js", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Sub.js", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Transpose_impl.js", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Unique_impl.js", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/kernel_utils/shared.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/addn_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/addn_packed_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/argminmax_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/packing_util.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/glsl_version.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/shader_compiler_util.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/shader_compiler.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/argminmax_packed_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/avg_pool_backprop_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/binaryop_complex_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/binaryop_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/binaryop_packed_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/clip_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/clip_packed_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/complex_abs_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/concat_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/concat_packed_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/conv_backprop_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/conv_backprop_gpu_depthwise.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/conv_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/conv_gpu_depthwise.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/conv_packed_gpu_depthwise.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/crop_and_resize_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/cumsum_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/decode_matrix_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/decode_matrix_packed_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/depth_to_space_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/diag_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/encode_float_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/encode_float_packed_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/encode_matrix_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/encode_matrix_packed_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/fft_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/fill_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/gather_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/gather_nd_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/gpgpu_util.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/gpgpu_context.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/gpgpu_math.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/im2col_packed_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/lrn_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/lrn_grad_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/lrn_packed_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/max_pool_backprop_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/mulmat_packed_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/multinomial_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/onehot_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/pack_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/pad_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/pad_packed_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/pool_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/reduce_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/reshape_packed_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/resize_bilinear_backprop_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/resize_bilinear_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/resize_bilinear_packed_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/resize_nearest_neighbor_backprop_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/resize_nearest_neighbor_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/reverse_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/reverse_packed_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/scatter_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/segment_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/select_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/slice_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/slice_packed_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/strided_slice_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/texture_manager.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/tile_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/unaryop_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/unaryop_packed_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/unpack_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/backend_webgl.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/version.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/webgl.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/base.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/kernel_utils/kernel_funcs_utils.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/kernels/Atan2.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/kernels/Identity.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/kernels/AvgPool.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/kernels/AvgPoolBackprop.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/batchnorm_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/batchnorm_packed_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/kernels/BatchNorm.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/kernels/Cos.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/kernels/Div.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/flip_left_right_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/kernels/FlipLeftRight.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/kernels/FromPixels_utils/from_pixels_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/kernels/FromPixels_utils/from_pixels_packed_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/kernels/FromPixels.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/kernel_utils/reduce.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/kernel_utils/reshape.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/kernels/Reshape.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/kernels/Max_impl.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/transpose_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/transpose_packed_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/kernels/Transpose_impl.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/kernels/Max.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/kernels/MaxPool.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/kernels/MaxPoolBackprop.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/kernels/MaxPoolWithArgmax_impl.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/kernels/MaxPoolWithArgmax.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/kernels/NonMaxSuppressionV3.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/kernels/NonMaxSuppressionV4.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/kernels/NonMaxSuppressionV5.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/rotate_gpu.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/kernels/RotateWithOffset.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/kernels/Sin.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/kernels/Square.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/kernels/SquaredDifference.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/kernels/Tan.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/kernels/Transpose.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/kernels/Unique.ts", "node_modules/@tensorflow/tfjs-backend-webgl/dist/../src/register_all_kernels.ts", "node_modules/@tensorflow/tfjs/dist/../src/version.ts", "node_modules/@tensorflow/tfjs/dist/../src/index.ts", "src/blazeface/box.js", "src/blazeface/face.js", "src/blazeface/index.js", "src/facemesh/keypoints.js", "src/facemesh/box.js", "src/facemesh/util.js", "src/facemesh/pipeline.js", "src/facemesh/uvcoords.js", "src/facemesh/triangulation.js", "src/facemesh/index.js", "src/ssrnet/index.js", "src/posenet/modelBase.js", "src/posenet/modelMobileNet.js", "src/posenet/heapSort.js", "src/posenet/buildParts.js", "src/posenet/keypoints.js", "src/posenet/vectors.js", "src/posenet/decodePose.js", "src/posenet/decodeMultiple.js", "src/posenet/decoders.js", "src/posenet/decodeSingle.js", "src/posenet/util.js", "src/posenet/modelPoseNet.js", "src/posenet/index.js", "src/handpose/box.js", "src/handpose/hand.js", "src/handpose/keypoints.js", "src/handpose/util.js", "src/handpose/pipeline.js", "src/handpose/index.js", "src/config.js", "src/index.js"], - "sourcesContent": ["", "", "", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Conv2DInfo, Conv3DInfo} from '../ops/conv_util';\nimport {FusedBatchMatMulConfig, FusedConv2DConfig} from '../ops/fused_types';\nimport {Backend, DataId, Scalar, Tensor, Tensor1D, Tensor2D, Tensor3D, Tensor4D, Tensor5D} from '../tensor';\nimport {BackendValues, DataType, Rank, ShapeMap} from '../types';\n\nexport const EPSILON_FLOAT32 = 1e-7;\nexport const EPSILON_FLOAT16 = 1e-4;\n\n// Required information for all backends.\nexport interface BackendTimingInfo {\n kernelMs: number|{error: string};\n getExtraProfileInfo?(): string; // a field for additional timing information\n // e.g. packing / unpacking for WebGL backend\n}\n\nexport interface TensorStorage {\n read(dataId: DataId): Promise;\n readSync(dataId: DataId): BackendValues;\n disposeData(dataId: DataId): void;\n write(values: BackendValues, shape: number[], dtype: DataType): DataId;\n move(dataId: DataId, values: BackendValues, shape: number[], dtype: DataType):\n void;\n memory(): {unreliable: boolean;}; // Backend-specific information.\n /** Returns number of data ids currently in the storage. */\n numDataIds(): number;\n}\n\n/** Convenient class for storing tensor-related data. */\nexport class DataStorage {\n private data = new WeakMap();\n private dataIdsCount = 0;\n\n constructor(private backend: KernelBackend, private dataMover: DataMover) {}\n\n get(dataId: DataId) {\n if (!this.data.has(dataId)) {\n this.dataMover.moveData(this.backend, dataId);\n }\n return this.data.get(dataId);\n }\n\n set(dataId: DataId, value: T): void {\n this.dataIdsCount++;\n this.data.set(dataId, value);\n }\n\n has(dataId: DataId): boolean {\n return this.data.has(dataId);\n }\n\n delete(dataId: DataId): boolean {\n this.dataIdsCount--;\n return this.data.delete(dataId);\n }\n\n numDataIds(): number {\n return this.dataIdsCount;\n }\n}\n\nexport interface DataMover {\n /**\n * To be called by backends whenever they see a dataId that they don't own.\n * Upon calling this method, the mover will fetch the tensor from another\n * backend and register it with the current active backend.\n */\n moveData(backend: KernelBackend, dataId: DataId): void;\n}\n\nexport interface BackendTimer {\n time(f: () => void): Promise;\n}\n\n/**\n * The interface that defines the kernels that should be implemented when\n * adding a new backend. New backends don't need to implement every one of the\n * methods, this can be done gradually (throw an error for unimplemented\n * methods).\n */\nexport class KernelBackend implements TensorStorage, Backend, BackendTimer {\n time(f: () => void): Promise {\n return notYetImplemented('time');\n }\n read(dataId: object): Promise {\n return notYetImplemented('read');\n }\n readSync(dataId: object): BackendValues {\n return notYetImplemented('readSync');\n }\n numDataIds(): number {\n return notYetImplemented('numDataIds');\n }\n disposeData(dataId: object): void {\n return notYetImplemented('disposeData');\n }\n write(values: BackendValues, shape: number[], dtype: DataType): DataId {\n return notYetImplemented('write');\n }\n move(dataId: DataId, values: BackendValues, shape: number[], dtype: DataType):\n void {\n return notYetImplemented('move');\n }\n memory(): {unreliable: boolean; reasons?: string[]} {\n return notYetImplemented('memory');\n }\n /** Returns the highest precision for floats in bits (e.g. 16 or 32) */\n floatPrecision(): 16|32 {\n return notYetImplemented('floatPrecision');\n }\n /** Returns the smallest representable number. */\n epsilon(): number {\n return this.floatPrecision() === 32 ? EPSILON_FLOAT32 : EPSILON_FLOAT16;\n }\n\n batchMatMul(\n a: Tensor3D, b: Tensor3D, transposeA: boolean,\n transposeB: boolean): Tensor3D {\n return notYetImplemented('batchMatMul');\n }\n\n fusedBatchMatMul(\n {a, b, transposeA, transposeB, bias, activation, preluActivationWeights}:\n FusedBatchMatMulConfig): Tensor3D {\n return notYetImplemented('fusedBatchMatMul');\n }\n\n slice(x: T, begin: number[], size: number[]): T {\n return notYetImplemented('slice');\n }\n stridedSlice(\n x: T, begin: number[], end: number[], strides: number[]): T {\n return notYetImplemented('stridedSlice');\n }\n unstack(x: Tensor, axis: number): Tensor[] {\n return notYetImplemented('unstack');\n }\n reverse(a: T, axis: number[]): T {\n return notYetImplemented('reverse');\n }\n\n concat(tensors: Tensor[], axis: number): Tensor {\n return notYetImplemented('concat');\n }\n\n neg(a: T): T {\n return notYetImplemented('neg');\n }\n\n add(a: Tensor, b: Tensor): Tensor {\n return notYetImplemented('add');\n }\n addN(tensors: T[]): T {\n return notYetImplemented('addN');\n }\n subtract(a: Tensor, b: Tensor): Tensor {\n return notYetImplemented('subtract');\n }\n multiply(a: Tensor, b: Tensor): Tensor {\n return notYetImplemented('multiply');\n }\n realDivide(a: Tensor, b: Tensor): Tensor {\n return notYetImplemented('realDivide');\n }\n floorDiv(a: Tensor, b: Tensor): Tensor {\n return notYetImplemented('floorDiv');\n }\n\n sum(x: Tensor, axes: number[]): Tensor {\n return notYetImplemented('sum');\n }\n prod(x: Tensor, axes: number[]): Tensor {\n return notYetImplemented('prod');\n }\n\n unsortedSegmentSum(\n x: T, segmentIds: Tensor1D, numSegments: number): Tensor {\n return notYetImplemented('unsortedSegmentSum');\n }\n\n argMin(x: Tensor, axis: number): Tensor {\n return notYetImplemented('argMin');\n }\n argMax(x: Tensor, axis: number): Tensor {\n return notYetImplemented('argMax');\n }\n\n equal(a: Tensor, b: Tensor): Tensor {\n return notYetImplemented('equal');\n }\n notEqual(a: Tensor, b: Tensor): Tensor {\n return notYetImplemented('notEqual');\n }\n\n less(a: Tensor, b: Tensor): Tensor {\n return notYetImplemented('less');\n }\n lessEqual(a: Tensor, b: Tensor): Tensor {\n return notYetImplemented('lessEqual');\n }\n\n greater(a: Tensor, b: Tensor): Tensor {\n return notYetImplemented('greater');\n }\n greaterEqual(a: Tensor, b: Tensor): Tensor {\n return notYetImplemented('greaterEqual');\n }\n\n logicalNot(a: T): T {\n return notYetImplemented('logicalNot');\n }\n logicalAnd(a: Tensor, b: Tensor): Tensor {\n return notYetImplemented('logicalAnd');\n }\n logicalOr(a: Tensor, b: Tensor): Tensor {\n return notYetImplemented('logicalOr');\n }\n\n where(condition: Tensor): Tensor2D {\n return notYetImplemented('where');\n }\n select(condition: Tensor, a: Tensor, b: Tensor): Tensor {\n return notYetImplemented('select');\n }\n\n topk(x: T, k: number, sorted: boolean): [T, T] {\n return notYetImplemented('topk');\n }\n\n min(x: Tensor, axes: number[]): Tensor {\n return notYetImplemented('min');\n }\n minimum(a: Tensor, b: Tensor): Tensor {\n return notYetImplemented('minimum');\n }\n\n mod(a: Tensor, b: Tensor): Tensor {\n return notYetImplemented('mod');\n }\n\n max(x: Tensor, axes: number[]): Tensor {\n return notYetImplemented('max');\n }\n maximum(a: Tensor, b: Tensor): Tensor {\n return notYetImplemented('maximum');\n }\n\n all(x: Tensor, axes: number[]): Tensor {\n return notYetImplemented('all');\n }\n any(x: Tensor, axes: number[]): Tensor {\n return notYetImplemented('any');\n }\n\n squaredDifference(a: Tensor, b: Tensor): Tensor {\n return notYetImplemented('squaredDifference');\n }\n\n ceil(x: T): T {\n return notYetImplemented('ceil');\n }\n floor(x: T): T {\n return notYetImplemented('floor');\n }\n round(x: T): T {\n return notYetImplemented('round');\n }\n\n sign(x: T): T {\n return notYetImplemented('sign');\n }\n\n isNaN(x: T): T {\n return notYetImplemented('isNaN');\n }\n isInf(x: T): T {\n return notYetImplemented('isInf');\n }\n isFinite(x: T): T {\n return notYetImplemented('isFinite');\n }\n\n pow(a: T, b: Tensor): T {\n return notYetImplemented('pow');\n }\n exp(x: T): T {\n return notYetImplemented('exp');\n }\n expm1(x: T): T {\n return notYetImplemented('expm1');\n }\n softmax(x: T, dim: number): T {\n return notYetImplemented('softmax');\n }\n log(x: T): T {\n return notYetImplemented('log');\n }\n log1p(x: T): T {\n return notYetImplemented('log1p');\n }\n sqrt(x: T): T {\n return notYetImplemented('sqrt');\n }\n rsqrt(x: T): T {\n return notYetImplemented('rsqrt');\n }\n square(x: T): T {\n return notYetImplemented('square');\n }\n reciprocal(x: T): T {\n return notYetImplemented('reciprocal');\n }\n relu(x: T): T {\n return notYetImplemented('relu');\n }\n relu6(x: T): T {\n return notYetImplemented('relu6');\n }\n prelu(x: T, a: T): T {\n return notYetImplemented('prelu');\n }\n elu(x: T): T {\n return notYetImplemented('elu');\n }\n eluDer(dy: T, y: T): T {\n return notYetImplemented('eluDer');\n }\n selu(x: T): T {\n return notYetImplemented('selu');\n }\n int(x: T): T {\n return notYetImplemented('int');\n }\n\n clip(x: T, min: number, max: number): T {\n return notYetImplemented('clip');\n }\n\n abs(x: T): T {\n return notYetImplemented('abs');\n }\n complexAbs(x: T): T {\n return notYetImplemented('complexAbs');\n }\n\n sigmoid(x: T): T {\n return notYetImplemented('sigmoid');\n }\n\n softplus(x: T): T {\n return notYetImplemented('softplus');\n }\n\n sin(x: T): T {\n return notYetImplemented('sin');\n }\n cos(x: T): T {\n return notYetImplemented('cos');\n }\n tan(x: T): T {\n return notYetImplemented('tan');\n }\n\n asin(x: T): T {\n return notYetImplemented('asin');\n }\n acos(x: T): T {\n return notYetImplemented('acos');\n }\n atan(x: T): T {\n return notYetImplemented('atan');\n }\n atan2(a: T, b: T): T {\n return notYetImplemented('atan2');\n }\n\n sinh(x: T): T {\n return notYetImplemented('sinh');\n }\n cosh(x: T): T {\n return notYetImplemented('cosh');\n }\n tanh(x: T): T {\n return notYetImplemented('tanh');\n }\n\n asinh(x: T): T {\n return notYetImplemented('asinh');\n }\n acosh(x: T): T {\n return notYetImplemented('acosh');\n }\n atanh(x: T): T {\n return notYetImplemented('atanh');\n }\n\n erf(x: T): T {\n return notYetImplemented('erf');\n }\n\n step(x: T, alpha: number): T {\n return notYetImplemented('step');\n }\n\n fusedConv2d(\n {input, filter, convInfo, bias, activation, preluActivationWeights}:\n FusedConv2DConfig): Tensor4D {\n return notYetImplemented('fusedConv2d');\n }\n\n conv2d(x: Tensor4D, filter: Tensor4D, convInfo: Conv2DInfo): Tensor4D {\n return notYetImplemented('conv2d');\n }\n conv2dDerInput(dy: Tensor4D, filter: Tensor4D, convInfo: Conv2DInfo):\n Tensor4D {\n return notYetImplemented('conv2dDerInput');\n }\n conv2dDerFilter(x: Tensor4D, dY: Tensor4D, convInfo: Conv2DInfo): Tensor4D {\n return notYetImplemented('conv2dDerFilter');\n }\n\n fusedDepthwiseConv2D(\n {input, filter, convInfo, bias, activation, preluActivationWeights}:\n FusedConv2DConfig): Tensor4D {\n return notYetImplemented('fusedDepthwiseConv2D');\n }\n\n depthwiseConv2D(input: Tensor4D, filter: Tensor4D, convInfo: Conv2DInfo):\n Tensor4D {\n return notYetImplemented('depthwiseConv2D');\n }\n depthwiseConv2DDerInput(dy: Tensor4D, filter: Tensor4D, convInfo: Conv2DInfo):\n Tensor4D {\n return notYetImplemented('depthwiseConv2DDerInput');\n }\n depthwiseConv2DDerFilter(x: Tensor4D, dY: Tensor4D, convInfo: Conv2DInfo):\n Tensor4D {\n return notYetImplemented('depthwiseConv2DDerFilter');\n }\n conv3d(x: Tensor5D, filter: Tensor5D, convInfo: Conv3DInfo): Tensor5D {\n return notYetImplemented('conv3d');\n }\n conv3dDerInput(dy: Tensor5D, filter: Tensor5D, convInfo: Conv3DInfo):\n Tensor5D {\n return notYetImplemented('conv3dDerInput');\n }\n conv3dDerFilter(x: Tensor5D, dY: Tensor5D, convInfo: Conv3DInfo): Tensor5D {\n return notYetImplemented('conv3dDerFilter');\n }\n maxPool(x: Tensor4D, convInfo: Conv2DInfo): Tensor4D {\n return notYetImplemented('maxPool');\n }\n maxPoolBackprop(dy: Tensor4D, x: Tensor4D, y: Tensor4D, convInfo: Conv2DInfo):\n Tensor4D {\n return notYetImplemented('maxPoolBackprop');\n }\n avgPool(x: Tensor4D, convInfo: Conv2DInfo): Tensor4D {\n return notYetImplemented('avgPool');\n }\n avgPoolBackprop(dy: Tensor4D, x: Tensor4D, convInfo: Conv2DInfo): Tensor4D {\n return notYetImplemented('avgPoolBackprop');\n }\n avgPool3d(x: Tensor5D, convInfo: Conv3DInfo): Tensor5D {\n return notYetImplemented('avgPool3d');\n }\n avgPool3dBackprop(dy: Tensor5D, x: Tensor5D, convInfo: Conv3DInfo): Tensor5D {\n return notYetImplemented('avgPool3dBackprop');\n }\n maxPool3d(x: Tensor5D, convInfo: Conv3DInfo): Tensor5D {\n return notYetImplemented('maxPool3d');\n }\n maxPool3dBackprop(\n dy: Tensor5D, x: Tensor5D, y: Tensor5D, convInfo: Conv3DInfo): Tensor5D {\n return notYetImplemented('maxPool3dBackprop');\n }\n\n reshape(x: T, shape: ShapeMap[R]):\n Tensor {\n return notYetImplemented('reshape');\n }\n cast(x: T, dtype: DataType): T {\n return notYetImplemented('cast');\n }\n\n tile(x: T, reps: number[]): T {\n return notYetImplemented('tile');\n }\n\n pad(\n x: T, paddings: Array<[number, number]>, constantValue: number): T {\n return notYetImplemented('pad');\n }\n\n transpose(x: T, perm: number[]): T {\n return notYetImplemented('transpose');\n }\n\n gather(x: T, indices: Tensor1D, axis: number): T {\n return notYetImplemented('gather');\n }\n\n gatherND(x: Tensor, indices: Tensor): Tensor {\n return notYetImplemented('gatherND');\n }\n\n scatterND(\n indices: Tensor, updates: Tensor, shape: ShapeMap[R]): Tensor {\n return notYetImplemented('scatterND');\n }\n\n batchToSpaceND(\n x: T, blockShape: number[], crops: number[][]): T {\n return notYetImplemented('batchToSpaceND');\n }\n\n spaceToBatchND(\n x: T, blockShape: number[], paddings: number[][]): T {\n return notYetImplemented('spaceToBatchND');\n }\n\n resizeBilinear(\n x: Tensor4D, newHeight: number, newWidth: number,\n alignCorners: boolean): Tensor4D {\n return notYetImplemented('resizeBilinear');\n }\n\n resizeBilinearBackprop(dy: Tensor4D, x: Tensor4D, alignCorners: boolean):\n Tensor4D {\n return notYetImplemented('resizeBilinearBackprop');\n }\n\n resizeNearestNeighbor(\n x: Tensor4D, newHEight: number, newWidth: number,\n alignCorners: boolean): Tensor4D {\n return notYetImplemented('resizeNearestNeighbor');\n }\n\n resizeNearestNeighborBackprop(\n dy: Tensor4D, x: Tensor4D, alignCorners: boolean): Tensor4D {\n return notYetImplemented('resizeNearestNeighborBackprop');\n }\n\n batchNorm(\n x: Tensor4D, mean: Tensor4D|Tensor1D, variance: Tensor4D|Tensor1D,\n offset?: Tensor4D|Tensor1D, scale?: Tensor4D|Tensor1D,\n varianceEpsilon?: number): Tensor4D {\n return notYetImplemented('batchNorm');\n }\n\n localResponseNormalization4D(\n x: Tensor4D, radius: number, bias: number, alpha: number,\n beta: number): Tensor4D {\n return notYetImplemented('localResponseNormalization4D');\n }\n\n LRNGrad(\n dy: Tensor4D, inputImage: Tensor4D, outputImage: Tensor4D, radius: number,\n bias: number, alpha: number, beta: number): Tensor4D {\n return notYetImplemented('LRNGrad');\n }\n\n multinomial(\n logits: Tensor2D, normalized: boolean, numSamples: number,\n seed: number): Tensor2D {\n return notYetImplemented('multinomial');\n }\n\n oneHot(indices: Tensor1D, depth: number, onValue: number, offValue: number):\n Tensor2D {\n return notYetImplemented('oneHot');\n }\n\n cumsum(x: Tensor, axis: number, exclusive: boolean, reverse: boolean):\n Tensor {\n return notYetImplemented('cumsum');\n }\n\n nonMaxSuppression(\n boxes: Tensor2D, scores: Tensor1D, maxOutputSize: number,\n iouThreshold: number, scoreThreshold?: number): Tensor1D {\n return notYetImplemented('nonMaxSuppression');\n }\n\n fft(x: Tensor2D): Tensor2D {\n return notYetImplemented('fft');\n }\n ifft(x: Tensor2D): Tensor2D {\n return notYetImplemented('ifft');\n }\n complex(real: T, imag: T): T {\n return notYetImplemented('complex');\n }\n real(input: T): T {\n return notYetImplemented('real');\n }\n imag(input: T): T {\n return notYetImplemented('imag');\n }\n\n cropAndResize(\n image: Tensor4D, boxes: Tensor2D, boxIndex: Tensor1D,\n cropSize: [number, number], method: 'bilinear'|'nearest',\n extrapolationValue: number): Tensor4D {\n return notYetImplemented('cropAndResize');\n }\n\n depthToSpace(x: Tensor4D, blockSize: number, dataFormat: string): Tensor4D {\n return notYetImplemented('depthToSpace');\n }\n\n // Aligns with the \"SplitV\" kernel in TensorFlow.\n split(value: T, sizeSplits: number[], axis: number): T[] {\n return notYetImplemented('split');\n }\n\n sparseToDense(\n sparseIndices: Tensor, sparseValues: Tensor, outputShape: ShapeMap[R],\n defaultValue: Scalar): Tensor {\n return notYetImplemented('sparseToDense');\n }\n\n diag(x: Tensor): Tensor {\n return notYetImplemented('diag');\n }\n\n fill(\n shape: ShapeMap[R], value: number|string, dtype?: DataType): Tensor {\n return notYetImplemented('fill');\n }\n\n onesLike(x: Tensor): Tensor {\n return notYetImplemented('onesLike');\n }\n\n zerosLike(x: Tensor): Tensor {\n return notYetImplemented('zerosLike');\n }\n\n linspace(start: number, stop: number, num: number): Tensor1D {\n return notYetImplemented('linspace');\n }\n\n dispose(): void {\n return notYetImplemented('dispose');\n }\n}\n\nfunction notYetImplemented(kernelName: string): never {\n throw new Error(\n `'${kernelName}' not yet implemented or not found in the registry. ` +\n `This kernel may not be supported by the tfjs backend you have chosen`);\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Platform} from './platforms/platform';\n\n// Expects flags from URL in the format ?tfjsflags=FLAG1:1,FLAG2:true.\nconst TENSORFLOWJS_FLAGS_PREFIX = 'tfjsflags';\n\ntype FlagValue = number|boolean;\ntype FlagEvaluationFn = (() => FlagValue)|(() => Promise);\nexport type Flags = {\n [featureName: string]: FlagValue\n};\nexport type FlagRegistryEntry = {\n evaluationFn: FlagEvaluationFn;\n setHook?: (value: FlagValue) => void;\n};\n\n/**\n * The environment contains evaluated flags as well as the registered platform.\n * This is always used as a global singleton and can be retrieved with\n * `tf.env()`.\n *\n * @doc {heading: 'Environment'}\n */\nexport class Environment {\n private flags: Flags = {};\n private flagRegistry: {[flagName: string]: FlagRegistryEntry} = {};\n\n private urlFlags: Flags = {};\n\n platformName: string;\n platform: Platform;\n\n // tslint:disable-next-line: no-any\n constructor(public global: any) {\n this.populateURLFlags();\n }\n\n setPlatform(platformName: string, platform: Platform) {\n if (this.platform != null) {\n console.warn(\n `Platform ${this.platformName} has already been set. ` +\n `Overwriting the platform with ${platform}.`);\n }\n this.platformName = platformName;\n this.platform = platform;\n }\n\n registerFlag(\n flagName: string, evaluationFn: FlagEvaluationFn,\n setHook?: (value: FlagValue) => void) {\n this.flagRegistry[flagName] = {evaluationFn, setHook};\n\n // Override the flag value from the URL. This has to happen here because the\n // environment is initialized before flags get registered.\n if (this.urlFlags[flagName] != null) {\n const flagValue = this.urlFlags[flagName];\n console.warn(\n `Setting feature override from URL ${flagName}: ${flagValue}.`);\n this.set(flagName, flagValue);\n }\n }\n\n async getAsync(flagName: string): Promise {\n if (flagName in this.flags) {\n return this.flags[flagName];\n }\n\n this.flags[flagName] = await this.evaluateFlag(flagName);\n return this.flags[flagName];\n }\n\n get(flagName: string): FlagValue {\n if (flagName in this.flags) {\n return this.flags[flagName];\n }\n\n const flagValue = this.evaluateFlag(flagName);\n if (flagValue instanceof Promise) {\n throw new Error(\n `Flag ${flagName} cannot be synchronously evaluated. ` +\n `Please use getAsync() instead.`);\n }\n\n this.flags[flagName] = flagValue;\n\n return this.flags[flagName];\n }\n\n getNumber(flagName: string): number {\n return this.get(flagName) as number;\n }\n\n getBool(flagName: string): boolean {\n return this.get(flagName) as boolean;\n }\n\n getFlags(): Flags {\n return this.flags;\n }\n // For backwards compatibility.\n get features(): Flags {\n return this.flags;\n }\n\n set(flagName: string, value: FlagValue): void {\n if (this.flagRegistry[flagName] == null) {\n throw new Error(\n `Cannot set flag ${flagName} as it has not been registered.`);\n }\n this.flags[flagName] = value;\n if (this.flagRegistry[flagName].setHook != null) {\n this.flagRegistry[flagName].setHook(value);\n }\n }\n\n private evaluateFlag(flagName: string): FlagValue|Promise {\n if (this.flagRegistry[flagName] == null) {\n throw new Error(\n `Cannot evaluate flag '${flagName}': no evaluation function found.`);\n }\n return this.flagRegistry[flagName].evaluationFn();\n }\n\n setFlags(flags: Flags) {\n this.flags = Object.assign({}, flags);\n }\n\n reset() {\n this.flags = {};\n this.urlFlags = {};\n this.populateURLFlags();\n }\n\n private populateURLFlags(): void {\n if (typeof this.global === 'undefined' ||\n typeof this.global.location === 'undefined' ||\n typeof this.global.location.search === 'undefined') {\n return;\n }\n\n const urlParams = getQueryParams(this.global.location.search);\n if (TENSORFLOWJS_FLAGS_PREFIX in urlParams) {\n const keyValues = urlParams[TENSORFLOWJS_FLAGS_PREFIX].split(',');\n keyValues.forEach(keyValue => {\n const [key, value] = keyValue.split(':') as [string, string];\n this.urlFlags[key] = parseValue(key, value);\n });\n }\n }\n}\n\nexport function getQueryParams(queryString: string): {[key: string]: string} {\n const params = {};\n queryString.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g, (s, ...t) => {\n decodeParam(params, t[0], t[1]);\n return t.join('=');\n });\n return params;\n}\n\nfunction decodeParam(\n params: {[key: string]: string}, name: string, value?: string) {\n params[decodeURIComponent(name)] = decodeURIComponent(value || '');\n}\n\nfunction parseValue(flagName: string, value: string): FlagValue {\n value = value.toLowerCase();\n if (value === 'true' || value === 'false') {\n return value === 'true';\n } else if (`${+ value}` === value) {\n return +value;\n }\n throw new Error(\n `Could not parse value flag value ${value} for flag ${flagName}.`);\n}\n\n/**\n * Returns the current environment (a global singleton).\n *\n * The environment object contains the evaluated feature values as well as the\n * active platform.\n *\n * @doc {heading: 'Environment'}\n */\nexport function env() {\n return ENV;\n}\n\nexport let ENV: Environment = null;\nexport function setEnvironmentGlobal(environment: Environment) {\n ENV = environment;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Note that the identifier globalNameSpace is scoped to this module, but will\n// always resolve to the same global object regardless of how the module is\n// resolved.\n// tslint:disable-next-line:no-any\nlet globalNameSpace: {_tfGlobals: Map};\n// tslint:disable-next-line:no-any\nexport function getGlobalNamespace(): {_tfGlobals: Map} {\n if (globalNameSpace == null) {\n // tslint:disable-next-line:no-any\n let ns: any;\n if (typeof (window) !== 'undefined') {\n ns = window;\n } else if (typeof (global) !== 'undefined') {\n ns = global;\n } else if (typeof (process) !== 'undefined') {\n ns = process;\n } else if (typeof (self) !== 'undefined') {\n ns = self;\n } else {\n throw new Error('Could not find a global object');\n }\n globalNameSpace = ns;\n }\n return globalNameSpace;\n}\n\n// tslint:disable-next-line:no-any\nfunction getGlobalMap(): Map {\n const ns = getGlobalNamespace();\n if (ns._tfGlobals == null) {\n ns._tfGlobals = new Map();\n }\n return ns._tfGlobals;\n}\n\n/**\n * Returns a globally accessible 'singleton' object.\n *\n * @param key the name of the object\n * @param init a function to initialize to initialize this object\n * the first time it is fetched.\n */\nexport function getGlobal(key: string, init: () => T): T {\n const globalMap = getGlobalMap();\n if (globalMap.has(key)) {\n return globalMap.get(key);\n } else {\n const singleton = init();\n globalMap.set(key, singleton);\n return globalMap.get(key);\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n// Allow UpperCamelCase variable names\n// tslint:disable: variable-name\n// Unfortunately just enabling PascalCase per file (tslint:enable:\n// allow-pascal-case) doesn't work.\nimport {NamedTensorInfoMap, TensorInfo} from './kernel_registry';\nimport {ExplicitPadding} from './ops/conv_util';\nimport {Activation} from './ops/fused_types';\nimport {DataType, PixelData} from './types';\n\nexport const Abs = 'Abs';\nexport type AbsInputs = UnaryInputs;\n\nexport const Acos = 'Acos';\nexport type AcosInputs = UnaryInputs;\n\nexport const Acosh = 'Acosh';\nexport type AcoshInputs = UnaryInputs;\n\nexport const Add = 'Add';\nexport type AddInputs = BinaryInputs;\n\nexport const AddN = 'AddN';\nexport type AddNInputs = TensorInfo[];\n\nexport const All = 'All';\nexport type AllInputs = Pick;\nexport interface AllAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const Any = 'Any';\nexport type AnyInputs = Pick;\nexport interface AnyAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const ArgMax = 'ArgMax';\nexport type ArgMaxInputs = Pick;\nexport interface ArgMaxAttrs {\n axis: number;\n}\n\nexport const ArgMin = 'ArgMin';\nexport type ArgMinInputs = Pick;\nexport interface ArgMinAttrs {\n axis: number;\n}\n\nexport const Asin = 'Asin';\nexport type AsinInputs = UnaryInputs;\n\nexport const Asinh = 'Asinh';\nexport type AsinhInputs = UnaryInputs;\n\nexport const Atan = 'Atan';\nexport type AtanInputs = UnaryInputs;\n\nexport const Atanh = 'Atanh';\nexport type AtanhInputs = UnaryInputs;\n\nexport const Atan2 = 'Atan2';\nexport type Atan2Inputs = BinaryInputs;\n\nexport const AvgPool = 'AvgPool';\nexport type AvgPoolInputs = Pick;\nexport interface AvgPoolAttrs {\n filterSize: [number, number]|number;\n strides: [number, number]|number;\n pad: 'valid'|'same'|number;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const AvgPoolBackprop = 'AvgPoolBackprop';\nexport type AvgPoolBackpropInputs = Pick;\nexport interface AvgPoolBackpropAttrs {\n filterSize: [number, number]|number;\n strides: [number, number]|number;\n pad: 'valid'|'same'|number;\n}\n\nexport const AvgPool3D = 'AvgPool3D';\nexport type AvgPool3DInputs = Pick;\nexport interface AvgPool3DAttrs {\n filterSize: [number, number, number]|number;\n strides: [number, number, number]|number;\n pad: 'valid'|'same'|number;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n dataFormat: 'NDHWC'|'NCDHW';\n dilations?: [number, number, number]|number;\n}\n\nexport const AvgPool3DBackprop = 'AvgPool3DBackprop';\nexport type AvgPool3DBackpropInputs = Pick;\nexport interface AvgPool3DBackpropAttrs {\n filterSize: [number, number, number]|number;\n strides: [number, number, number]|number;\n pad: 'valid'|'same'|number;\n dilations: [number, number, number]|number;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const BatchMatMul = 'BatchMatMul';\nexport type BatchMatMulInputs = Pick;\nexport interface BatchMatMulAttrs {\n transposeA: boolean;\n transposeB: boolean;\n}\n\nexport const BatchToSpaceND = 'BatchToSpaceND';\nexport type BatchToSpaceNDInputs = Pick;\nexport interface BatchToSpaceNDAttrs {\n blockShape: number[];\n crops: number[][];\n}\n\nexport type BinaryInputs = Pick;\n\nexport const BroadcastTo = 'BroadcastTo';\nexport type BroadcastToInputs = Pick;\nexport interface BroadCastToAttrs {\n shape: number[];\n inputShape: number[]; // for gradient\n}\n\nexport const Cast = 'Cast';\nexport type CastInputs = UnaryInputs;\nexport interface CastAttrs {\n dtype: DataType;\n}\n\nexport const Ceil = 'Ceil';\nexport type CeilInputs = UnaryInputs;\n\nexport const ClipByValue = 'ClipByValue';\nexport type ClipByValueInputs = UnaryInputs;\nexport interface ClipByValueAttrs {\n clipValueMin: number;\n clipValueMax: number;\n}\n\nexport const Complex = 'Complex';\nexport type ComplexInputs = Pick;\n\nexport const Concat = 'Concat';\nexport type ConcatInputs = TensorInfo[];\nexport interface ConcatAttrs {\n axis: number;\n}\n\nexport const Conv2D = 'Conv2D';\nexport type Conv2DInputs = Pick;\nexport interface Conv2DAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dataFormat: 'NHWC'|'NCHW';\n dilations: [number, number]|number;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const Conv2DBackpropFilter = 'Conv2DBackpropFilter';\nexport type Conv2DBackpropFilterInputs = Pick;\nexport interface Conv2DBackpropFilterAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dataFormat: 'NHWC'|'NCHW';\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const Conv2DBackpropInput = 'Conv2DBackpropInput';\nexport type Conv2DBackpropInputInputs = Pick;\nexport interface Conv2DBackpropInputAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dataFormat: 'NHWC'|'NCHW';\n dimRoundingMode?: 'floor'|'round'|'ceil';\n inputShape: [number, number, number, number];\n}\n\nexport const Conv3D = 'Conv3D';\nexport type Conv3DInputs = Pick;\nexport interface Conv3DAttrs {\n strides: [number, number, number]|number;\n pad: 'valid'|'same';\n dataFormat: 'NDHWC'|'NCDHW';\n dilations: [number, number, number]|number;\n}\n\nexport const Conv3DBackpropFilterV2 = 'Conv3DBackpropFilterV2';\nexport type Conv3DBackpropFilterInputs = Pick;\n\nexport interface Conv3DBackpropFilterAttrs {\n strides: [number, number, number]|number;\n pad: 'valid'|'same';\n}\n\nexport const Conv3DBackpropInputV2 = 'Conv3DBackpropInputV2';\nexport type Conv3DBackpropInputInputs = Pick;\nexport interface Conv3DBackpropInputAttrs {\n pad: 'valid'|'same';\n}\n\nexport const Cos = 'Cos';\nexport type CosInputs = UnaryInputs;\n\nexport const Cosh = 'Cosh';\nexport type CoshInputs = UnaryInputs;\n\nexport const Cumsum = 'Cumsum';\nexport type CumsumInputs = Pick;\nexport interface CumsumAttrs {\n axis: number;\n exclusive: boolean;\n reverse: boolean;\n}\n\nexport const CropAndResize = 'CropAndResize';\nexport type CropAndResizeInputs =\n Pick;\nexport interface CropAndResizeAttrs {\n cropSize: [number, number];\n method: 'bilinear'|'nearest';\n extrapolationValue: number;\n}\n\nexport const DepthToSpace = 'DepthToSpace';\nexport type DepthToSpaceInputs = Pick;\nexport interface DepthToSpaceAttrs {\n blockSize: number;\n dataFormat: 'NHWC'|'NCHW';\n}\n\nexport const DepthwiseConv2dNative = 'DepthwiseConv2dNative';\nexport type DepthwiseConv2dNativeInputs =\n Pick;\nexport interface DepthwiseConv2dNativeAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number;\n dataFormat: 'NHWC'|'NCHW';\n dilations: [number, number]|number;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const DepthwiseConv2dNativeBackpropFilter =\n 'DepthwiseConv2dNativeBackpropFilter';\nexport type DepthwiseConv2dNativeBackpropFilterInputs =\n Pick;\n\nexport const DepthwiseConv2dNativeBackpropInput =\n 'DepthwiseConv2dNativeBackpropInput';\nexport type DepthwiseConv2dNativeBackpropInputInputs =\n Pick;\n\nexport const Diag = 'Diag';\nexport type DiagInputs = Pick;\n\nexport const Dilation2D = 'Dilation2D';\nexport type Dilation2DInputs = Pick;\nexport interface Dilation2DAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number;\n dilations: [number, number]|number;\n}\n\nexport const Dilation2DBackpropInput = 'Dilation2DBackpropInput';\nexport type Dilation2DBackpropInputInputs =\n Pick;\n\nexport const Dilation2DBackpropFilter = 'Dilation2DBackpropFilter';\nexport type Dilation2DBackpropFilterInputs =\n Pick;\n\nexport const Div = 'Div';\nexport type DivInputs = BinaryInputs;\n\nexport const Elu = 'Elu';\nexport type EluInputs = Pick;\n\nexport const EluGrad = 'EluGrad';\nexport type EluGradInputs = Pick;\n\nexport const Erf = 'Erf';\nexport type ErfInputs = UnaryInputs;\n\nexport const Equal = 'Equal';\nexport type EqualInputs = BinaryInputs;\n\nexport const Exp = 'Exp';\nexport type ExpInputs = UnaryInputs;\n\nexport const Expm1 = 'Expm1';\nexport type Expm1Inputs = UnaryInputs;\n\nexport const FFT = 'FFT';\nexport type FFTInputs = Pick;\n\nexport const Fill = 'Fill';\nexport interface FillAttrs {\n shape: number[];\n value: number|string;\n dtype: DataType;\n}\n\nexport const FlipLeftRight = 'FlipLeftRight';\nexport type FlipLeftRightInputs = Pick;\n\nexport const Floor = 'Floor';\nexport type FloorInputs = UnaryInputs;\n\nexport const FloorDiv = 'FloorDiv';\nexport type FloorDivInputs = BinaryInputs;\n\nexport const FusedBatchNorm = 'FusedBatchNorm';\nexport type FusedBatchNormInputs =\n Pick;\nexport interface FusedBatchNormAttrs {\n varianceEpsilon: number;\n}\n\nexport const GatherV2 = 'GatherV2';\nexport type GatherV2Inputs = Pick;\nexport interface GatherV2Attrs {\n axis: number;\n}\n\nexport const GatherNd = 'GatherNd';\nexport type GatherNdInputs = Pick;\n\nexport const Greater = 'Greater';\nexport type GreaterInputs = BinaryInputs;\n\nexport const GreaterEqual = 'GreaterEqual';\nexport type GreaterEqualInputs = BinaryInputs;\n\nexport const Identity = 'Identity';\nexport type IdentityInputs = Pick;\n\nexport const IFFT = 'IFFT';\nexport type IFFTInputs = Pick;\n\nexport const Imag = 'Imag';\nexport type ImagInputs = Pick;\n\nexport const IsFinite = 'IsFinite';\nexport type IsFiniteInputs = UnaryInputs;\n\nexport const IsInf = 'IsInf';\nexport type IsInfInputs = UnaryInputs;\n\nexport const IsNan = 'IsNan';\nexport type IsNanInputs = UnaryInputs;\n\nexport const Less = 'Less';\nexport type LessInputs = BinaryInputs;\n\nexport const LessEqual = 'LessEqual';\nexport type LessEqualInputs = BinaryInputs;\n\nexport const LinSpace = 'LinSpace';\nexport interface LinSpaceAttrs {\n start: number;\n stop: number;\n num: number;\n}\nexport const Log = 'Log';\nexport type LogInputs = UnaryInputs;\n\nexport const Log1p = 'Log1p';\nexport type Log1pInputs = UnaryInputs;\n\nexport const LogicalAnd = 'LogicalAnd';\nexport type LogicalAndInputs = BinaryInputs;\n\nexport const LogicalNot = 'LogicalNot';\nexport type LogicalNotInputs = Pick;\n\nexport const LogicalOr = 'LogicalOr';\nexport type LogicalOrInputs = BinaryInputs;\n\nexport const LogSoftmax = 'LogSoftmax';\nexport type LogSoftmaxInputs = Pick;\nexport interface LogSoftmaxAttrs {\n axis: number;\n}\n\nexport const LRN = 'LRN';\nexport type LRNInputs = Pick;\nexport interface LRNAttrs {\n depthRadius: number;\n bias: number;\n alpha: number;\n beta: number;\n}\n\nexport const LRNBackprop = 'LRNBackprop';\nexport type LRNBackpropInputs = Pick;\nexport interface LRNBackpropAttrs {\n depthRadius: number;\n bias: number;\n alpha: number;\n beta: number;\n}\n\nexport const Max = 'Max';\nexport type MaxInputs = Pick;\nexport interface MaxAttrs {\n reductionIndices: number|number[];\n keepDims: boolean;\n}\n\nexport const Maximum = 'Maximum';\nexport type MaximumInputs = BinaryInputs;\n\nexport const MaxPool = 'MaxPool';\nexport type MaxPoolInputs = Pick;\nexport interface MaxPoolAttrs {\n filterSize: [number, number]|number;\n strides: [number, number]|number;\n pad: 'valid'|'same'|number;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const MaxPoolBackprop = 'MaxPoolBackprop';\nexport type MaxPoolBackpropInputs =\n Pick;\nexport interface MaxPoolBackpropAttrs {\n filterSize: [number, number]|number;\n strides: [number, number]|number;\n pad: 'valid'|'same'|number;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const MaxPool3D = 'MaxPool3D';\nexport type MaxPool3DInputs = Pick;\nexport interface MaxPool3DAttrs {\n filterSize: [number, number, number]|number;\n strides: [number, number, number]|number;\n pad: 'valid'|'same'|number;\n dataFormat: 'NDHWC'|'NCDHW';\n dilations?: [number, number, number]|number;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const MaxPool3DBackprop = 'MaxPool3DBackprop';\nexport type MaxPool3DBackpropInputs =\n Pick;\nexport interface MaxPool3DBackpropAttrs {\n filterSize: [number, number, number]|number;\n strides: [number, number, number]|number;\n pad: 'valid'|'same'|number;\n dilations?: [number, number, number]|number;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const MaxPoolWithArgmax = 'MaxPoolWithArgmax';\nexport type MaxPoolWithArgmaxInputs = Pick;\nexport interface MaxPoolWithArgmaxAttrs {\n filterSize: [number, number]|number;\n strides: [number, number]|number;\n pad: 'valid'|'same'|number;\n includeBatchInIndex: boolean;\n}\n\nexport const Mean = 'Mean';\nexport type MeanInputs = Pick;\nexport interface MeanAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const Min = 'Min';\nexport type MinInputs = Pick;\nexport interface MinAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const Minimum = 'Minimum';\nexport type MinimumInputs = BinaryInputs;\n\nexport const Mod = 'Mod';\nexport type ModInputs = BinaryInputs;\n\nexport const Multiply = 'Multiply';\nexport type MultiplyInputs = BinaryInputs;\n\nexport const Negate = 'Negate';\nexport type NegateInputs = UnaryInputs;\n\nexport const NotEqual = 'NotEqual';\nexport type NotEqualInputs = BinaryInputs;\n\nexport const NonMaxSuppressionV3 = 'NonMaxSuppressionV3';\nexport type NonMaxSuppressionV3Inputs =\n Pick;\nexport interface NonMaxSuppressionV3Attrs {\n maxOutputSize: number;\n iouThreshold: number;\n scoreThreshold: number;\n}\n\nexport const NonMaxSuppressionV4 = 'NonMaxSuppressionV4';\nexport type NonMaxSuppressionV4Inputs =\n Pick;\nexport interface NonMaxSuppressionV4Attrs {\n maxOutputSize: number;\n iouThreshold: number;\n scoreThreshold: number;\n padToMaxOutputSize: boolean;\n}\n\nexport const NonMaxSuppressionV5 = 'NonMaxSuppressionV5';\nexport type NonMaxSuppressionV5Inputs =\n Pick;\nexport interface NonMaxSuppressionV5Attrs {\n maxOutputSize: number;\n iouThreshold: number;\n scoreThreshold: number;\n softNmsSigma: number;\n}\n\nexport const OnesLike = 'OnesLike';\nexport type OnesLikeInputs = UnaryInputs;\n\nexport const OneHot = 'OneHot';\nexport type OneHotInputs = Pick;\nexport interface OneHotAttrs {\n depth: number;\n onValue: number;\n offValue: number;\n}\n\nexport const PadV2 = 'PadV2';\nexport type PadV2Inputs = Pick;\nexport interface PadV2Attrs {\n paddings: Array<[number, number]>;\n constantValue: number;\n}\n\nexport const Pool = 'Pool';\nexport type PoolInputs = Pick;\n\nexport const Pow = 'Pow';\nexport type PowInputs = BinaryInputs;\n\nexport const Prelu = 'Prelu';\nexport type PreluInputs = Pick;\n\nexport const Prod = 'Prod';\nexport type ProdInputs = Pick;\nexport interface ProdAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const Range = 'Range';\nexport interface RangeAttrs {\n start: number;\n stop: number;\n step: number;\n dtype: 'float32'|'int32';\n}\n\nexport const Real = 'Real';\nexport type RealInputs = Pick;\n\nexport const Reciprocal = 'Reciprocal';\nexport type ReciprocalInputs = UnaryInputs;\n\nexport const Relu = 'Relu';\nexport type ReluInputs = Pick;\n\nexport const Reshape = 'Reshape';\nexport type ReshapeInputs = Pick;\nexport interface ReshapeAttrs {\n shape: number[];\n}\n\nexport const ResizeNearestNeighbor = 'ResizeNearestNeighbor';\nexport type ResizeNearestNeighborInputs = Pick;\nexport interface ResizeNearestNeighborAttrs {\n alignCorners: boolean;\n size: [number, number];\n}\n\nexport const ResizeNearestNeighborGrad = 'ResizeNearestNeighborGrad';\nexport type ResizeNearestNeighborGradInputs =\n Pick;\n\nexport const ResizeBilinear = 'ResizeBilinear';\nexport type ResizeBilinearInputs = Pick;\nexport interface ResizeBilinearAttrs {\n alignCorners: boolean;\n size: [number, number];\n}\n\nexport const ResizeBilinearGrad = 'ResizeBilinearGrad';\nexport type ResizeBilinearGradInputs = Pick;\n\nexport const Relu6 = 'Relu6';\nexport type Relu6Inputs = Pick;\n\nexport const Reverse = 'Reverse';\nexport type ReverseInputs = Pick;\nexport interface ReverseAttrs {\n dims: number|number[];\n}\n\nexport const Round = 'Round';\nexport type RoundInputs = UnaryInputs;\n\nexport const Rsqrt = 'Rsqrt';\nexport type RsqrtInputs = UnaryInputs;\n\nexport const ScatterNd = 'ScatterNd';\nexport type ScatterNdInputs = Pick;\nexport interface ScatterNdAttrs {\n shape: number[];\n}\n\nexport const SelectV2 = 'SelectV2';\nexport type SelectV2Inputs = Pick;\n\nexport const Selu = 'Selu';\nexport type SeluInputs = Pick;\n\nexport const Slice = 'Slice';\nexport type SliceInputs = Pick;\nexport interface SliceAttrs {\n begin: number|number[];\n size: number|number[];\n}\nexport const Sin = 'Sin';\nexport type SinInputs = UnaryInputs;\n\nexport const Sinh = 'Sinh';\nexport type SinhInputs = UnaryInputs;\n\nexport const Sign = 'Sign';\nexport type SignInputs = UnaryInputs;\n\nexport const Sigmoid = 'Sigmoid';\nexport type SigmoidInputs = UnaryInputs;\n\nexport const Softplus = 'Softplus';\nexport type SoftplusInputs = UnaryInputs;\n\nexport const Sqrt = 'Sqrt';\nexport type SqrtInputs = UnaryInputs;\n\nexport const Sum = 'Sum';\nexport type SumInputs = Pick;\nexport interface SumAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const SpaceToBatchND = 'SpaceToBatchND';\nexport type SpaceToBatchNDInputs = Pick;\nexport interface SpaceToBatchNDAttrs {\n blockShape: number[];\n paddings: number[][];\n}\n\nexport const SplitV = 'SplitV';\nexport type SplitVInputs = Pick;\nexport interface SplitVAttrs {\n numOrSizeSplits: number[]|number;\n axis: number;\n}\n\nexport const Softmax = 'Softmax';\nexport type SoftmaxInputs = Pick;\nexport interface SoftmaxAttrs {\n dim: number;\n}\n\nexport const SquaredDifference = 'SquaredDifference';\nexport type SquaredDifferenceInputs = BinaryInputs;\n\nexport const Square = 'Square';\nexport type SquareInputs = Pick;\n\nexport const Sub = 'Sub';\nexport type SubInputs = BinaryInputs;\n\nexport const SparseToDense = 'SparseToDense';\nexport type SparseToDenseInputs =\n Pick;\nexport interface SparseToDenseAttrs {\n outputShape: number[];\n}\n\nexport const StridedSlice = 'StridedSlice';\nexport type StridedSliceInputs = Pick;\nexport interface StridedSliceAttrs {\n begin: number[];\n end: number[];\n strides: number[];\n beginMask: number;\n endMask: number;\n ellipsisMask: number;\n newAxisMask: number;\n shrinkAxisMask: number;\n}\n\nexport const Tan = 'Tan';\nexport type TanInputs = UnaryInputs;\n\nexport const Tanh = 'Tanh';\nexport type TanhInputs = UnaryInputs;\n\nexport const Tile = 'Tile';\nexport type TileInputs = Pick;\nexport interface TileAttrs {\n reps: number[];\n}\n\nexport const TopK = 'TopK';\nexport type TopKInputs = Pick;\nexport interface TopKAttrs {\n k: number;\n sorted: boolean;\n}\n\nexport const Transpose = 'Transpose';\nexport type TransposeInputs = Pick;\nexport interface TransposeAttrs {\n perm: number[];\n}\n\nexport const Unique = 'Unique';\nexport type UniqueInputs = Pick;\nexport interface UniqueAttrs {\n axis: number;\n}\n\nexport type UnaryInputs = Pick;\n\nexport const Unpack = 'Unpack';\nexport type UnpackInputs = Pick;\nexport interface UnpackAttrs {\n axis: number;\n}\n\nexport const UnsortedSegmentSum = 'UnsortedSegmentSum';\nexport type UnsortedSegmentSumInputs =\n Pick;\nexport interface UnsortedSegmentSumAttrs {\n numSegments: number;\n}\n\nexport const ZerosLike = 'ZerosLike';\nexport type ZerosLikeInputs = UnaryInputs;\n\n/**\n * TensorFlow.js-only kernels\n */\nexport const Step = 'Step';\nexport type StepInputs = UnaryInputs;\nexport interface StepAttrs {\n alpha: number;\n}\n\nexport const FromPixels = 'FromPixels';\nexport interface FromPixelsInputs {\n pixels: PixelData|ImageData|HTMLImageElement|HTMLCanvasElement|\n HTMLVideoElement;\n}\nexport interface FromPixelsAttrs {\n numChannels: number;\n}\n\nexport const RotateWithOffset = 'RotateWithOffset';\nexport type RotateWithOffsetInputs = Pick;\nexport interface RotateWithOffsetAttrs {\n radians: number;\n fillValue: number|[number, number, number];\n center: number|[number, number];\n}\n\nexport const _FusedMatMul = '_FusedMatMul';\n// tslint:disable-next-line: class-name\nexport interface _FusedMatMulInputs extends NamedTensorInfoMap {\n a: TensorInfo;\n b: TensorInfo;\n bias?: TensorInfo;\n preluActivationWeights?: TensorInfo;\n}\n// tslint:disable-next-line: class-name\nexport interface _FusedMatMulAttrs {\n transposeA: boolean;\n transposeB: boolean;\n activation: Activation;\n}\n\nexport const FusedConv2D = 'FusedConv2D';\nexport interface FusedConv2DInputs extends NamedTensorInfoMap {\n x: TensorInfo;\n filter: TensorInfo;\n bias?: TensorInfo;\n preluActivationWeights?: TensorInfo;\n}\nexport interface FusedConv2DAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dataFormat: 'NHWC'|'NCHW';\n dilations: [number, number]|number;\n dimRoundingMode: 'floor'|'round'|'ceil';\n activation: Activation;\n}\n\nexport const FusedDepthwiseConv2D = 'FusedDepthwiseConv2D';\nexport interface FusedDepthwiseConv2DInputs extends NamedTensorInfoMap {\n x: TensorInfo;\n filter: TensorInfo;\n bias?: TensorInfo;\n preluActivationWeights?: TensorInfo;\n}\nexport interface FusedDepthwiseConv2DAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number;\n dataFormat: 'NHWC'|'NCHW';\n dilations: [number, number]|number;\n dimRoundingMode: 'floor'|'round'|'ceil';\n activation: Activation;\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {env} from './environment';\n\nimport {getGlobal} from './global_util';\nimport {NamedGradientMap} from './tape';\nimport {Tensor} from './tensor';\nimport {DataType, RecursiveArray} from './types';\n\nconst kernelRegistry =\n getGlobal('kernelRegistry', () => new Map());\nconst gradRegistry =\n getGlobal('gradRegistry', () => new Map());\n\nexport type DataId = object;\n\ntype AttributeValue =\n number|number[]|boolean|boolean[]|string|string[]|NamedAttrMap;\n\n/** These are extra non-tensor/primitive params passed to kernel functions. */\nexport type Attribute = AttributeValue|RecursiveArray;\n\n/** Specifies the code to run when executing a kernel. */\nexport type KernelFunc = (params: {\n inputs: NamedTensorInfoMap,\n backend: {},\n attrs?: NamedAttrMap,\n}) => TensorInfo|TensorInfo[];\n\n/** The function to run when computing a gradient during backprop. */\nexport type GradFunc =\n (dy: Tensor|Tensor[], saved: Tensor[], attrs: NamedAttrMap) =>\n NamedGradientMap;\n\n/** Function that gets called after the backend initializes. */\nexport type KernelSetupFunc = (backend: {}) => void;\n/** Function that gets called right before the backend is disposed. */\nexport type KernelDisposeFunc = KernelSetupFunc;\n\n/** Config object for registering a kernel in the global registry. */\nexport interface KernelConfig {\n kernelName: string;\n backendName: string;\n kernelFunc: KernelFunc;\n setupFunc?: KernelSetupFunc;\n disposeFunc?: KernelDisposeFunc;\n}\n\n/** Config object for registering a gradient in the global registry. */\nexport interface GradConfig {\n kernelName: string;\n inputsToSave?: string[];\n // When saveAllInputs is true, all inputs will be saved. Only use this flag\n // if inputs is an array of Tensors.\n saveAllInputs?: boolean;\n outputsToSave?: boolean[];\n gradFunc: GradFunc;\n}\n\n/** Holds metadata for a given tensor. */\nexport interface TensorInfo {\n dataId: DataId;\n shape: number[];\n dtype: DataType;\n}\n\nexport interface NamedTensorInfoMap {\n [name: string]: TensorInfo;\n}\n\nexport interface NamedAttrMap {\n [name: string]: Attribute;\n}\n\n/**\n * Returns the kernel function (code) associated with the provided names.\n *\n * @param kernelName The official name of the kernel.\n * @param backendName The official name of the backend.\n */\nexport function getKernel(\n kernelName: string, backendName: string): KernelConfig {\n const key = makeKey(kernelName, backendName);\n return kernelRegistry.get(key);\n}\n\n/**\n * Returns the registered gradient info associated with the provided kernel.\n * @param kernelName The official TF kernel name.\n */\nexport function getGradient(kernelName: string): GradConfig {\n return gradRegistry.get(kernelName);\n}\n\nexport function getKernelsForBackend(backendName: string): KernelConfig[] {\n const it = kernelRegistry.entries();\n const result: KernelConfig[] = [];\n\n while (true) {\n const {done, value} = it.next();\n if (done) {\n break;\n }\n const [key, config] = value;\n const [backend, ] = key.split('_');\n if (backend === backendName) {\n result.push(config);\n }\n }\n return result;\n}\n\n/**\n * Registers the function (forward pass) for the kernel in a global registry.\n *\n * @param config A config object with the following properties:\n * - `kernelName` The official name of the kernel.\n * - `backendName` The official name of the backend.\n * - `kernelFunc` The function to run during the forward pass of the kernel.\n * - `setupFunc` Optional. Gets called once, after the backend initializes.\n * - `disposeFunc` Optional. Gets called once, right before the backend is\n * disposed.\n */\nexport function registerKernel(config: KernelConfig) {\n const {kernelName, backendName} = config;\n const key = makeKey(kernelName, backendName);\n if (kernelRegistry.has(key)) {\n console.warn(\n `The kernel '${kernelName}' for backend ` +\n `'${backendName}' is already registered`);\n }\n kernelRegistry.set(key, config);\n}\n\n/**\n * Registers a gradient function for a given kernel in the global registry,\n * to be used during the back-propagation of that kernel.\n *\n * @param config An object with the following properties:\n * - `kernelName` The name of the kernel that the gradient function is for.\n * - `gradFunc` The function to run during back-propagation.\n */\nexport function registerGradient(config: GradConfig) {\n const {kernelName} = config;\n\n if (gradRegistry.has(kernelName)) {\n // TODO (yassogba) after 3.0 assess whether we need to keep this gated\n // to debug mode.\n if (env().getBool('DEBUG')) {\n console.warn(`Overriding the gradient for '${kernelName}'`);\n }\n }\n gradRegistry.set(kernelName, config);\n}\n\n/**\n * Removes the kernel function from the registry.\n *\n * @param kernelName The official name of the kernel.\n * @param backendName The official name of the backend.\n *\n */\nexport function unregisterKernel(\n kernelName: string, backendName: string): void {\n const key = makeKey(kernelName, backendName);\n if (!kernelRegistry.has(key)) {\n throw new Error(\n `The kernel '${kernelName}' for backend ` +\n `'${backendName}' is not registered`);\n }\n kernelRegistry.delete(key);\n}\n\n/** Removes the registered gradient from the global registry. */\nexport function unregisterGradient(kernelName: string): void {\n if (!gradRegistry.has(kernelName)) {\n throw new Error(\n `The gradient '${kernelName}' for backend is not registered`);\n }\n gradRegistry.delete(kernelName);\n}\n\n/**\n * Finds kernels that have already been registered to a backend and re-registers\n * them for a new backend. Useful for registering custom backends.\n * @param registeredBackendName Already registered backend.\n * @param newBackendName New backend.\n */\nexport function copyRegisteredKernels(\n registeredBackendName: string, newBackendName: string): void {\n const kernels = getKernelsForBackend(registeredBackendName);\n kernels.forEach(kernelConfig => {\n const newKernelConfig =\n Object.assign({}, kernelConfig, {backendName: newBackendName});\n registerKernel(newKernelConfig);\n });\n}\n\nfunction makeKey(kernelName: string, backendName: string) {\n return `${backendName}_${kernelName}`;\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env} from './environment';\nimport {BackendValues, DataType, DataTypeMap, FlatVector, NumericDataType, RecursiveArray, TensorLike, TypedArray} from './types';\n\n/**\n * Shuffles the array in-place using Fisher-Yates algorithm.\n *\n * ```js\n * const a = [1, 2, 3, 4, 5];\n * tf.util.shuffle(a);\n * console.log(a);\n * ```\n *\n * @param array The array to shuffle in-place.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\n// tslint:disable-next-line:no-any\nexport function shuffle(array: any[]|Uint32Array|Int32Array|\n Float32Array): void {\n let counter = array.length;\n let temp = 0;\n let index = 0;\n // While there are elements in the array\n while (counter > 0) {\n // Pick a random index\n index = (Math.random() * counter) | 0;\n // Decrease counter by 1\n counter--;\n // And swap the last element with it\n temp = array[counter];\n array[counter] = array[index];\n array[index] = temp;\n }\n}\n\n/** Clamps a value to a specified range. */\nexport function clamp(min: number, x: number, max: number): number {\n return Math.max(min, Math.min(x, max));\n}\n\nexport function nearestLargerEven(val: number): number {\n return val % 2 === 0 ? val : val + 1;\n}\n\nexport function sum(arr: number[]): number {\n let sum = 0;\n for (let i = 0; i < arr.length; i++) {\n sum += arr[i];\n }\n return sum;\n}\n\n/**\n * Returns a sample from a uniform [a, b) distribution.\n *\n * @param a The minimum support (inclusive).\n * @param b The maximum support (exclusive).\n * @return A pseudorandom number on the half-open interval [a,b).\n */\nexport function randUniform(a: number, b: number) {\n const r = Math.random();\n return (b * r) + (1 - r) * a;\n}\n\n/** Returns the squared Euclidean distance between two vectors. */\nexport function distSquared(a: FlatVector, b: FlatVector): number {\n let result = 0;\n for (let i = 0; i < a.length; i++) {\n const diff = Number(a[i]) - Number(b[i]);\n result += diff * diff;\n }\n return result;\n}\n\n/**\n * Asserts that the expression is true. Otherwise throws an error with the\n * provided message.\n *\n * ```js\n * const x = 2;\n * tf.util.assert(x === 2, 'x is not 2');\n * ```\n *\n * @param expr The expression to assert (as a boolean).\n * @param msg A function that returns the message to report when throwing an\n * error. We use a function for performance reasons.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function assert(expr: boolean, msg: () => string) {\n if (!expr) {\n throw new Error(typeof msg === 'string' ? msg : msg());\n }\n}\n\nexport function assertShapesMatch(\n shapeA: number[], shapeB: number[], errorMessagePrefix = ''): void {\n assert(\n arraysEqual(shapeA, shapeB),\n () => errorMessagePrefix + ` Shapes ${shapeA} and ${shapeB} must match`);\n}\n\nexport function assertNonNull(a: TensorLike): void {\n assert(\n a != null,\n () => `The input to the tensor constructor must be a non-null value.`);\n}\n\n// NOTE: We explicitly type out what T extends instead of any so that\n// util.flatten on a nested array of number doesn't try to infer T as a\n// number[][], causing us to explicitly type util.flatten().\n/**\n * Flattens an arbitrarily nested array.\n *\n * ```js\n * const a = [[1, 2], [3, 4], [5, [6, [7]]]];\n * const flat = tf.util.flatten(a);\n * console.log(flat);\n * ```\n *\n * @param arr The nested array to flatten.\n * @param result The destination array which holds the elements.\n * @param skipTypedArray If true, avoids flattening the typed arrays. Defaults\n * to false.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function\nflatten|TypedArray>(\n arr: T|RecursiveArray, result: T[] = [], skipTypedArray = false): T[] {\n if (result == null) {\n result = [];\n }\n if (Array.isArray(arr) || isTypedArray(arr) && !skipTypedArray) {\n for (let i = 0; i < arr.length; ++i) {\n flatten(arr[i], result, skipTypedArray);\n }\n } else {\n result.push(arr as T);\n }\n return result;\n}\n\n/**\n * Returns the size (number of elements) of the tensor given its shape.\n *\n * ```js\n * const shape = [3, 4, 2];\n * const size = tf.util.sizeFromShape(shape);\n * console.log(size);\n * ```\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function sizeFromShape(shape: number[]): number {\n if (shape.length === 0) {\n // Scalar.\n return 1;\n }\n let size = shape[0];\n for (let i = 1; i < shape.length; i++) {\n size *= shape[i];\n }\n return size;\n}\n\nexport function isScalarShape(shape: number[]): boolean {\n return shape.length === 0;\n}\n\nexport function arraysEqual(n1: FlatVector, n2: FlatVector) {\n if (n1 === n2) {\n return true;\n }\n if (n1 == null || n2 == null) {\n return false;\n }\n\n if (n1.length !== n2.length) {\n return false;\n }\n for (let i = 0; i < n1.length; i++) {\n if (n1[i] !== n2[i]) {\n return false;\n }\n }\n return true;\n}\n\nexport function isInt(a: number): boolean {\n return a % 1 === 0;\n}\n\nexport function tanh(x: number): number {\n // tslint:disable-next-line:no-any\n if ((Math as any).tanh != null) {\n // tslint:disable-next-line:no-any\n return (Math as any).tanh(x);\n }\n if (x === Infinity) {\n return 1;\n } else if (x === -Infinity) {\n return -1;\n } else {\n const e2x = Math.exp(2 * x);\n return (e2x - 1) / (e2x + 1);\n }\n}\n\nexport function sizeToSquarishShape(size: number): [number, number] {\n const width = Math.ceil(Math.sqrt(size));\n return [width, Math.ceil(size / width)];\n}\n\n/**\n * Creates a new array with randomized indicies to a given quantity.\n *\n * ```js\n * const randomTen = tf.util.createShuffledIndices(10);\n * console.log(randomTen);\n * ```\n *\n * @param number Quantity of how many shuffled indicies to create.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function createShuffledIndices(n: number): Uint32Array {\n const shuffledIndices = new Uint32Array(n);\n for (let i = 0; i < n; ++i) {\n shuffledIndices[i] = i;\n }\n shuffle(shuffledIndices);\n return shuffledIndices;\n}\n\nexport function rightPad(a: string, size: number): string {\n if (size <= a.length) {\n return a;\n }\n return a + ' '.repeat(size - a.length);\n}\n\nexport function repeatedTry(\n checkFn: () => boolean, delayFn = (counter: number) => 0,\n maxCounter?: number): Promise {\n return new Promise((resolve, reject) => {\n let tryCount = 0;\n\n const tryFn = () => {\n if (checkFn()) {\n resolve();\n return;\n }\n\n tryCount++;\n\n const nextBackoff = delayFn(tryCount);\n\n if (maxCounter != null && tryCount >= maxCounter) {\n reject();\n return;\n }\n setTimeout(tryFn, nextBackoff);\n };\n\n tryFn();\n });\n}\n\n/**\n * Given the full size of the array and a shape that may contain -1 as the\n * implicit dimension, returns the inferred shape where -1 is replaced.\n * E.g. For shape=[2, -1, 3] and size=24, it will return [2, 4, 3].\n *\n * @param shape The shape, which may contain -1 in some dimension.\n * @param size The full size (number of elements) of the array.\n * @return The inferred shape where -1 is replaced with the inferred size.\n */\nexport function inferFromImplicitShape(\n shape: number[], size: number): number[] {\n let shapeProd = 1;\n let implicitIdx = -1;\n\n for (let i = 0; i < shape.length; ++i) {\n if (shape[i] >= 0) {\n shapeProd *= shape[i];\n } else if (shape[i] === -1) {\n if (implicitIdx !== -1) {\n throw Error(\n `Shapes can only have 1 implicit size. ` +\n `Found -1 at dim ${implicitIdx} and dim ${i}`);\n }\n implicitIdx = i;\n } else if (shape[i] < 0) {\n throw Error(`Shapes can not be < 0. Found ${shape[i]} at dim ${i}`);\n }\n }\n\n if (implicitIdx === -1) {\n if (size > 0 && size !== shapeProd) {\n throw Error(`Size(${size}) must match the product of shape ${shape}`);\n }\n return shape;\n }\n\n if (shapeProd === 0) {\n throw Error(\n `Cannot infer the missing size in [${shape}] when ` +\n `there are 0 elements`);\n }\n if (size % shapeProd !== 0) {\n throw Error(\n `The implicit shape can't be a fractional number. ` +\n `Got ${size} / ${shapeProd}`);\n }\n\n const newShape = shape.slice();\n newShape[implicitIdx] = size / shapeProd;\n return newShape;\n}\n\nexport function parseAxisParam(\n axis: number|number[], shape: number[]): number[] {\n const rank = shape.length;\n\n // Normalize input\n axis = axis == null ? shape.map((s, i) => i) : [].concat(axis);\n\n // Check for valid range\n assert(\n axis.every(ax => ax >= -rank && ax < rank),\n () =>\n `All values in axis param must be in range [-${rank}, ${rank}) but ` +\n `got axis ${axis}`);\n\n // Check for only integers\n assert(\n axis.every(ax => isInt(ax)),\n () => `All values in axis param must be integers but ` +\n `got axis ${axis}`);\n\n // Handle negative axis.\n return axis.map(a => a < 0 ? rank + a : a);\n}\n\n/** Reduces the shape by removing all dimensions of shape 1. */\nexport function squeezeShape(shape: number[], axis?: number[]):\n {newShape: number[], keptDims: number[]} {\n const newShape: number[] = [];\n const keptDims: number[] = [];\n const isEmptyArray = axis != null && Array.isArray(axis) && axis.length === 0;\n const axes = (axis == null || isEmptyArray) ?\n null :\n parseAxisParam(axis, shape).sort();\n let j = 0;\n for (let i = 0; i < shape.length; ++i) {\n if (axes != null) {\n if (axes[j] === i && shape[i] !== 1) {\n throw new Error(\n `Can't squeeze axis ${i} since its dim '${shape[i]}' is not 1`);\n }\n if ((axes[j] == null || axes[j] > i) && shape[i] === 1) {\n newShape.push(shape[i]);\n keptDims.push(i);\n }\n if (axes[j] <= i) {\n j++;\n }\n }\n if (shape[i] !== 1) {\n newShape.push(shape[i]);\n keptDims.push(i);\n }\n }\n return {newShape, keptDims};\n}\n\nexport function getTypedArrayFromDType(\n dtype: D, size: number): DataTypeMap[D] {\n let values = null;\n if (dtype == null || dtype === 'float32') {\n values = new Float32Array(size);\n } else if (dtype === 'int32') {\n values = new Int32Array(size);\n } else if (dtype === 'bool') {\n values = new Uint8Array(size);\n } else {\n throw new Error(`Unknown data type ${dtype}`);\n }\n return values as DataTypeMap[D];\n}\n\nexport function getArrayFromDType(\n dtype: D, size: number): DataTypeMap[D] {\n let values = null;\n if (dtype == null || dtype === 'float32') {\n values = new Float32Array(size);\n } else if (dtype === 'int32') {\n values = new Int32Array(size);\n } else if (dtype === 'bool') {\n values = new Uint8Array(size);\n } else if (dtype === 'string') {\n values = new Array<'string'>(size);\n } else {\n throw new Error(`Unknown data type ${dtype}`);\n }\n return values as DataTypeMap[D];\n}\n\nexport function checkConversionForErrors(\n vals: DataTypeMap[D]|number[], dtype: D): void {\n for (let i = 0; i < vals.length; i++) {\n const num = vals[i] as number;\n if (isNaN(num) || !isFinite(num)) {\n throw Error(`A tensor of type ${dtype} being uploaded contains ${num}.`);\n }\n }\n}\n\n/** Returns true if the dtype is valid. */\nexport function isValidDtype(dtype: DataType): boolean {\n return dtype === 'bool' || dtype === 'complex64' || dtype === 'float32' ||\n dtype === 'int32' || dtype === 'string';\n}\n\n/**\n * Returns true if the new type can't encode the old type without loss of\n * precision.\n */\nexport function hasEncodingLoss(oldType: DataType, newType: DataType): boolean {\n if (newType === 'complex64') {\n return false;\n }\n if (newType === 'float32' && oldType !== 'complex64') {\n return false;\n }\n if (newType === 'int32' && oldType !== 'float32' && oldType !== 'complex64') {\n return false;\n }\n if (newType === 'bool' && oldType === 'bool') {\n return false;\n }\n return true;\n}\n\nexport function isTypedArray(a: {}): a is Float32Array|Int32Array|Uint8Array {\n return a instanceof Float32Array || a instanceof Int32Array ||\n a instanceof Uint8Array;\n}\n\nexport function bytesPerElement(dtype: DataType): number {\n if (dtype === 'float32' || dtype === 'int32') {\n return 4;\n } else if (dtype === 'complex64') {\n return 8;\n } else if (dtype === 'bool') {\n return 1;\n } else {\n throw new Error(`Unknown dtype ${dtype}`);\n }\n}\n\n/**\n * Returns the approximate number of bytes allocated in the string array - 2\n * bytes per character. Computing the exact bytes for a native string in JS is\n * not possible since it depends on the encoding of the html page that serves\n * the website.\n */\nexport function bytesFromStringArray(arr: Uint8Array[]): number {\n if (arr == null) {\n return 0;\n }\n let bytes = 0;\n arr.forEach(x => bytes += x.length);\n return bytes;\n}\n\n/** Returns true if the value is a string. */\nexport function isString(value: {}): value is string {\n return typeof value === 'string' || value instanceof String;\n}\n\nexport function isBoolean(value: {}): boolean {\n return typeof value === 'boolean';\n}\n\nexport function isNumber(value: {}): boolean {\n return typeof value === 'number';\n}\n\nexport function inferDtype(values: TensorLike): DataType {\n if (Array.isArray(values)) {\n return inferDtype(values[0]);\n }\n if (values instanceof Float32Array) {\n return 'float32';\n } else if (values instanceof Int32Array || values instanceof Uint8Array) {\n return 'int32';\n } else if (isNumber(values)) {\n return 'float32';\n } else if (isString(values)) {\n return 'string';\n } else if (isBoolean(values)) {\n return 'bool';\n }\n return 'float32';\n}\n\nexport function isFunction(f: Function) {\n return !!(f && f.constructor && f.call && f.apply);\n}\n\nexport function nearestDivisor(size: number, start: number): number {\n for (let i = start; i < size; ++i) {\n if (size % i === 0) {\n return i;\n }\n }\n return size;\n}\n\nexport function computeStrides(shape: number[]): number[] {\n const rank = shape.length;\n if (rank < 2) {\n return [];\n }\n\n // Last dimension has implicit stride of 1, thus having D-1 (instead of D)\n // strides.\n const strides = new Array(rank - 1);\n strides[rank - 2] = shape[rank - 1];\n for (let i = rank - 3; i >= 0; --i) {\n strides[i] = strides[i + 1] * shape[i + 1];\n }\n return strides;\n}\n\n/**\n * Create typed array for scalar value. Used for storing in `DataStorage`.\n */\nexport function createScalarValue(\n value: DataType, dtype: DataType): BackendValues {\n if (dtype === 'string') {\n return encodeString(value);\n }\n\n return toTypedArray([value], dtype);\n}\n\nexport function toTypedArray(a: TensorLike, dtype: DataType): TypedArray {\n if (dtype === 'string') {\n throw new Error('Cannot convert a string[] to a TypedArray');\n }\n if (Array.isArray(a)) {\n a = flatten(a);\n }\n\n if (env().getBool('DEBUG')) {\n checkConversionForErrors(a as number[], dtype);\n }\n if (noConversionNeeded(a, dtype)) {\n return a as TypedArray;\n }\n if (dtype == null || dtype === 'float32' || dtype === 'complex64') {\n return new Float32Array(a as number[]);\n } else if (dtype === 'int32') {\n return new Int32Array(a as number[]);\n } else if (dtype === 'bool') {\n const bool = new Uint8Array((a as number[]).length);\n for (let i = 0; i < bool.length; ++i) {\n if (Math.round((a as number[])[i]) !== 0) {\n bool[i] = 1;\n }\n }\n return bool;\n } else {\n throw new Error(`Unknown data type ${dtype}`);\n }\n}\n\nfunction createNestedArray(offset: number, shape: number[], a: TypedArray) {\n const ret = new Array();\n if (shape.length === 1) {\n const d = shape[0];\n for (let i = 0; i < d; i++) {\n ret[i] = a[offset + i];\n }\n } else {\n const d = shape[0];\n const rest = shape.slice(1);\n const len = rest.reduce((acc, c) => acc * c);\n for (let i = 0; i < d; i++) {\n ret[i] = createNestedArray(offset + i * len, rest, a);\n }\n }\n return ret;\n}\n\n// Provide a nested array of TypedArray in given shape.\nexport function toNestedArray(shape: number[], a: TypedArray) {\n if (shape.length === 0) {\n // Scalar type should return a single number.\n return a[0];\n }\n const size = shape.reduce((acc, c) => acc * c);\n if (size === 0) {\n // A tensor with shape zero should be turned into empty list.\n return [];\n }\n if (size !== a.length) {\n throw new Error(`[${shape}] does not match the input size ${a.length}.`);\n }\n\n return createNestedArray(0, shape, a);\n}\n\nfunction noConversionNeeded(a: TensorLike, dtype: DataType): boolean {\n return (a instanceof Float32Array && dtype === 'float32') ||\n (a instanceof Int32Array && dtype === 'int32') ||\n (a instanceof Uint8Array && dtype === 'bool');\n}\n\nexport function makeOnesTypedArray(\n size: number, dtype: D): DataTypeMap[D] {\n const array = makeZerosTypedArray(size, dtype);\n for (let i = 0; i < array.length; i++) {\n array[i] = 1;\n }\n return array;\n}\n\nexport function makeZerosTypedArray(\n size: number, dtype: D): DataTypeMap[D] {\n if (dtype == null || dtype === 'float32' || dtype === 'complex64') {\n return new Float32Array(size) as DataTypeMap[D];\n } else if (dtype === 'int32') {\n return new Int32Array(size) as DataTypeMap[D];\n } else if (dtype === 'bool') {\n return new Uint8Array(size) as DataTypeMap[D];\n } else {\n throw new Error(`Unknown data type ${dtype}`);\n }\n}\n\n/**\n * Make nested `TypedArray` filled with zeros.\n * @param shape The shape information for the nested array.\n * @param dtype dtype of the array element.\n */\nexport function makeZerosNestedTypedArray(\n shape: number[], dtype: D) {\n const size = shape.reduce((prev, curr) => prev * curr, 1);\n if (dtype == null || dtype === 'float32') {\n return toNestedArray(shape, new Float32Array(size));\n } else if (dtype === 'int32') {\n return toNestedArray(shape, new Int32Array(size));\n } else if (dtype === 'bool') {\n return toNestedArray(shape, new Uint8Array(size));\n } else {\n throw new Error(`Unknown data type ${dtype}`);\n }\n}\n\n/**\n * Returns the current high-resolution time in milliseconds relative to an\n * arbitrary time in the past. It works across different platforms (node.js,\n * browsers).\n *\n * ```js\n * console.log(tf.util.now());\n * ```\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function now(): number {\n return env().platform.now();\n}\n\nexport function assertNonNegativeIntegerDimensions(shape: number[]) {\n shape.forEach(dimSize => {\n assert(\n Number.isInteger(dimSize) && dimSize >= 0,\n () =>\n `Tensor must have a shape comprised of positive integers but got ` +\n `shape [${shape}].`);\n });\n}\n\n/**\n * Returns a platform-specific implementation of\n * [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).\n *\n * If `fetch` is defined on the global object (`window`, `process`, etc.),\n * `tf.util.fetch` returns that function.\n *\n * If not, `tf.util.fetch` returns a platform-specific solution.\n *\n * ```js\n * const resource = await tf.util.fetch('https://unpkg.com/@tensorflow/tfjs');\n * // handle response\n * ```\n *\n * @doc {heading: 'Util'}\n */\nexport function fetch(\n path: string, requestInits?: RequestInit): Promise {\n return env().platform.fetch(path, requestInits);\n}\n\n/**\n * Encodes the provided string into bytes using the provided encoding scheme.\n *\n * @param s The string to encode.\n * @param encoding The encoding scheme. Defaults to utf-8.\n *\n * @doc {heading: 'Util'}\n */\nexport function encodeString(s: string, encoding = 'utf-8'): Uint8Array {\n encoding = encoding || 'utf-8';\n return env().platform.encode(s, encoding);\n}\n\n/**\n * Decodes the provided bytes into a string using the provided encoding scheme.\n * @param bytes The bytes to decode.\n *\n * @param encoding The encoding scheme. Defaults to utf-8.\n *\n * @doc {heading: 'Util'}\n */\nexport function decodeString(bytes: Uint8Array, encoding = 'utf-8'): string {\n encoding = encoding || 'utf-8';\n return env().platform.decode(bytes, encoding);\n}\n\n/**\n * Computes flat index for a given location (multidimentionsal index) in a\n * Tensor/multidimensional array.\n *\n * @param locs Location in the tensor.\n * @param rank Rank of the tensor.\n * @param strides Tensor strides.\n */\nexport function locToIndex(\n locs: number[], rank: number, strides: number[]): number {\n if (rank === 0) {\n return 0;\n } else if (rank === 1) {\n return locs[0];\n }\n let index = locs[locs.length - 1];\n for (let i = 0; i < locs.length - 1; ++i) {\n index += strides[i] * locs[i];\n }\n return index;\n}\n\n/**\n * Computes the location (multidimensional index) in a tensor/multidimentional\n * array for a given flat index.\n *\n * @param index Index in flat array.\n * @param rank Rank of tensor.\n * @param strides Strides of tensor.\n */\nexport function indexToLoc(\n index: number, rank: number, strides: number[]): number[] {\n if (rank === 0) {\n return [];\n } else if (rank === 1) {\n return [index];\n }\n const locs: number[] = new Array(rank);\n for (let i = 0; i < locs.length - 1; ++i) {\n locs[i] = Math.floor(index / strides[i]);\n index -= locs[i] * strides[i];\n }\n locs[locs.length - 1] = index;\n return locs;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {BackendTimer} from './backends/backend';\nimport {Tensor} from './tensor';\nimport {NamedTensorMap} from './tensor_types';\nimport {DataType, DataTypeMap, TypedArray} from './types';\nimport * as util from './util';\n\nexport type KernelProfile = {\n kernelName: string,\n outputs: Tensor[],\n inputs: NamedTensorMap,\n timeMs: Promise,\n extraInfo: Promise\n};\n\nexport class Profiler {\n constructor(private backendTimer: BackendTimer, private logger?: Logger) {\n if (logger == null) {\n this.logger = new Logger();\n }\n }\n\n profileKernel(kernelName: string, inputs: NamedTensorMap, f: () => Tensor[]):\n KernelProfile {\n let outputs: Tensor[];\n const holdResultWrapperFn = () => {\n outputs = f();\n };\n const timer = this.backendTimer.time(holdResultWrapperFn);\n\n for (let i = 0; i < outputs.length; i++) {\n const output = outputs[i];\n // Dangling promise here because we don't want to propagate up\n // asynchronicity.\n output.data().then(tensorVals => {\n checkComputationForErrors(tensorVals, output.dtype, kernelName);\n });\n }\n\n const kernelProfile = {\n kernelName,\n outputs,\n inputs,\n timeMs: timer.then(timing => timing.kernelMs),\n extraInfo: timer.then(\n timing => timing.getExtraProfileInfo != null ?\n timing.getExtraProfileInfo() :\n '')\n };\n return kernelProfile;\n }\n\n logKernelProfile(kernelProfile: KernelProfile): void {\n const {kernelName, outputs, timeMs, inputs, extraInfo} = kernelProfile;\n\n outputs.forEach(result => {\n Promise.all([result.data(), timeMs, extraInfo]).then(valueContainer => {\n this.logger.logKernelProfile(\n kernelName, result, valueContainer[0], valueContainer[1], inputs,\n valueContainer[2]);\n });\n });\n }\n}\n\nexport function checkComputationForErrors(\n vals: DataTypeMap[D], dtype: D, kernelName: string): boolean {\n if (dtype !== 'float32') {\n // Only floating point computations will generate NaN values\n return false;\n }\n for (let i = 0; i < vals.length; i++) {\n const num = vals[i] as number;\n if (isNaN(num) || !isFinite(num)) {\n // Throwing custom exception so behavior is testable.\n console.warn(`Found ${num} in the result of '${kernelName}'`);\n return true;\n }\n }\n return false;\n}\n\nexport class Logger {\n logKernelProfile(\n name: string, result: Tensor, vals: TypedArray,\n timeMs: number|{error: string}, inputs: NamedTensorMap,\n extraInfo?: string) {\n const time = typeof timeMs === 'number' ? util.rightPad(`${timeMs}ms`, 9) :\n timeMs['error'];\n const paddedName = util.rightPad(name, 25);\n const rank = result.rank;\n const size = result.size;\n const shape = util.rightPad(result.shape.toString(), 14);\n let inputShapesDescription = '';\n\n for (const name in inputs) {\n const input = inputs[name];\n if (input != null) {\n // The input might be a non-tensor (e.g HTMLImageElement), in which case\n // we claim the output shape as input shape.\n const inputShape = input.shape || result.shape;\n const inputRank = inputShape.length;\n inputShapesDescription +=\n `${name}: ${inputRank}D ${inputRank > 0 ? inputShape : ''} `;\n }\n }\n\n console.log(\n `%c${paddedName}\\t%c${time}\\t%c${rank}D ${shape}\\t%c${size}\\t%c${\n inputShapesDescription}\\t%c${extraInfo}`,\n 'font-weight:bold', 'color:red', 'color:blue', 'color: orange',\n 'color: green', 'color: steelblue');\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from './tensor';\nimport {NamedTensorMap} from './tensor_types';\nimport * as util from './util';\n\nexport interface TapeNode {\n id: number;\n kernelName: string;\n outputs: Tensor[];\n inputs: NamedTensorMap;\n // Optional params, defined only for ops with gradient impl.\n gradient?: (dys: Tensor[]) => NamedGradientMap;\n saved?: Tensor[];\n}\n\nexport type NamedGradientMap = {\n [inputName: string]: () => Tensor;\n};\n\n/**\n * Computes a list of TapeNodes that connect x to y, filtering everything else\n * out and preserving the order of the original tape elements.\n *\n * @param tape The tape elements to filter.\n * @param xs The input Tensors.\n * @param y The output Tensor.\n */\nexport function getFilteredNodesXToY(\n tape: TapeNode[], xs: Tensor[], y: Tensor): TapeNode[] {\n // Forward pass to compute all the nodes and Tensors that are transitively a\n // function of x.\n const tensorsFromX: {[tensorId: number]: boolean} = {};\n const nodesFromX: {[nodeId: number]: boolean} = {};\n for (let i = 0; i < xs.length; i++) {\n tensorsFromX[xs[i].id] = true;\n }\n\n for (let i = 0; i < tape.length; i++) {\n const node = tape[i];\n const nodeInputs = node.inputs;\n for (const inputName in nodeInputs) {\n const input = nodeInputs[inputName];\n\n let anyInputFromX = false;\n for (let j = 0; j < xs.length; j++) {\n if (tensorsFromX[input.id]) {\n node.outputs.forEach(output => tensorsFromX[output.id] = true);\n anyInputFromX = true;\n nodesFromX[node.id] = true;\n break;\n }\n }\n\n if (anyInputFromX) {\n break;\n }\n }\n }\n\n // Backward pass to find all of the nodes and Tensors that lead to y.\n const tensorsLeadToY: {[tensorId: number]: boolean} = {};\n tensorsLeadToY[y.id] = true;\n const nodesToY: {[nodeId: number]: boolean} = {};\n\n for (let i = tape.length - 1; i >= 0; i--) {\n const node = tape[i];\n const nodeInputs = node.inputs;\n\n // If any of the outputs lead to y, mark all of the inputs as leading to y.\n for (let j = 0; j < node.outputs.length; j++) {\n if (tensorsLeadToY[node.outputs[j].id]) {\n for (const inputName in nodeInputs) {\n tensorsLeadToY[nodeInputs[inputName].id] = true;\n nodesToY[node.id] = true;\n }\n break;\n }\n }\n }\n\n // Return the paths that come from x and lead to y.\n const filteredTape: TapeNode[] = [];\n for (let i = 0; i < tape.length; i++) {\n const node = tape[i];\n\n if (nodesFromX[node.id] && nodesToY[node.id]) {\n // Prune the inputs from the node that aren't a function of x.\n const prunedInputs: {[inputName: string]: Tensor} = {};\n for (const inputName in node.inputs) {\n const nodeInput = node.inputs[inputName];\n if (tensorsFromX[nodeInput.id]) {\n prunedInputs[inputName] = nodeInput;\n }\n }\n\n // Copy the node and overwrite inputsAndArgs to the pruned version.\n const prunedNode = Object.assign({}, node);\n prunedNode.inputs = prunedInputs;\n prunedNode.outputs = node.outputs;\n\n filteredTape.push(prunedNode);\n }\n }\n\n return filteredTape;\n}\n\n/**\n * Backpropagate gradients through the filtered TapeNodes.\n *\n * @param tensorAccumulatedGradientMap A map of Tensor to its gradient. This map\n * is mutated by this method.\n * @param filteredTape The filtered TapeNodes to backprop through.\n */\nexport function backpropagateGradients(\n tensorAccumulatedGradientMap: {[tensorId: number]: Tensor},\n filteredTape: TapeNode[], tidy: (f: Function) => Tensor,\n add: (a: Tensor, b: Tensor) => Tensor) {\n // Walk the tape backward and keep a map of Tensor to its gradient.\n for (let i = filteredTape.length - 1; i >= 0; i--) {\n const node = filteredTape[i];\n\n const dys: Tensor[] = [];\n node.outputs.forEach(o => {\n const gradTensor = tensorAccumulatedGradientMap[o.id];\n if (gradTensor != null) {\n dys.push(gradTensor);\n } else {\n // This particular output is not in the back-propagation subgraph, so it\n // does not affect the final output, thus we put null for its dy.\n dys.push(null);\n }\n });\n\n if (node.gradient == null) {\n throw new Error(\n `Cannot compute gradient: gradient function not found ` +\n `for ${node.kernelName}.`);\n }\n\n // Backprop dy through this node and accumulate gradients over the inputs.\n const inputGradients = node.gradient(dys);\n\n for (const inputName in node.inputs) {\n if (!(inputName in inputGradients)) {\n throw new Error(\n `Cannot backprop through input ${inputName}. ` +\n `Available gradients found: ${Object.keys(inputGradients)}.`);\n }\n\n // Call the gradient function.\n const dx = tidy(() => inputGradients[inputName]());\n if (dx.dtype !== 'float32') {\n throw new Error(\n `Error in gradient for op ${\n node.kernelName}. The gradient of input ` +\n `${inputName} must have 'float32' dtype, but has '${dx.dtype}'`);\n }\n const x = node.inputs[inputName];\n if (!util.arraysEqual(dx.shape, x.shape)) {\n throw new Error(\n `Error in gradient for op ${\n node.kernelName}. The gradient of input ` +\n `'${inputName}' has shape '${dx.shape}', which does not match ` +\n `the shape of the input '${x.shape}'`);\n }\n\n if (tensorAccumulatedGradientMap[x.id] == null) {\n tensorAccumulatedGradientMap[x.id] = dx;\n } else {\n const curGradient = tensorAccumulatedGradientMap[x.id];\n tensorAccumulatedGradientMap[x.id] = add(curGradient, dx);\n curGradient.dispose();\n }\n }\n }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, TypedArray} from './types';\nimport {computeStrides, isString, rightPad, sizeFromShape} from './util';\n\n// Maximum number of values before we decide to show ellipsis.\nconst FORMAT_LIMIT_NUM_VALS = 20;\n// Number of first and last values to show when displaying a, b,...,y, z.\nconst FORMAT_NUM_FIRST_LAST_VALS = 3;\n// Number of significant digits to show.\nconst FORMAT_NUM_SIG_DIGITS = 7;\n\nexport function tensorToString(\n vals: TypedArray|string[], shape: number[], dtype: DataType,\n verbose: boolean) {\n const strides = computeStrides(shape);\n const padPerCol = computeMaxSizePerColumn(vals, shape, dtype, strides);\n const rank = shape.length;\n const valsLines = subTensorToString(vals, shape, dtype, strides, padPerCol);\n const lines = ['Tensor'];\n if (verbose) {\n lines.push(` dtype: ${dtype}`);\n lines.push(` rank: ${rank}`);\n lines.push(` shape: [${shape}]`);\n lines.push(` values:`);\n }\n lines.push(valsLines.map(l => ' ' + l).join('\\n'));\n return lines.join('\\n');\n}\n\nfunction computeMaxSizePerColumn(\n vals: TypedArray|string[], shape: number[], dtype: DataType,\n strides: number[]): number[] {\n const n = sizeFromShape(shape);\n const numCols = strides[strides.length - 1];\n const padPerCol = new Array(numCols).fill(0);\n const rank = shape.length;\n const valuesOrTuples =\n dtype === 'complex64' ? createComplexTuples(vals) : vals;\n\n if (rank > 1) {\n for (let row = 0; row < n / numCols; row++) {\n const offset = row * numCols;\n for (let j = 0; j < numCols; j++) {\n padPerCol[j] = Math.max(\n padPerCol[j],\n valToString(valuesOrTuples[offset + j], 0, dtype).length);\n }\n }\n }\n return padPerCol;\n}\n\nfunction valToString(\n val: number|string|[number, number], pad: number, dtype: DataType) {\n let valStr: string;\n if (Array.isArray(val)) {\n valStr = `${parseFloat(val[0].toFixed(FORMAT_NUM_SIG_DIGITS))} + ` +\n `${parseFloat(val[1].toFixed(FORMAT_NUM_SIG_DIGITS))}j`;\n } else if (isString(val)) {\n valStr = `'${val}'`;\n } else if (dtype === 'bool') {\n valStr = boolNumToString(val);\n } else {\n valStr = parseFloat(val.toFixed(FORMAT_NUM_SIG_DIGITS)).toString();\n }\n\n return rightPad(valStr, pad);\n}\n\nfunction boolNumToString(v: number): string {\n return v === 0 ? 'false' : 'true';\n}\n\nfunction subTensorToString(\n vals: TypedArray|string[], shape: number[], dtype: DataType,\n strides: number[], padPerCol: number[], isLast = true): string[] {\n const storagePerElement = dtype === 'complex64' ? 2 : 1;\n\n const size = shape[0];\n const rank = shape.length;\n if (rank === 0) {\n if (dtype === 'complex64') {\n const complexTuple = createComplexTuples(vals);\n return [valToString(complexTuple[0], 0, dtype)];\n }\n if (dtype === 'bool') {\n return [boolNumToString(vals[0] as number)];\n }\n return [vals[0].toString()];\n }\n\n if (rank === 1) {\n if (size > FORMAT_LIMIT_NUM_VALS) {\n const firstValsSize = FORMAT_NUM_FIRST_LAST_VALS * storagePerElement;\n\n let firstVals = Array.from(\n vals.slice(0, firstValsSize));\n let lastVals = Array.from(vals.slice(\n (size - FORMAT_NUM_FIRST_LAST_VALS) * storagePerElement,\n size * storagePerElement));\n if (dtype === 'complex64') {\n firstVals = createComplexTuples(firstVals);\n lastVals = createComplexTuples(lastVals);\n }\n return [\n '[' +\n firstVals.map((x, i) => valToString(x, padPerCol[i], dtype))\n .join(', ') +\n ', ..., ' +\n lastVals\n .map(\n (x, i) => valToString(\n x, padPerCol[size - FORMAT_NUM_FIRST_LAST_VALS + i], dtype))\n .join(', ') +\n ']'\n ];\n }\n const displayVals: Array =\n dtype === 'complex64' ? createComplexTuples(vals) :\n Array.from(vals);\n\n return [\n '[' +\n displayVals.map((x, i) => valToString(x, padPerCol[i], dtype))\n .join(', ') +\n ']'\n ];\n }\n\n // The array is rank 2 or more.\n const subshape = shape.slice(1);\n const substrides = strides.slice(1);\n const stride = strides[0] * storagePerElement;\n const lines: string[] = [];\n if (size > FORMAT_LIMIT_NUM_VALS) {\n for (let i = 0; i < FORMAT_NUM_FIRST_LAST_VALS; i++) {\n const start = i * stride;\n const end = start + stride;\n lines.push(...subTensorToString(\n vals.slice(start, end), subshape, dtype, substrides, padPerCol,\n false /* isLast */));\n }\n lines.push('...');\n for (let i = size - FORMAT_NUM_FIRST_LAST_VALS; i < size; i++) {\n const start = i * stride;\n const end = start + stride;\n lines.push(...subTensorToString(\n vals.slice(start, end), subshape, dtype, substrides, padPerCol,\n i === size - 1 /* isLast */));\n }\n } else {\n for (let i = 0; i < size; i++) {\n const start = i * stride;\n const end = start + stride;\n lines.push(...subTensorToString(\n vals.slice(start, end), subshape, dtype, substrides, padPerCol,\n i === size - 1 /* isLast */));\n }\n }\n const sep = rank === 2 ? ',' : '';\n lines[0] = '[' + lines[0] + sep;\n for (let i = 1; i < lines.length - 1; i++) {\n lines[i] = ' ' + lines[i] + sep;\n }\n let newLineSep = ',\\n';\n for (let i = 2; i < rank; i++) {\n newLineSep += '\\n';\n }\n lines[lines.length - 1] =\n ' ' + lines[lines.length - 1] + ']' + (isLast ? '' : newLineSep);\n return lines;\n}\n\nfunction createComplexTuples(vals: Array<{}>|\n TypedArray): Array<[number, number]> {\n const complexTuples: Array<[number, number]> = [];\n for (let i = 0; i < vals.length; i += 2) {\n complexTuples.push([vals[i], vals[i + 1]] as [number, number]);\n }\n return complexTuples;\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {tensorToString} from './tensor_format';\nimport {ArrayMap, BackendValues, DataType, DataTypeMap, DataValues, NumericDataType, Rank, ShapeMap, SingleValueMap, TypedArray} from './types';\nimport * as util from './util';\nimport {computeStrides, toNestedArray} from './util';\n\nexport interface TensorData {\n dataId?: DataId;\n values?: DataTypeMap[D];\n}\n\n// This interface mimics KernelBackend (in backend.ts), which would create a\n// circular dependency if imported.\nexport interface Backend {}\n\n/**\n * A mutable object, similar to `tf.Tensor`, that allows users to set values\n * at locations before converting to an immutable `tf.Tensor`.\n *\n * See `tf.buffer` for creating a tensor buffer.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\nexport class TensorBuffer {\n size: number;\n shape: ShapeMap[R];\n strides: number[];\n values: DataTypeMap[D];\n\n constructor(shape: ShapeMap[R], public dtype: D, values?: DataTypeMap[D]) {\n this.shape = shape.slice() as ShapeMap[R];\n this.size = util.sizeFromShape(shape);\n\n if (values != null) {\n const n = values.length;\n util.assert(\n n === this.size,\n () => `Length of values '${n}' does not match the size ` +\n `inferred by the shape '${this.size}'.`);\n }\n if (dtype === 'complex64') {\n throw new Error(\n `complex64 dtype TensorBuffers are not supported. Please create ` +\n `a TensorBuffer for the real and imaginary parts separately and ` +\n `call tf.complex(real, imag).`);\n }\n this.values = values || util.getArrayFromDType(dtype, this.size);\n this.strides = computeStrides(shape);\n }\n\n /**\n * Sets a value in the buffer at a given location.\n *\n * @param value The value to set.\n * @param locs The location indices.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\n set(value: SingleValueMap[D], ...locs: number[]): void {\n if (locs.length === 0) {\n locs = [0];\n }\n util.assert(\n locs.length === this.rank,\n () => `The number of provided coordinates (${locs.length}) must ` +\n `match the rank (${this.rank})`);\n\n const index = this.locToIndex(locs);\n this.values[index] = value as number;\n }\n\n /**\n * Returns the value in the buffer at the provided location.\n *\n * @param locs The location indices.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\n get(...locs: number[]): SingleValueMap[D] {\n if (locs.length === 0) {\n locs = [0];\n }\n let i = 0;\n for (const loc of locs) {\n if (loc < 0 || loc >= this.shape[i]) {\n const msg = `Requested out of range element at ${locs}. ` +\n ` Buffer shape=${this.shape}`;\n throw new Error(msg);\n }\n i++;\n }\n let index = locs[locs.length - 1];\n for (let i = 0; i < locs.length - 1; ++i) {\n index += this.strides[i] * locs[i];\n }\n return this.values[index] as SingleValueMap[D];\n }\n\n locToIndex(locs: number[]): number {\n if (this.rank === 0) {\n return 0;\n } else if (this.rank === 1) {\n return locs[0];\n }\n let index = locs[locs.length - 1];\n for (let i = 0; i < locs.length - 1; ++i) {\n index += this.strides[i] * locs[i];\n }\n return index;\n }\n\n indexToLoc(index: number): number[] {\n if (this.rank === 0) {\n return [];\n } else if (this.rank === 1) {\n return [index];\n }\n const locs: number[] = new Array(this.shape.length);\n for (let i = 0; i < locs.length - 1; ++i) {\n locs[i] = Math.floor(index / this.strides[i]);\n index -= locs[i] * this.strides[i];\n }\n locs[locs.length - 1] = index;\n return locs;\n }\n\n get rank() {\n return this.shape.length;\n }\n\n /**\n * Creates an immutable `tf.Tensor` object from the buffer.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\n toTensor(): Tensor {\n return trackerFn().makeTensor(this.values, this.shape, this.dtype) as\n Tensor;\n }\n}\n\nexport interface TensorTracker {\n makeTensor(\n values: DataValues, shape: number[], dtype: DataType,\n backend?: Backend): Tensor;\n makeVariable(\n initialValue: Tensor, trainable?: boolean, name?: string,\n dtype?: DataType): Variable;\n incRef(a: Tensor, backend: Backend): void;\n disposeTensor(t: Tensor): void;\n disposeVariable(v: Variable): void;\n read(dataId: DataId): Promise;\n readSync(dataId: DataId): BackendValues;\n}\n\n/**\n * The Tensor class calls into this handler to delegate chaining operations.\n */\nexport interface OpHandler {\n cast(x: T, dtype: DataType): T;\n buffer(\n shape: ShapeMap[R], dtype: D,\n values?: DataTypeMap[D]): TensorBuffer;\n print(x: T, verbose: boolean): void;\n clone(x: T): T;\n // TODO(yassogba) bring reshape back?\n}\n\n// For tracking tensor creation and disposal.\nlet trackerFn: () => TensorTracker = null;\n// Used by chaining methods to call into ops.\nlet opHandler: OpHandler = null;\n// Used to warn about deprecated methods.\nlet deprecationWarningFn: (msg: string) => void = null;\n// This here so that we can use this method on dev branches and keep the\n// functionality at master.\n// tslint:disable-next-line:no-unused-expression\n[deprecationWarningFn];\n\n/**\n * An external consumer can register itself as the tensor tracker. This way\n * the Tensor class can notify the tracker for every tensor created and\n * disposed.\n */\nexport function setTensorTracker(fn: () => TensorTracker) {\n trackerFn = fn;\n}\n\n/**\n * An external consumer can register itself as the op handler. This way the\n * Tensor class can have chaining methods that call into ops via the op\n * handler.\n */\nexport function setOpHandler(handler: OpHandler) {\n opHandler = handler;\n}\n\n/**\n * Sets the deprecation warning function to be used by this file. This way the\n * Tensor class can be a leaf but still use the environment.\n */\nexport function setDeprecationWarningFn(fn: (msg: string) => void) {\n deprecationWarningFn = fn;\n}\n\n/**\n * We wrap data id since we use weak map to avoid memory leaks.\n * Since we have our own memory management, we have a reference counter\n * mapping a tensor to its data, so there is always a pointer (even if that\n * data is otherwise garbage collectable).\n * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/\n * Global_Objects/WeakMap\n */\nexport type DataId = object; // object instead of {} to force non-primitive.\n\n// Declare this namespace to make Tensor class augmentation work in google3.\nexport declare namespace Tensor {}\n/**\n * A `tf.Tensor` object represents an immutable, multidimensional array of\n * numbers that has a shape and a data type.\n *\n * See `tf.tensor` for details on how to create a `tf.Tensor`.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\nexport class Tensor {\n /** Unique id of this tensor. */\n readonly id: number;\n /**\n * Id of the bucket holding the data for this tensor. Multiple arrays can\n * point to the same bucket (e.g. when calling array.reshape()).\n */\n dataId: DataId;\n /** The shape of the tensor. */\n readonly shape: ShapeMap[R];\n /** Number of elements in the tensor. */\n readonly size: number;\n /** The data type for the array. */\n readonly dtype: DataType;\n /** The rank type for the array (see `Rank` enum). */\n readonly rankType: R;\n\n /** Whether this tensor has been globally kept. */\n kept = false;\n /** The id of the scope this tensor is being tracked in. */\n scopeId: number;\n\n /**\n * Number of elements to skip in each dimension when indexing. See\n * https://docs.scipy.org/doc/numpy/reference/generated/\\\n * numpy.ndarray.strides.html\n */\n readonly strides: number[];\n\n constructor(shape: ShapeMap[R], dtype: DataType, dataId: DataId, id: number) {\n this.shape = shape.slice() as ShapeMap[R];\n this.dtype = dtype || 'float32';\n this.size = util.sizeFromShape(shape);\n this.strides = computeStrides(shape);\n this.dataId = dataId;\n this.id = id;\n this.rankType = (this.rank < 5 ? this.rank.toString() : 'higher') as R;\n }\n\n get rank(): number {\n return this.shape.length;\n }\n\n /**\n * Returns a promise of `tf.TensorBuffer` that holds the underlying data.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n async buffer(): Promise> {\n const vals = await this.data();\n return opHandler.buffer(this.shape, this.dtype as D, vals);\n }\n\n /**\n * Returns a `tf.TensorBuffer` that holds the underlying data.\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n bufferSync(): TensorBuffer {\n return opHandler.buffer(this.shape, this.dtype as D, this.dataSync());\n }\n\n /**\n * Returns the tensor data as a nested array. The transfer of data is done\n * asynchronously.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n async array(): Promise {\n const vals = await this.data();\n return toNestedArray(this.shape, vals) as ArrayMap[R];\n }\n\n /**\n * Returns the tensor data as a nested array. The transfer of data is done\n * synchronously.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n arraySync(): ArrayMap[R] {\n return toNestedArray(this.shape, this.dataSync()) as ArrayMap[R];\n }\n\n /**\n * Asynchronously downloads the values from the `tf.Tensor`. Returns a\n * promise of `TypedArray` that resolves when the computation has finished.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n async data(): Promise {\n this.throwIfDisposed();\n const data = trackerFn().read(this.dataId);\n if (this.dtype === 'string') {\n const bytes = await data as Uint8Array[];\n try {\n return bytes.map(b => util.decodeString(b)) as DataTypeMap[D];\n } catch {\n throw new Error(\n 'Failed to decode the string bytes into utf-8. ' +\n 'To get the original bytes, call tensor.bytes().');\n }\n }\n return data as Promise;\n }\n\n /**\n * Synchronously downloads the values from the `tf.Tensor`. This blocks the\n * UI thread until the values are ready, which can cause performance issues.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n dataSync(): DataTypeMap[D] {\n this.throwIfDisposed();\n const data = trackerFn().readSync(this.dataId);\n if (this.dtype === 'string') {\n try {\n return (data as Uint8Array[]).map(b => util.decodeString(b)) as\n DataTypeMap[D];\n } catch {\n throw new Error(\n 'Failed to decode the string bytes into utf-8. ' +\n 'To get the original bytes, call tensor.bytes().');\n }\n }\n return data as DataTypeMap[D];\n }\n\n /** Returns the underlying bytes of the tensor's data. */\n async bytes(): Promise {\n this.throwIfDisposed();\n const data = await trackerFn().read(this.dataId);\n if (this.dtype === 'string') {\n return data as Uint8Array[];\n } else {\n return new Uint8Array((data as TypedArray).buffer);\n }\n }\n\n /**\n * Disposes `tf.Tensor` from memory.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n dispose(): void {\n if (this.isDisposed) {\n return;\n }\n trackerFn().disposeTensor(this);\n this.isDisposedInternal = true;\n }\n\n protected isDisposedInternal = false;\n get isDisposed(): boolean {\n return this.isDisposedInternal;\n }\n\n throwIfDisposed() {\n if (this.isDisposed) {\n throw new Error(`Tensor is disposed.`);\n }\n }\n\n /**\n * Prints the `tf.Tensor`. See `tf.print` for details.\n *\n * @param verbose Whether to print verbose information about the tensor,\n * including dtype and size.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n print(verbose = false): void {\n return opHandler.print(this, verbose);\n }\n\n /**\n * Returns a copy of the tensor. See `tf.clone` for details.\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n clone(this: T): T {\n this.throwIfDisposed();\n return opHandler.clone(this);\n }\n\n /**\n * Returns a human-readable description of the tensor. Useful for logging.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n toString(verbose = false): string {\n const vals = this.dataSync();\n return tensorToString(vals, this.shape, this.dtype, verbose);\n }\n\n cast(dtype: DataType): T {\n this.throwIfDisposed();\n return opHandler.cast(this as T, dtype);\n }\n variable(trainable = true, name?: string, dtype?: DataType): Variable {\n this.throwIfDisposed();\n return trackerFn().makeVariable(this, trainable, name, dtype) as\n Variable;\n }\n}\nObject.defineProperty(Tensor, Symbol.hasInstance, {\n value: (instance: Tensor) => {\n // Implementation note: we should use properties of the object that will be\n // defined before the constructor body has finished executing (methods).\n // This is because when this code is transpiled by babel, babel will call\n // classCallCheck before the constructor body is run.\n // See https://github.com/tensorflow/tfjs/issues/3384 for backstory.\n return !!instance && instance.data != null && instance.dataSync != null &&\n instance.throwIfDisposed != null;\n }\n});\n\nexport interface NumericTensor extends Tensor {\n dtype: NumericDataType;\n dataSync(): DataTypeMap[D];\n data(): Promise;\n}\n\nexport interface StringTensor extends Tensor {\n dtype: 'string';\n dataSync(): DataTypeMap[D];\n data(): Promise;\n}\n\n/** @doclink Tensor */\nexport type Scalar = Tensor;\n/** @doclink Tensor */\nexport type Tensor1D = Tensor;\n/** @doclink Tensor */\nexport type Tensor2D = Tensor;\n/** @doclink Tensor */\nexport type Tensor3D = Tensor;\n/** @doclink Tensor */\nexport type Tensor4D = Tensor;\n/** @doclink Tensor */\nexport type Tensor5D = Tensor;\n/** @doclink Tensor */\nexport type Tensor6D = Tensor;\n\n/**\n * A mutable `tf.Tensor`, useful for persisting state, e.g. for training.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\nexport class Variable extends Tensor {\n name: string;\n\n constructor(\n initialValue: Tensor, public trainable: boolean, name: string,\n tensorId: number) {\n super(\n initialValue.shape, initialValue.dtype, initialValue.dataId, tensorId);\n this.name = name;\n }\n\n /**\n * Assign a new `tf.Tensor` to this variable. The new `tf.Tensor` must have\n * the same shape and dtype as the old `tf.Tensor`.\n *\n * @param newValue New tensor to be assigned to this variable.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n assign(newValue: Tensor): void {\n if (newValue.dtype !== this.dtype) {\n throw new Error(\n `dtype of the new value (${newValue.dtype}) and ` +\n `previous value (${this.dtype}) must match`);\n }\n if (!util.arraysEqual(newValue.shape, this.shape)) {\n throw new Error(\n `shape of the new value (${newValue.shape}) and ` +\n `previous value (${this.shape}) must match`);\n }\n trackerFn().disposeTensor(this);\n this.dataId = newValue.dataId;\n trackerFn().incRef(this, null /* backend */);\n }\n\n dispose(): void {\n trackerFn().disposeVariable(this);\n this.isDisposedInternal = true;\n }\n}\n\nObject.defineProperty(Variable, Symbol.hasInstance, {\n value: (instance: Variable) => {\n return instance instanceof Tensor && instance.assign != null &&\n instance.assign instanceof Function;\n }\n});\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/** @docalias number[] */\nexport interface ShapeMap {\n R0: number[];\n R1: [number];\n R2: [number, number];\n R3: [number, number, number];\n R4: [number, number, number, number];\n R5: [number, number, number, number, number];\n R6: [number, number, number, number, number, number];\n}\n\n/** @docalias number[] */\nexport interface ArrayMap {\n R0: number;\n R1: number[];\n R2: number[][];\n R3: number[][][];\n R4: number[][][][];\n R5: number[][][][][];\n R6: number[][][][][][];\n}\n\nexport interface DataTypeMap {\n float32: Float32Array;\n int32: Int32Array;\n bool: Uint8Array;\n complex64: Float32Array;\n string: string[];\n}\n\nexport interface SingleValueMap {\n bool: boolean;\n int32: number;\n float32: number;\n complex64: number;\n string: string;\n}\n\n/** @docalias 'float32'|'int32'|'bool'|'complex64'|'string' */\nexport type DataType = keyof DataTypeMap;\nexport type NumericDataType = 'float32'|'int32'|'bool'|'complex64';\nexport type TypedArray = Float32Array|Int32Array|Uint8Array;\n/** Tensor data used in tensor creation and user-facing API. */\nexport type DataValues = DataTypeMap[DataType];\n/** The underlying tensor data that gets stored in a backend. */\nexport type BackendValues = Float32Array|Int32Array|Uint8Array|Uint8Array[];\n\nexport enum Rank {\n R0 = 'R0',\n R1 = 'R1',\n R2 = 'R2',\n R3 = 'R3',\n R4 = 'R4',\n R5 = 'R5',\n R6 = 'R6'\n}\n\nexport type FlatVector = boolean[]|number[]|TypedArray;\nexport type RegularArray =\n T[]|T[][]|T[][][]|T[][][][]|T[][][][][]|T[][][][][][];\n\n// tslint:disable-next-line:no-any\nexport interface RecursiveArray {\n [index: number]: T|RecursiveArray;\n}\n\n// Looks for upcasting types. Used, for example, in operations with mixed dtype\n// inputs.\nenum UpcastInt32AndMap {\n 'float32' = 'float32',\n 'int32' = 'int32',\n 'bool' = 'int32',\n 'complex64' = 'complex64'\n}\n\nenum UpcastBoolAndMap {\n 'float32' = 'float32',\n 'int32' = 'int32',\n 'bool' = 'bool',\n 'complex64' = 'complex64'\n}\n\nenum UpcastFloat32AndMap {\n 'float32' = 'float32',\n 'int32' = 'float32',\n 'bool' = 'float32',\n 'complex64' = 'complex64'\n}\n\nenum UpcastComplex64AndMap {\n 'float32' = 'complex64',\n 'int32' = 'complex64',\n 'bool' = 'complex64',\n 'complex64' = 'complex64'\n}\n\nconst upcastTypeMap = {\n 'float32': UpcastFloat32AndMap,\n 'int32': UpcastInt32AndMap,\n 'bool': UpcastBoolAndMap,\n 'complex64': UpcastComplex64AndMap\n};\n\nexport function upcastType(typeA: DataType, typeB: DataType): DataType {\n if (typeA === 'string' || typeB === 'string') {\n if (typeA === 'string' && typeB === 'string') {\n return 'string';\n }\n throw new Error(`Can not upcast ${typeA} with ${typeB}`);\n }\n return upcastTypeMap[typeA][typeB];\n}\n\n/** Returns the output type after summation. */\nexport function sumOutType(type: DataType): DataType {\n return upcastType(type, 'int32');\n}\n\n/** @docalias TypedArray|Array */\nexport type TensorLike =\n TypedArray|number|boolean|string|RecursiveArray|\n RecursiveArray|RecursiveArray|Uint8Array[];\nexport type ScalarLike = number|boolean|string|Uint8Array;\n/** @docalias TypedArray|Array */\nexport type TensorLike1D = TypedArray|number[]|boolean[]|string[]|Uint8Array[];\n/** @docalias TypedArray|Array */\nexport type TensorLike2D = TypedArray|number[]|number[][]|boolean[]|boolean[][]|\n string[]|string[][]|Uint8Array[]|Uint8Array[][];\n/** @docalias TypedArray|Array */\nexport type TensorLike3D = TypedArray|number[]|number[][][]|boolean[]|\n boolean[][][]|string[]|string[][][]|Uint8Array[]|Uint8Array[][][];\n/** @docalias TypedArray|Array */\nexport type TensorLike4D = TypedArray|number[]|number[][][][]|boolean[]|\n boolean[][][][]|string[]|string[][][][]|Uint8Array[]|Uint8Array[][][][];\n/** @docalias TypedArray|Array */\nexport type TensorLike5D =\n TypedArray|number[]|number[][][][][]|boolean[]|boolean[][][][][]|string[]|\n string[][][][][]|Uint8Array[]|Uint8Array[][][][][];\n/** @docalias TypedArray|Array */\nexport type TensorLike6D =\n TypedArray|number[]|number[][][][][][]|boolean[]|boolean[][][][][][]|\n string[]|string[][][][][][]|Uint8Array[]|Uint8Array[][][][][];\n\n/** Type for representing image dat in Uint8Array type. */\nexport interface PixelData {\n width: number;\n height: number;\n data: Uint8Array;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from './tensor';\nimport {TensorContainer, TensorContainerArray} from './tensor_types';\nimport {upcastType} from './types';\nimport {assert} from './util';\n\nexport function makeTypesMatch(a: T, b: T): [T, T] {\n if (a.dtype === b.dtype) {\n return [a, b];\n }\n const dtype = upcastType(a.dtype, b.dtype);\n return [a.cast(dtype), b.cast(dtype)];\n}\n\nexport function assertTypesMatch(a: Tensor, b: Tensor): void {\n assert(\n a.dtype === b.dtype,\n () => `The dtypes of the first(${a.dtype}) and` +\n ` second(${b.dtype}) input must match`);\n}\n\nexport function isTensorInList(tensor: Tensor, tensorList: Tensor[]): boolean {\n return tensorList.some(x => x.id === tensor.id);\n}\n\n/**\n * Extracts any `Tensor`s found within the provided object.\n *\n * @param container an object that may be a `Tensor` or may directly contain\n * `Tensor`s, such as a `Tensor[]` or `{key: Tensor, ...}`. In general it\n * is safe to pass any object here, except that `Promise`s are not\n * supported.\n * @returns An array of `Tensors` found within the passed object. If the\n * argument is simply a `Tensor', a list containing that `Tensor` is\n * returned. If the object is not a `Tensor` or does not\n * contain `Tensors`, an empty list is returned.\n */\nexport function getTensorsInContainer(result: TensorContainer): Tensor[] {\n const list: Tensor[] = [];\n const seen = new Set<{}|void>();\n walkTensorContainer(result, list, seen);\n return list;\n}\n\nfunction walkTensorContainer(\n container: TensorContainer, list: Tensor[], seen: Set<{}|void>): void {\n if (container == null) {\n return;\n }\n if (container instanceof Tensor) {\n list.push(container);\n return;\n }\n if (!isIterable(container)) {\n return;\n }\n // Iteration over keys works also for arrays.\n const iterable = container as TensorContainerArray;\n for (const k in iterable) {\n const val = iterable[k];\n if (!seen.has(val)) {\n seen.add(val);\n walkTensorContainer(val, list, seen);\n }\n }\n}\n\n// tslint:disable-next-line:no-any\nfunction isIterable(obj: any): boolean {\n return Array.isArray(obj) || typeof obj === 'object';\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {BackendTimingInfo, DataMover, KernelBackend} from './backends/backend';\nimport {Environment, setEnvironmentGlobal} from './environment';\nimport {getGlobalNamespace} from './global_util';\nimport {Add, Cast} from './kernel_names';\nimport {getGradient, getKernel, getKernelsForBackend, GradFunc, NamedAttrMap, TensorInfo} from './kernel_registry';\nimport {KernelProfile, Profiler} from './profiler';\nimport {backpropagateGradients, getFilteredNodesXToY, TapeNode} from './tape';\nimport {DataId, setTensorTracker, Tensor, TensorTracker, Variable} from './tensor';\nimport {GradSaveFunc, NamedTensorMap, NamedVariableMap, TensorContainer} from './tensor_types';\nimport {getTensorsInContainer} from './tensor_util';\nimport {BackendValues, DataType, DataValues} from './types';\nimport * as util from './util';\nimport {bytesFromStringArray, makeOnesTypedArray, now, sizeFromShape} from './util';\n\n/**\n * A function that computes an output. The save function is for saving tensors\n * computed in the forward pass, that we need in the backward pass.\n */\nexport type ForwardFunc = (backend: KernelBackend, save?: GradSaveFunc) => T;\n\n/**\n * @docalias (a: Tensor, b: Tensor,..., save?: Function) => {\n * value: Tensor,\n * gradFunc: (dy: Tensor, saved?: NamedTensorMap) => Tensor | Tensor[]\n * }\n */\nexport type CustomGradientFunc =\n (...inputs: Array) => {\n value: T;\n gradFunc: (dy: T, saved: Tensor[]) => Tensor | Tensor[];\n };\n\nexport type MemoryInfo = {\n numTensors: number; numDataBuffers: number; numBytes: number;\n unreliable?: boolean; reasons: string[];\n};\n\ntype KernelInfo = {\n name: string; bytesAdded: number; totalBytesSnapshot: number;\n tensorsAdded: number;\n totalTensorsSnapshot: number;\n inputShapes: number[][];\n outputShapes: number[][];\n kernelTimeMs: number | {error: string} | Promise;\n extraInfo: string | Promise;\n};\n\nexport type ProfileInfo = {\n newBytes: number; newTensors: number; peakBytes: number;\n kernels: KernelInfo[];\n result: TensorContainer;\n};\n\nexport interface TimingInfo extends BackendTimingInfo {\n wallMs: number;\n}\n\n/** @docalias Function */\nexport type ScopeFn = () => T;\n\ninterface ScopeState {\n track: Tensor[];\n name: string;\n id: number;\n}\n\nclass EngineState {\n // Public since optimizers will use it.\n registeredVariables: NamedVariableMap = {};\n\n nextTapeNodeId = 0;\n numBytes = 0;\n numTensors = 0;\n numStringTensors = 0;\n numDataBuffers = 0;\n\n activeTape: TapeNode[];\n // Number of nested tf.grad() statements when computing higher-order\n // gradients. E.g. `1` for first-order gradients and `2` for second-order\n // gradients. Used to track if the tape should be removed after a backprop.\n gradientDepth = 0;\n // Number of nested kernel calls. When kernel depth is greater than 1, we turn\n // off the tape.\n kernelDepth = 0;\n\n // Keep Tensors that parallel the tapes.\n activeScope: ScopeState;\n scopeStack: ScopeState[] = [];\n /**\n * Keeps track of the number of data moves during a kernel execution. We\n * maintain a stack since kernels can call other kernels, recursively.\n */\n numDataMovesStack: number[] = [];\n nextScopeId = 0;\n\n tensorInfo = new WeakMap();\n\n profiling = false;\n activeProfile: ProfileInfo =\n {newBytes: 0, newTensors: 0, peakBytes: 0, kernels: [], result: null};\n\n dispose() {\n for (const variableName in this.registeredVariables) {\n this.registeredVariables[variableName].dispose();\n }\n }\n}\n\nexport class Engine implements TensorTracker, DataMover {\n state: EngineState;\n backendName: string;\n registry: {[id: string]: KernelBackend} = {};\n registryFactory: {\n [id: string]: {\n factory: () => KernelBackend | Promise,\n priority: number\n }\n } = {};\n\n private profiler: Profiler;\n private backendInstance: KernelBackend;\n private pendingBackendInit: Promise;\n private pendingBackendInitId = 0;\n\n constructor(public ENV: Environment) {\n this.state = new EngineState();\n }\n\n async ready(): Promise {\n if (this.pendingBackendInit != null) {\n return this.pendingBackendInit.then(() => {});\n }\n if (this.backendInstance != null) {\n return;\n }\n const sortedBackends = this.getSortedBackends();\n\n for (let i = 0; i < sortedBackends.length; i++) {\n const backendName = sortedBackends[i];\n const success = await this.initializeBackend(backendName).success;\n if (success) {\n await this.setBackend(backendName);\n return;\n }\n }\n\n throw new Error(\n `Could not initialize any backends, all backend initializations ` +\n `failed.`);\n }\n\n get backend(): KernelBackend {\n if (this.pendingBackendInit != null) {\n throw new Error(\n `Backend '${this.backendName}' has not yet been initialized. Make ` +\n `sure to await tf.ready() or await tf.setBackend() before calling ` +\n `other methods`);\n }\n if (this.backendInstance == null) {\n const {name, asyncInit} = this.initializeBackendsAndReturnBest();\n if (asyncInit) {\n throw new Error(\n `The highest priority backend '${name}' has not yet been ` +\n `initialized. Make sure to await tf.ready() or ` +\n `await tf.setBackend() before calling other methods`);\n }\n this.setBackend(name);\n }\n return this.backendInstance;\n }\n\n backendNames(): string[] {\n return Object.keys(this.registryFactory);\n }\n\n findBackend(backendName: string): KernelBackend {\n if (!(backendName in this.registry)) {\n // If the backend hasn't been initialized but we have a registry entry for\n // it, initialize it and return it.\n if (backendName in this.registryFactory) {\n const {asyncInit} = this.initializeBackend(backendName);\n if (asyncInit) {\n // Backend is not ready yet.\n return null;\n }\n } else {\n return null;\n }\n }\n return this.registry[backendName];\n }\n\n findBackendFactory(backendName: string):\n () => KernelBackend | Promise {\n if (!(backendName in this.registryFactory)) {\n return null;\n }\n return this.registryFactory[backendName].factory;\n }\n\n registerBackend(\n backendName: string,\n factory: () => KernelBackend | Promise,\n priority = 1): boolean {\n if (backendName in this.registryFactory) {\n console.warn(\n `${backendName} backend was already registered. ` +\n `Reusing existing backend factory.`);\n return false;\n }\n this.registryFactory[backendName] = {factory, priority};\n return true;\n }\n\n async setBackend(backendName: string): Promise {\n if (this.registryFactory[backendName] == null) {\n throw new Error(`Backend name '${backendName}' not found in registry`);\n }\n this.backendName = backendName;\n if (this.registry[backendName] == null) {\n this.backendInstance = null;\n const {success, asyncInit} = this.initializeBackend(backendName);\n const result = asyncInit ? await success : success;\n if (!result) {\n return false;\n }\n }\n this.backendInstance = this.registry[backendName];\n this.setupRegisteredKernels();\n // Reset the profiler.\n this.profiler = new Profiler(this.backendInstance);\n\n return true;\n }\n\n private setupRegisteredKernels(): void {\n const kernels = getKernelsForBackend(this.backendName);\n kernels.forEach(kernel => {\n if (kernel.setupFunc != null) {\n kernel.setupFunc(this.backendInstance);\n }\n });\n }\n\n private disposeRegisteredKernels(backendName: string): void {\n const kernels = getKernelsForBackend(backendName);\n kernels.forEach(kernel => {\n if (kernel.disposeFunc != null) {\n kernel.disposeFunc(this.registry[backendName]);\n }\n });\n }\n\n /**\n * Initializes a backend by looking up the backend name in the factory\n * registry and calling the factory method. Returns a boolean representing\n * whether the initialization of the backend suceeded. Throws an error if\n * there is no backend in the factory registry.\n */\n private initializeBackend(backendName: string):\n {success: boolean|Promise, asyncInit: boolean} {\n const registryFactoryEntry = this.registryFactory[backendName];\n if (registryFactoryEntry == null) {\n throw new Error(\n `Cannot initialize backend ${backendName}, no registration found.`);\n }\n\n try {\n const backend = registryFactoryEntry.factory();\n /* Test if the factory returns a promise.\n Done in a more liberal way than\n previous 'Promise.resolve(backend)===backend'\n as we needed to account for custom Promise\n implementations (e.g. Angular) */\n if (backend && !(backend instanceof KernelBackend)\n && typeof backend.then === 'function') {\n const promiseId = ++this.pendingBackendInitId;\n const success =\n backend\n .then(backendInstance => {\n // Outdated promise. Another backend was set in the meantime.\n if (promiseId < this.pendingBackendInitId) {\n return false;\n }\n this.registry[backendName] = backendInstance;\n this.pendingBackendInit = null;\n return true;\n })\n .catch(err => {\n // Outdated promise. Another backend was set in the meantime.\n if (promiseId < this.pendingBackendInitId) {\n return false;\n }\n this.pendingBackendInit = null;\n console.warn(\n `Initialization of backend ${backendName} failed`);\n console.warn(err.stack || err.message);\n return false;\n });\n this.pendingBackendInit = success;\n return {success, asyncInit: true};\n } else {\n this.registry[backendName] = backend as KernelBackend;\n return {success: true, asyncInit: false};\n }\n } catch (err) {\n console.warn(`Initialization of backend ${backendName} failed`);\n console.warn(err.stack || err.message);\n return {success: false, asyncInit: false};\n }\n }\n\n removeBackend(backendName: string): void {\n if (!(backendName in this.registryFactory)) {\n throw new Error(`${backendName} backend not found in registry`);\n }\n if (this.backendName === backendName && this.pendingBackendInit != null) {\n // There is a pending promise of the backend we want to remove. Make it\n // obsolete.\n this.pendingBackendInitId++;\n }\n\n if (backendName in this.registry) {\n this.disposeRegisteredKernels(backendName);\n this.registry[backendName].dispose();\n delete this.registry[backendName];\n }\n\n delete this.registryFactory[backendName];\n\n // Unset the backend if it is active.\n if (this.backendName === backendName) {\n this.pendingBackendInit = null;\n this.backendName = null;\n this.backendInstance = null;\n }\n }\n\n private getSortedBackends(): string[] {\n if (Object.keys(this.registryFactory).length === 0) {\n throw new Error('No backend found in registry.');\n }\n return Object.keys(this.registryFactory).sort((a: string, b: string) => {\n // Highest priority comes first.\n return this.registryFactory[b].priority -\n this.registryFactory[a].priority;\n });\n }\n\n private initializeBackendsAndReturnBest():\n {name: string, asyncInit: boolean} {\n const sortedBackends = this.getSortedBackends();\n\n for (let i = 0; i < sortedBackends.length; i++) {\n const backendName = sortedBackends[i];\n const {success, asyncInit} = this.initializeBackend(backendName);\n if (asyncInit || success) {\n return {name: backendName, asyncInit};\n }\n }\n throw new Error(\n `Could not initialize any backends, all backend initializations ` +\n `failed.`);\n }\n\n moveData(backend: KernelBackend, dataId: DataId) {\n const info = this.state.tensorInfo.get(dataId);\n const srcBackend = info.backend;\n const values = this.readSync(dataId);\n // Delete the tensor from the old backend and move it to the new\n // backend.\n srcBackend.disposeData(dataId);\n info.backend = backend;\n backend.move(dataId, values, info.shape, info.dtype);\n if (this.shouldCheckForMemLeaks()) {\n // Track the number of moves during a kernel execution to correctly\n // detect memory leaks.\n this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1]++;\n }\n }\n\n tidy(nameOrFn: string|ScopeFn, fn?: ScopeFn):\n T {\n let name: string = null;\n if (fn == null) {\n // Called with only 1 argument.\n if (typeof nameOrFn !== 'function') {\n throw new Error('Please provide a function to tidy()');\n }\n fn = nameOrFn;\n } else {\n // Called with 2 arguments.\n if (typeof nameOrFn !== 'string' && !(nameOrFn instanceof String)) {\n throw new Error(\n 'When calling with two arguments, the first argument ' +\n 'to tidy() must be a string');\n }\n if (typeof fn !== 'function') {\n throw new Error(\n 'When calling with two arguments, the 2nd argument ' +\n 'to tidy() must be a function');\n }\n name = nameOrFn as string;\n // TODO(nsthorat,smilkov): Do operation logging and performance\n // profiling.\n }\n let result: T;\n return this.scopedRun(\n () => this.startScope(name), () => this.endScope(result), () => {\n result = fn();\n if (result instanceof Promise) {\n console.error('Cannot return a Promise inside of tidy.');\n }\n return result;\n });\n }\n\n private scopedRun(start: () => void, end: () => void, f: () => T): T {\n start();\n try {\n const res = f();\n end();\n return res;\n } catch (ex) {\n end();\n throw ex;\n }\n }\n\n private static nextTensorId = 0;\n private nextTensorId(): number {\n return Engine.nextTensorId++;\n }\n\n private static nextVariableId = 0;\n private nextVariableId(): number {\n return Engine.nextVariableId++;\n }\n\n /**\n * This method is called instead of the public-facing tensor.clone() when\n * saving a tensor for backwards pass. It makes sure to add the clone\n * operation to the tape regardless of being called inside a kernel\n * execution.\n *\n * This method will go away once all kernels are modularized since we won't\n * need to turn off the tape inside runKernel().\n */\n private clone(x: Tensor): Tensor {\n const y = this.makeTensorFromDataId(x.dataId, x.shape, x.dtype);\n const inputs = {x};\n const grad = (dy: Tensor) => ({\n x: () => {\n const dtype = 'float32';\n const gradInputs = {x: dy};\n const attrs = {dtype};\n\n return ENGINE.runKernelFunc(\n backend => backend.cast(dy, dtype),\n gradInputs as {} as NamedTensorMap, null /* grad */, Cast,\n attrs as {} as NamedAttrMap);\n }\n });\n const saved: Tensor[] = [];\n this.addTapeNode(this.state.activeScope.name, inputs, [y], grad, saved, {});\n return y;\n }\n\n /**\n * Execute a kernel with the given name and return the output tensor.\n *\n * @param kernelName The name of the kernel to execute.\n * @param inputs A map of input names to tensors.\n * @param attrs A map of attribute names to their values. An attribute is a\n * primitive (non-tensor) input to the kernel.\n * @param inputsToSave A list of tensors, inputs to save for the backprop\n * computation.\n * @param outputsToSave A list of booleans, specifying which output to save\n * for the backprop computation. These are booleans since the output\n * tensors are not visible to the user.\n */\n runKernel(\n kernelName: string, inputs: NamedTensorMap, attrs: NamedAttrMap,\n inputsToSave?: Tensor[], outputsToSave?: boolean[]): Tensor|Tensor[] {\n const forwardFunc: null = null;\n const backwardsFunc: null = null;\n // Call runKernel as a stop-gap until we modularize all kernels.\n // Once we modularize all kernels, we will remove the existing\n // `runKernelFunc`.\n return this.runKernelFunc(\n forwardFunc, inputs, backwardsFunc, kernelName, attrs, inputsToSave,\n outputsToSave);\n }\n\n private shouldCheckForMemLeaks(): boolean {\n return this.ENV.getBool('IS_TEST');\n }\n\n private checkKernelForMemLeak(\n kernelName: string, numDataIdsBefore: number,\n outInfos: TensorInfo[]): void {\n const numDataIdsAfter = this.backend.numDataIds();\n\n // Count the number of data ids associated with the result of the kernel.\n let numOutputDataIds = 0;\n outInfos.forEach(info => {\n // Complex numbers allocate 3 data ids, one for 'real', one for\n // 'imaginary', and one for the container that holds the former two.\n numOutputDataIds += (info.dtype === 'complex64' ? 3 : 1);\n });\n\n // Account for the number of moves during kernel execution. A \"data move\"\n // can happen in the middle of a kernel execution, placing a new (key,value)\n // pair in the data storage. Since data moves have net zero effect (we\n // always remove the data from the old backend), we have to cancel them out\n // when detecting memory leaks.\n const numMoves =\n this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1];\n const dataIdsLeaked =\n numDataIdsAfter - numDataIdsBefore - numOutputDataIds - numMoves;\n if (dataIdsLeaked > 0) {\n throw new Error(\n `Backend '${this.backendName}' has an internal memory leak ` +\n `(${dataIdsLeaked} data ids) after running '${kernelName}'`);\n }\n }\n\n /**\n * @deprecated Use `runKernel` for newly added kernels. Keep using this method\n * only for kernels that are not yet fully modularized.\n */\n runKernelFunc(\n forwardFunc: ForwardFunc, inputs: I,\n backwardsFunc?: (dy: T, saved: Tensor[]) => {[P in keyof I]: () => I[P]},\n kernelName?: string, attrs?: NamedAttrMap, inputsToSave?: Tensor[],\n outputsToSave?: boolean[]): T {\n let outputs: Tensor[];\n let saved: Tensor[] = [];\n const isTapeOn = this.isTapeOn();\n if (kernelName == null) {\n kernelName =\n this.state.activeScope != null ? this.state.activeScope.name : '';\n }\n\n const startingBytecount = this.state.numBytes;\n const startingNumTensors = this.state.numTensors;\n\n if (this.shouldCheckForMemLeaks()) {\n this.state.numDataMovesStack.push(0);\n }\n\n let kernelFunc: () => Tensor[];\n const kernel = getKernel(kernelName, this.backendName);\n let out: TensorInfo|TensorInfo[];\n if (kernel != null) {\n kernelFunc = () => {\n const numDataIdsBefore = this.backend.numDataIds();\n out = kernel.kernelFunc({inputs, attrs, backend: this.backend});\n const outInfos = Array.isArray(out) ? out : [out];\n if (this.shouldCheckForMemLeaks()) {\n this.checkKernelForMemLeak(kernelName, numDataIdsBefore, outInfos);\n }\n const outTensors = outInfos.map(\n ({dataId, shape, dtype}) =>\n this.makeTensorFromDataId(dataId, shape, dtype));\n\n // Save the inputs and outputs.\n // Do not save unless we are recording to the tape. Otherwise it would\n // cause a mem leak since we would never run backprop, which disposes\n // the kept tensors.\n if (isTapeOn) {\n let tensorsToSave =\n this.getTensorsForGradient(kernelName, inputs, outTensors);\n if (tensorsToSave == null) {\n // Fallback for ops that call runKernelFunc and pass in\n // inputsToSave and outputsToSave. Currently this is the set of ops\n // with kernel support in the WASM backend. Once those ops and\n // respective gradients are modularised we can remove this path.\n if (outputsToSave == null) {\n outputsToSave = [];\n }\n const outsToSave = outTensors.filter((_, i) => outputsToSave[i]);\n tensorsToSave = (inputsToSave || []).slice().concat(outsToSave);\n }\n saved = this.saveTensorsForBackwardMode(tensorsToSave);\n }\n return outTensors;\n };\n } else {\n const saveFunc: GradSaveFunc = (tensors) => {\n // Do not save unless we are recording to the tape. Otherwise it would\n // cause a mem leak since we would never run backprop, which disposes\n // the kept tensors.\n if (!isTapeOn) {\n return;\n }\n saved = tensors.map(tensor => this.keep(this.clone(tensor)));\n };\n\n kernelFunc = () => {\n const numDataIdsBefore = this.backend.numDataIds();\n out = this.tidy(() => forwardFunc(this.backend, saveFunc));\n const outs = (Array.isArray(out) ? out : [out]) as Tensor[];\n if (this.shouldCheckForMemLeaks()) {\n this.checkKernelForMemLeak(kernelName, numDataIdsBefore, outs);\n }\n return outs;\n };\n }\n\n // Stop recording to a tape when running a kernel.\n let kernelProfile: KernelProfile;\n this.scopedRun(\n () => this.state.kernelDepth++, () => this.state.kernelDepth--, () => {\n if (!this.ENV.getBool('DEBUG') && !this.state.profiling) {\n outputs = kernelFunc();\n } else {\n kernelProfile = this.profiler.profileKernel(\n kernelName, inputs, () => kernelFunc());\n if (this.ENV.getBool('DEBUG')) {\n this.profiler.logKernelProfile(kernelProfile);\n }\n outputs = kernelProfile.outputs;\n }\n });\n\n if (isTapeOn) {\n this.addTapeNode(\n kernelName, inputs, outputs, backwardsFunc, saved, attrs);\n }\n\n if (this.state.profiling) {\n this.state.activeProfile.kernels.push({\n name: kernelName,\n bytesAdded: this.state.numBytes - startingBytecount,\n totalBytesSnapshot: this.state.numBytes,\n tensorsAdded: this.state.numTensors - startingNumTensors,\n totalTensorsSnapshot: this.state.numTensors,\n inputShapes: Object.keys(inputs).map(\n key => inputs[key] != null ? inputs[key].shape : null),\n outputShapes: outputs.map(item => item.shape),\n kernelTimeMs: kernelProfile.timeMs,\n extraInfo: kernelProfile.extraInfo\n });\n }\n return (Array.isArray(out) ? outputs : outputs[0]) as T;\n }\n\n /**\n * Saves tensors used in forward mode for use in backward mode.\n *\n * @param tensors the list of tensors to save.\n */\n private saveTensorsForBackwardMode(tensors: Tensor[]): Tensor[] {\n const saved = tensors.map(tensor => this.keep(this.clone(tensor)));\n return saved;\n }\n\n /**\n * Returns a list of tensors to save for a given gradient calculation.\n *\n * Returns undefined if their is no registered gradient for this kernel in the\n * gradient registry.\n *\n * @param kernelName name of kernel to look up gradient for.\n * @param inputs a map of input tensors.\n * @param outputs an array of output tensors from forward mode of kernel.\n */\n private getTensorsForGradient(\n kernelName: string, inputs: NamedTensorMap,\n outputs: Tensor[]): Tensor[]|null {\n const gradConfig = getGradient(kernelName);\n if (gradConfig != null) {\n const inputsToSave: string[] = gradConfig.inputsToSave || [];\n const outputsToSave: boolean[] = gradConfig.outputsToSave || [];\n\n // If saveAllInputs is true, all inputs will be saved. Otherwise, inputs\n // specified in inputsToSave will be saved.\n let inputTensorsToSave: Tensor[];\n if (gradConfig.saveAllInputs) {\n util.assert(\n Array.isArray(inputs),\n () => 'saveAllInputs is true, expected inputs to be an array.');\n\n inputTensorsToSave = Object.keys(inputs).map((key) => inputs[key]);\n } else {\n inputTensorsToSave = inputsToSave.map((inputName) => inputs[inputName]);\n }\n\n const outputTensorsToSave: Tensor[] =\n outputs.filter((_, i) => outputsToSave[i]);\n\n return inputTensorsToSave.concat(outputTensorsToSave);\n }\n // TODO(yassogba) throw exception here once all runkernelFunc calls with\n // inputsToSave/outputsToSave are removed\n return null;\n }\n\n /**\n * Internal method used by public APIs for tensor creation. Makes a new\n * tensor with the provided shape, dtype and values. It always\n * creates a new data id and writes the values to the underlying backend.\n */\n makeTensor(\n values: DataValues, shape: number[], dtype: DataType,\n backend?: KernelBackend): Tensor {\n if (values == null) {\n throw new Error('Values passed to engine.makeTensor() are null');\n }\n dtype = dtype || 'float32';\n backend = backend || this.backend;\n let backendVals = values as BackendValues;\n if (dtype === 'string' && util.isString(values[0])) {\n backendVals = (values as string[]).map(d => util.encodeString(d));\n }\n const dataId = backend.write(backendVals, shape, dtype);\n const t = new Tensor(shape, dtype, dataId, this.nextTensorId());\n this.incRef(t, backend);\n\n // Count bytes for string tensors.\n if (dtype === 'string') {\n const info = this.state.tensorInfo.get(dataId);\n const newBytes = bytesFromStringArray(backendVals as Uint8Array[]);\n this.state.numBytes += newBytes - info.bytes;\n info.bytes = newBytes;\n }\n return t;\n }\n\n /**\n * Internal method used by backends. Makes a new tensor\n * that is a wrapper around an existing data id. It doesn't create\n * a new data id, only increments the ref count used in memory tracking.\n */\n makeTensorFromDataId(\n dataId: DataId, shape: number[], dtype: DataType,\n backend?: KernelBackend): Tensor {\n dtype = dtype || 'float32';\n const t = new Tensor(shape, dtype, dataId, this.nextTensorId());\n this.incRef(t, backend);\n return t;\n }\n\n makeVariable(\n initialValue: Tensor, trainable = true, name?: string,\n dtype?: DataType): Variable {\n name = name || this.nextVariableId().toString();\n if (dtype != null && dtype !== initialValue.dtype) {\n initialValue = initialValue.cast(dtype);\n }\n const v = new Variable(initialValue, trainable, name, this.nextTensorId());\n if (this.state.registeredVariables[v.name] != null) {\n throw new Error(`Variable with name ${v.name} was already registered`);\n }\n this.state.registeredVariables[v.name] = v;\n this.incRef(v, this.backend);\n return v;\n }\n\n incRef(a: Tensor, backend: KernelBackend): void {\n const refCount = this.state.tensorInfo.has(a.dataId) ?\n this.state.tensorInfo.get(a.dataId).refCount :\n 0;\n this.state.numTensors++;\n if (a.dtype === 'string') {\n this.state.numStringTensors++;\n }\n if (refCount === 0) {\n this.state.numDataBuffers++;\n\n // Bytes for complex numbers are counted by their components. Bytes for\n // string tensors are counted when writing values.\n let bytes = 0;\n if (a.dtype !== 'complex64' && a.dtype !== 'string') {\n bytes = a.size * util.bytesPerElement(a.dtype);\n }\n this.state.tensorInfo.set(a.dataId, {\n backend: backend || this.backend,\n dtype: a.dtype,\n shape: a.shape,\n bytes,\n refCount: 0\n });\n this.state.numBytes += bytes;\n }\n\n this.state.tensorInfo.get(a.dataId).refCount++;\n\n if (!(a instanceof Variable)) {\n this.track(a);\n }\n }\n\n disposeTensor(a: Tensor): void {\n if (!this.state.tensorInfo.has(a.dataId)) {\n return;\n }\n\n this.state.numTensors--;\n if (a.dtype === 'string') {\n this.state.numStringTensors--;\n }\n const info = this.state.tensorInfo.get(a.dataId);\n const refCount = info.refCount;\n\n if (refCount <= 1) {\n // Don't count bytes for complex numbers as they are counted by their\n // components.\n if (a.dtype !== 'complex64') {\n this.state.numBytes -= info.bytes;\n }\n this.state.numDataBuffers--;\n\n info.backend.disposeData(a.dataId);\n this.state.tensorInfo.delete(a.dataId);\n } else {\n this.state.tensorInfo.get(a.dataId).refCount--;\n }\n // TODO(nsthorat): Construct an error and save the stack trace for\n // debugging when in debug mode. Creating a stack trace is too expensive\n // to do unconditionally.\n }\n\n disposeVariables(): void {\n for (const varName in this.state.registeredVariables) {\n const v = this.state.registeredVariables[varName];\n this.disposeVariable(v);\n }\n }\n\n disposeVariable(v: Variable): void {\n this.disposeTensor(v);\n if (this.state.registeredVariables[v.name] != null) {\n delete this.state.registeredVariables[v.name];\n }\n }\n\n memory(): MemoryInfo {\n const info = this.backend.memory() as MemoryInfo;\n info.numTensors = this.state.numTensors;\n info.numDataBuffers = this.state.numDataBuffers;\n info.numBytes = this.state.numBytes;\n if (this.state.numStringTensors > 0) {\n info.unreliable = true;\n if (info.reasons == null) {\n info.reasons = [];\n }\n info.reasons.push(\n 'Memory usage by string tensors is approximate ' +\n '(2 bytes per character)');\n }\n return info;\n }\n\n async profile(query: () => (TensorContainer | Promise)):\n Promise {\n this.state.profiling = true;\n\n const startBytes = this.state.numBytes;\n const startNumTensors = this.state.numTensors;\n\n this.state.activeProfile.kernels = [];\n this.state.activeProfile.result = await query();\n\n this.state.profiling = false;\n\n this.state.activeProfile.peakBytes = Math.max(\n ...this.state.activeProfile.kernels.map(d => d.totalBytesSnapshot));\n this.state.activeProfile.newBytes = this.state.numBytes - startBytes;\n this.state.activeProfile.newTensors =\n this.state.numTensors - startNumTensors;\n for (const kernel of this.state.activeProfile.kernels) {\n kernel.kernelTimeMs = await kernel.kernelTimeMs;\n kernel.extraInfo = await kernel.extraInfo;\n }\n return this.state.activeProfile;\n }\n\n isTapeOn(): boolean {\n return this.state.gradientDepth > 0 && this.state.kernelDepth === 0;\n }\n\n private addTapeNode(\n kernelName: string, inputs: NamedTensorMap, outputs: Tensor[],\n gradientsFunc: GradFunc, saved: Tensor[], attrs: NamedAttrMap): void {\n const tapeNode: TapeNode =\n {id: this.state.nextTapeNodeId++, kernelName, inputs, outputs, saved};\n\n const gradConfig = getGradient(kernelName);\n if (gradConfig != null) {\n gradientsFunc = gradConfig.gradFunc;\n }\n if (gradientsFunc != null) {\n tapeNode.gradient = (dys: Tensor[]) => {\n // TODO(smilkov): To optimize back-prop, pass dys that are not used in\n // the backprop graph to the user as null instead of zeros\n dys = dys.map((dy, i) => {\n if (dy == null) {\n const output = outputs[i];\n const vals = util.makeZerosTypedArray(output.size, output.dtype);\n return this.makeTensor(vals, output.shape, output.dtype);\n }\n return dy;\n });\n // Grad functions of ops with single outputs expect a dy, while ops\n // with multiple outputs expect dys (array of dy).\n return gradientsFunc(dys.length > 1 ? dys : dys[0], saved, attrs);\n };\n }\n this.state.activeTape.push(tapeNode);\n }\n\n keep(result: T): T {\n result.kept = true;\n return result;\n }\n\n private startTape() {\n if (this.state.gradientDepth === 0) {\n this.state.activeTape = [];\n }\n this.state.gradientDepth++;\n }\n\n private endTape() {\n this.state.gradientDepth--;\n }\n\n /**\n * Start a scope. Use this with endScope() to achieve the same functionality\n * as scope() without the need for a function closure.\n */\n startScope(name?: string) {\n const scopeInfo: ScopeState = {\n track: [],\n name: 'unnamed scope',\n id: this.state.nextScopeId++\n };\n if (name) {\n scopeInfo.name = name;\n }\n this.state.scopeStack.push(scopeInfo);\n this.state.activeScope = scopeInfo;\n }\n\n /**\n * End a scope. Use this with startScope() to achieve the same functionality\n * as scope() without the need for a function closure.\n */\n endScope(result?: TensorContainer) {\n const tensorsToTrackInParent = getTensorsInContainer(result);\n const tensorsToTrackInParentSet =\n new Set(tensorsToTrackInParent.map(t => t.id));\n\n // Dispose the arrays tracked in this scope.\n for (let i = 0; i < this.state.activeScope.track.length; i++) {\n const tensor = this.state.activeScope.track[i];\n if (!tensor.kept && !tensorsToTrackInParentSet.has(tensor.id)) {\n tensor.dispose();\n }\n }\n\n const oldScope = this.state.scopeStack.pop();\n this.state.activeScope = this.state.scopeStack.length === 0 ?\n null :\n this.state.scopeStack[this.state.scopeStack.length - 1];\n\n // Track the current result in the parent scope.\n tensorsToTrackInParent.forEach(tensor => {\n // Only track the tensor if was allocated in the inner scope and is not\n // globally kept.\n if (!tensor.kept && tensor.scopeId === oldScope.id) {\n this.track(tensor);\n }\n });\n }\n\n /**\n * Returns gradients of `f` with respect to each of the `xs`. The gradients\n * returned are of the same length as `xs`, but some might be null if `f`\n * was not a function of that `x`. It also takes optional dy to multiply the\n * gradient, which defaults to `1`.\n */\n gradients(\n f: () => T, xs: Tensor[], dy?: T,\n allowNoGradients = false): {value: T, grads: Tensor[]} {\n util.assert(\n xs.length > 0, () => 'gradients() received an empty list of xs.');\n if (dy != null && dy.dtype !== 'float32') {\n throw new Error(`dy must have 'float32' dtype, but has '${dy.dtype}'`);\n }\n\n const y = this.scopedRun(\n () => this.startTape(), () => this.endTape(),\n () => this.tidy('forward', f));\n\n util.assert(\n y instanceof Tensor,\n () => 'The result y returned by f() must be a tensor.');\n // Filter out the nodes that don't connect x => y.\n const filteredTape = getFilteredNodesXToY(this.state.activeTape, xs, y);\n if (!allowNoGradients && filteredTape.length === 0 && xs.length > 0) {\n throw new Error(\n 'Cannot compute gradient of y=f(x) with respect to x. Make sure ' +\n 'that the f you passed encloses all operations that lead from x ' +\n 'to y.');\n }\n\n return this.tidy('backward', () => {\n const accumulatedGradientMap: {[tensorId: number]: Tensor} = {};\n accumulatedGradientMap[y.id] = (dy == null) ? ones(y.shape) : dy;\n\n // Backprop gradients through the filtered nodes.\n backpropagateGradients(\n accumulatedGradientMap, filteredTape,\n // Pass the tidy function to avoid circular dep with `tape.ts`.\n f => this.tidy(f as ScopeFn),\n // Pass an add function to avoide a circular dep with `tape.ts`.\n add);\n const grads = xs.map(x => accumulatedGradientMap[x.id]);\n\n if (this.state.gradientDepth === 0) {\n // This means that we are not computing higher-order gradients\n // and can clean up the tape.\n this.state.activeTape.forEach(node => {\n for (const tensor of node.saved) {\n tensor.dispose();\n }\n });\n this.state.activeTape = null;\n }\n return {value: y, grads};\n });\n }\n\n customGrad(f: CustomGradientFunc):\n (...args: Array) => T {\n util.assert(\n util.isFunction(f),\n () => 'The f passed in customGrad(f) must be a function.');\n return (...inputs: Tensor[]): T => {\n util.assert(\n inputs.every(t => t instanceof Tensor),\n () => 'The args passed in customGrad(f)(x1, x2,...) must all be ' +\n 'tensors');\n\n let res: {\n value: T,\n gradFunc: (dy: T, saved: Tensor[]) => Tensor | Tensor[],\n };\n const inputMap: NamedTensorMap = {};\n inputs.forEach((input, i) => {\n inputMap[i] = input;\n });\n return this.runKernelFunc(\n (_, save) => {\n res = f(...[...inputs, save]);\n util.assert(\n res.value instanceof Tensor,\n () => 'The function f passed in customGrad(f) must return an ' +\n 'object where `obj.value` is a tensor');\n util.assert(\n util.isFunction(res.gradFunc),\n () => 'The function f passed in customGrad(f) must return an ' +\n 'object where `obj.gradFunc` is a function.');\n return res.value;\n },\n inputMap,\n (dy: T, saved: Tensor[]) => {\n const gradRes = res.gradFunc(dy, saved);\n const grads: Tensor[] =\n Array.isArray(gradRes) ? gradRes : [gradRes];\n util.assert(\n grads.length === inputs.length,\n () => 'The function f passed in customGrad(f) must return an ' +\n 'object where `obj.gradFunc` is a function that returns ' +\n 'the same number of tensors as inputs passed to f(...).');\n util.assert(\n grads.every(t => t instanceof Tensor),\n () => 'The function f passed in customGrad(f) must return an ' +\n 'object where `obj.gradFunc` is a function that returns ' +\n 'a list of only tensors.');\n const gradMap: {[key: string]: () => Tensor} = {};\n grads.forEach((grad, i) => {\n gradMap[i] = () => grad;\n });\n return gradMap;\n });\n };\n }\n\n readSync(dataId: DataId): BackendValues {\n // Route the read to the correct backend.\n const info = this.state.tensorInfo.get(dataId);\n return info.backend.readSync(dataId);\n }\n read(dataId: DataId): Promise {\n // Route the read to the correct backend.\n const info = this.state.tensorInfo.get(dataId);\n return info.backend.read(dataId);\n }\n\n async time(query: () => void): Promise {\n const start = now();\n const timingInfo = await this.backend.time(query) as TimingInfo;\n timingInfo.wallMs = now() - start;\n return timingInfo;\n }\n\n /**\n * Tracks a Tensor in the current scope to be automatically cleaned up\n * when the current scope ends, and returns the value.\n *\n * @param result The Tensor to track in the current scope.\n */\n private track(result: T): T {\n if (this.state.activeScope != null) {\n result.scopeId = this.state.activeScope.id;\n this.state.activeScope.track.push(result);\n }\n\n return result;\n }\n\n get registeredVariables(): NamedVariableMap {\n return this.state.registeredVariables;\n }\n\n /**\n * Resets the engine state. Removes all backends but does not remove\n * registered backend factories.\n */\n reset(): void {\n // Make any pending promise obsolete.\n this.pendingBackendInitId++;\n\n this.state.dispose();\n this.ENV.reset();\n this.state = new EngineState();\n\n for (const backendName in this.registry) {\n this.disposeRegisteredKernels(backendName);\n this.registry[backendName].dispose();\n delete this.registry[backendName];\n }\n this.backendName = null;\n this.backendInstance = null;\n this.pendingBackendInit = null;\n }\n}\n\nfunction ones(shape: number[]): Tensor {\n const values = makeOnesTypedArray(sizeFromShape(shape), 'float32');\n return ENGINE.makeTensor(values, shape, 'float32');\n}\n\nexport function getOrMakeEngine(): Engine {\n const ns = getGlobalNamespace() as {} as {_tfengine: Engine};\n if (ns._tfengine == null) {\n const environment = new Environment(ns);\n ns._tfengine = new Engine(environment);\n }\n setEnvironmentGlobal(ns._tfengine.ENV);\n\n // Tell the current tensor interface that the global engine is responsible\n // for tracking.\n setTensorTracker(() => ns._tfengine);\n return ns._tfengine;\n}\n\nexport const ENGINE = getOrMakeEngine();\n\n/**\n * A implementation of the add op for use within engine and tape.\n *\n * This allows us to avoid a circular dependency between add.ts and engine.\n * It is exported to be available in tape tests.\n */\nexport function add(a: Tensor, b: Tensor): Tensor {\n // We duplicate Add here to avoid a circular dependency with add.ts.\n const inputs = {a, b};\n return ENGINE.runKernelFunc((backend, save) => {\n const res = backend.add(a, b);\n save([a, b]);\n return res;\n }, inputs as {} as NamedTensorMap, null /* gradient */, Add);\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// tslint:disable-next-line:no-any\nfunction _isNavigatorDefined(): boolean {\n return typeof navigator !== 'undefined' && navigator != null;\n}\n\nexport function isMobile(): boolean {\n if (_isNavigatorDefined()) {\n // tslint:disable-next-line:no-any\n const a = navigator.userAgent || navigator.vendor || (window as any).opera;\n // tslint:disable-next-line:max-line-length\n 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\n .test(a) ||\n // tslint:disable-next-line:max-line-length\n /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\n .test(a.substr(0, 4));\n }\n return false;\n}\n\nexport function isBrowser(): boolean {\n return (typeof window !== 'undefined' && window.document != null) ||\n //@ts-ignore\n (typeof WorkerGlobalScope !== 'undefined');\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport './engine';\n\nimport * as device_util from './device_util';\nimport {env} from './environment';\n\nconst ENV = env();\n\n/**\n * This file contains environment-related flag registrations.\n */\n\n/** Whether to enable debug mode. */\nENV.registerFlag('DEBUG', () => false, debugValue => {\n if (debugValue) {\n console.warn(\n 'Debugging mode is ON. The output of every math call will ' +\n 'be downloaded to CPU and checked for NaNs. ' +\n 'This significantly impacts performance.');\n }\n});\n\n/** Whether we are in a browser (as versus, say, node.js) environment. */\nENV.registerFlag('IS_BROWSER', () => device_util.isBrowser());\n\n/** Whether we are in a browser (as versus, say, node.js) environment. */\nENV.registerFlag(\n 'IS_NODE',\n () => (typeof process !== 'undefined') &&\n (typeof process.versions !== 'undefined') &&\n (typeof process.versions.node !== 'undefined'));\n\n/** Whether this browser is Chrome. */\nENV.registerFlag(\n 'IS_CHROME',\n () => typeof navigator !== 'undefined' && navigator != null &&\n navigator.userAgent != null && /Chrome/.test(navigator.userAgent) &&\n /Google Inc/.test(navigator.vendor));\n\n/**\n * True when the environment is \"production\" where we disable safety checks\n * to gain performance.\n */\nENV.registerFlag('PROD', () => false);\n\n/**\n * Whether to do sanity checks when inferring a shape from user-provided\n * values, used when creating a new tensor.\n */\nENV.registerFlag(\n 'TENSORLIKE_CHECK_SHAPE_CONSISTENCY', () => ENV.getBool('DEBUG'));\n\n/** Whether deprecation warnings are enabled. */\nENV.registerFlag('DEPRECATION_WARNINGS_ENABLED', () => true);\n\n/** True if running unit tests. */\nENV.registerFlag('IS_TEST', () => false);\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from './engine';\nimport {env} from './environment';\nimport {Tensor} from './tensor';\nimport {DataType, TensorLike} from './types';\nimport {assert, flatten, inferDtype, isTypedArray, toTypedArray} from './util';\n\nexport function inferShape(val: TensorLike, dtype?: DataType): number[] {\n let firstElem: typeof val = val;\n\n if (isTypedArray(val)) {\n return dtype === 'string' ? [] : [val.length];\n }\n if (!Array.isArray(val)) {\n return []; // Scalar.\n }\n const shape: number[] = [];\n\n while (Array.isArray(firstElem) ||\n isTypedArray(firstElem) && dtype !== 'string') {\n shape.push(firstElem.length);\n firstElem = firstElem[0];\n }\n if (Array.isArray(val) &&\n env().getBool('TENSORLIKE_CHECK_SHAPE_CONSISTENCY')) {\n deepAssertShapeConsistency(val, shape, []);\n }\n\n return shape;\n}\n\nfunction deepAssertShapeConsistency(\n val: TensorLike, shape: number[], indices: number[]) {\n indices = indices || [];\n if (!(Array.isArray(val)) && !isTypedArray(val)) {\n assert(\n shape.length === 0,\n () => `Element arr[${indices.join('][')}] is a primitive, ` +\n `but should be an array/TypedArray of ${shape[0]} elements`);\n return;\n }\n assert(\n shape.length > 0,\n () => `Element arr[${indices.join('][')}] should be a primitive, ` +\n `but is an array of ${val.length} elements`);\n assert(\n val.length === shape[0],\n () => `Element arr[${indices.join('][')}] should have ${shape[0]} ` +\n `elements, but has ${val.length} elements`);\n const subShape = shape.slice(1);\n for (let i = 0; i < val.length; ++i) {\n deepAssertShapeConsistency(val[i], subShape, indices.concat(i));\n }\n}\n\nfunction assertDtype(\n expectedDtype: DataType|'numeric', actualDType: DataType, argName: string,\n functionName: string) {\n if (expectedDtype == null) {\n return;\n }\n if (expectedDtype !== 'numeric' && expectedDtype !== actualDType ||\n expectedDtype === 'numeric' && actualDType === 'string') {\n throw new Error(\n `Argument '${argName}' passed to '${functionName}' must ` +\n `be ${expectedDtype} tensor, but got ${actualDType} tensor`);\n }\n}\n\nexport function convertToTensor(\n x: T|TensorLike, argName: string, functionName: string,\n parseAsDtype: DataType|'numeric' = 'numeric'): T {\n if (x instanceof Tensor) {\n assertDtype(parseAsDtype, x.dtype, argName, functionName);\n return x;\n }\n let inferredDtype = inferDtype(x);\n // If the user expects a bool/int/float, use that info to update the\n // inferredDtype when it is not a string.\n if (inferredDtype !== 'string' &&\n ['bool', 'int32', 'float32'].indexOf(parseAsDtype) >= 0) {\n inferredDtype = parseAsDtype as DataType;\n }\n assertDtype(parseAsDtype, inferredDtype, argName, functionName);\n\n if ((x == null) ||\n (!isTypedArray(x) && !Array.isArray(x) && typeof x !== 'number' &&\n typeof x !== 'boolean' && typeof x !== 'string')) {\n const type = x == null ? 'null' : (x as {}).constructor.name;\n throw new Error(\n `Argument '${argName}' passed to '${functionName}' must be a ` +\n `Tensor or TensorLike, but got '${type}'`);\n }\n const inferredShape = inferShape(x, inferredDtype);\n if (!isTypedArray(x) && !Array.isArray(x)) {\n x = [x] as number[];\n }\n const skipTypedArray = true;\n const values = inferredDtype !== 'string' ?\n toTypedArray(x, inferredDtype as DataType) :\n flatten(x as string[], [], skipTypedArray) as string[];\n return ENGINE.makeTensor(values, inferredShape, inferredDtype) as T;\n}\n\nexport function convertToTensorArray(\n arg: Array, argName: string, functionName: string,\n parseAsDtype: DataType|'numeric' = 'numeric'): T[] {\n if (!Array.isArray(arg)) {\n throw new Error(\n `Argument ${argName} passed to ${functionName} must be a ` +\n '`Tensor[]` or `TensorLike[]`');\n }\n const tensors = arg as T[];\n return tensors.map(\n (t, i) => convertToTensor(t, `${argName}[${i}]`, functionName),\n parseAsDtype);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\n\nexport const OP_SCOPE_SUFFIX = '__op';\n\n/**\n * Used for wrapping functions that perform math operations on\n * Tensors. The function will be wrapped in a named scope that cleans all\n * memory usage after the function is done.\n */\nexport function op(f: {[name: string]: T}): T {\n const keys = Object.keys(f);\n if (keys.length !== 1) {\n throw new Error(\n `Please provide an object with a single key ` +\n `(operation name) mapping to a function. Got an object with ` +\n `${keys.length} keys.`);\n }\n\n let opName = keys[0];\n const fn = f[opName];\n\n // Strip the underscore from the end of the function name.\n if (opName.endsWith('_')) {\n opName = opName.substring(0, opName.length - 1);\n }\n\n // add an __op suffix to distinguish ops from kernels in tf.profile\n opName = opName + OP_SCOPE_SUFFIX;\n\n // tslint:disable-next-line:no-any\n const f2 = (...args: any[]) => {\n ENGINE.startScope(opName);\n try {\n const result = fn(...args);\n if (result instanceof Promise) {\n console.error('Cannot return a Promise inside of tidy.');\n }\n ENGINE.endScope(result);\n return result;\n } catch (ex) {\n ENGINE.endScope(null);\n throw ex;\n }\n };\n Object.defineProperty(f2, 'name', {value: opName, configurable: true});\n\n // tslint:disable-next-line:no-any\n return f2 as any as T;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE, ForwardFunc} from '../engine';\nimport {Complex, ComplexInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Converts two real numbers to a complex number.\n *\n * Given a tensor `real` representing the real part of a complex number, and a\n * tensor `imag` representing the imaginary part of a complex number, this\n * operation returns complex numbers elementwise of the form [r0, i0, r1, i1],\n * where r represents the real part and i represents the imag part.\n *\n * The input tensors real and imag must have the same shape.\n *\n * ```js\n * const real = tf.tensor1d([2.25, 3.25]);\n * const imag = tf.tensor1d([4.75, 5.75]);\n * const complex = tf.complex(real, imag);\n *\n * complex.print();\n * ```\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction complex_(real: T|TensorLike, imag: T|TensorLike): T {\n const $real = convertToTensor(real, 'real', 'complex');\n const $imag = convertToTensor(imag, 'imag', 'complex');\n util.assertShapesMatch(\n $real.shape, $imag.shape,\n `real and imag shapes, ${$real.shape} and ${$imag.shape}, ` +\n `must match in call to tf.complex().`);\n\n const forward: ForwardFunc = (backend) => {\n return backend.complex($real, $imag);\n };\n const inputs: ComplexInputs = {real: $real, imag: $imag};\n return ENGINE.runKernelFunc(\n forward, inputs as {} as NamedTensorMap, null /* gradient */,\n Complex) as T;\n}\n\nexport const complex = op({complex_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tensor} from '../tensor';\nimport {TensorLike, TypedArray} from '../types';\nimport {DataType} from '../types';\nimport {assert, assertNonNegativeIntegerDimensions, flatten, inferDtype, isTypedArray, sizeFromShape, toTypedArray} from '../util';\n\n/** This is shared code across all tensor creation methods. */\nexport function makeTensor(\n values: TensorLike, shape: number[], inferredShape: number[],\n dtype?: DataType): Tensor {\n if (dtype == null) {\n dtype = inferDtype(values);\n }\n if (dtype === 'complex64') {\n throw new Error(\n `Cannot construct a complex64 tensor directly. ` +\n `Please use tf.complex(real, imag).`);\n }\n if (!isTypedArray(values) && !Array.isArray(values) &&\n typeof values !== 'number' && typeof values !== 'boolean' &&\n typeof values !== 'string') {\n throw new Error(\n 'values passed to tensor(values) must be a number/boolean/string or ' +\n 'an array of numbers/booleans/strings, or a TypedArray');\n }\n if (shape != null) {\n assertNonNegativeIntegerDimensions(shape);\n\n const providedSize = sizeFromShape(shape);\n const inferredSize = sizeFromShape(inferredShape);\n assert(\n providedSize === inferredSize,\n () =>\n `Based on the provided shape, [${shape}], the tensor should have ` +\n `${providedSize} values but has ${inferredSize}`);\n\n for (let i = 0; i < inferredShape.length; ++i) {\n const inferred = inferredShape[i];\n const flatDimsDontMatch = i === inferredShape.length - 1 ?\n inferred !== sizeFromShape(shape.slice(i)) :\n true;\n assert(\n inferredShape[i] === shape[i] || !flatDimsDontMatch,\n () => `Error creating a new Tensor. Inferred shape ` +\n `(${inferredShape}) does not match the provided ` +\n `shape (${shape}). `);\n }\n }\n\n if (!isTypedArray(values) && !Array.isArray(values)) {\n values = [values] as number[];\n }\n\n shape = shape || inferredShape;\n values = dtype !== 'string' ?\n toTypedArray(values, dtype) :\n flatten(values as string[], [], true) as string[];\n return ENGINE.makeTensor(values as TypedArray, shape, dtype);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {inferShape} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {DataType, Rank, ShapeMap} from '../types';\n\nimport {makeTensor} from './tensor_ops_util';\n\n/**\n * Creates a `tf.Tensor` with the provided values, shape and dtype.\n *\n * ```js\n * // Pass an array of values to create a vector.\n * tf.tensor([1, 2, 3, 4]).print();\n * ```\n *\n * ```js\n * // Pass a nested array of values to make a matrix or a higher\n * // dimensional tensor.\n * tf.tensor([[1, 2], [3, 4]]).print();\n * ```\n *\n * ```js\n * // Pass a flat array and specify a shape yourself.\n * tf.tensor([1, 2, 3, 4], [2, 2]).print();\n * ```\n *\n * @param values The values of the tensor. Can be nested array of numbers,\n * or a flat array, or a `TypedArray`. If the values are strings,\n * they will be encoded as utf-8 and kept as `Uint8Array[]`.\n * @param shape The shape of the tensor. Optional. If not provided,\n * it is inferred from `values`.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function tensor(\n values: TensorLike, shape?: ShapeMap[R], dtype?: DataType): Tensor {\n const inferredShape = inferShape(values, dtype);\n return makeTensor(values, shape, inferredShape, dtype) as Tensor;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/* Type definitions for exporting and importing of models. */\n\n/**\n * A map from Tensor dtype to number of bytes per element of the Tensor.\n */\nexport const DTYPE_VALUE_SIZE_MAP: {[dtype: string]: number} = {\n 'float32': 4,\n 'float16': 2,\n 'int32': 4,\n 'uint16': 2,\n 'uint8': 1,\n 'bool': 1,\n 'complex64': 8\n};\n\n/**\n * A weight manifest.\n *\n * The weight manifest consists of an ordered list of weight-manifest groups.\n * Each weight-manifest group (\"group\" for short hereafter) consists of a\n * number of weight values stored in a number of paths.\n * See the documentation of `WeightManifestGroupConfig` below for more details.\n */\nexport declare type WeightsManifestConfig = WeightsManifestGroupConfig[];\n\n/**\n * A weight-manifest group.\n *\n * Consists of an ordered list of weight values encoded in binary format,\n * stored in an ordered list of paths.\n */\nexport declare interface WeightsManifestGroupConfig {\n /**\n * An ordered list of paths.\n *\n * Paths are intentionally abstract in order to be general. For example, they\n * can be relative URL paths or relative paths on the file system.\n */\n paths: string[];\n\n /**\n * Specifications of the weights stored in the paths.\n */\n weights: WeightsManifestEntry[];\n}\n\n/**\n * Group to which the weight belongs.\n *\n * - 'optimizer': Weight from a stateful optimizer.\n */\nexport type WeightGroup = 'model'|'optimizer';\n\n/**\n * An entry in the weight manifest.\n *\n * The entry contains specification of a weight.\n */\nexport declare interface WeightsManifestEntry {\n /**\n * Name of the weight, e.g., 'Dense_1/bias'\n */\n name: string;\n\n /**\n * Shape of the weight.\n */\n shape: number[];\n\n /**\n * Data type of the weight.\n */\n dtype: 'float32'|'int32'|'bool'|'string'|'complex64';\n\n /**\n * Type of the weight.\n *\n * Optional.\n *\n * The value 'optimizer' indicates the weight belongs to an optimizer\n * (i.e., used only during model training and not during inference).\n */\n group?: WeightGroup;\n\n /**\n * Information for dequantization of the weight.\n */\n quantization?: {\n scale?: number, // The scaling constant to multiply by.\n min?: number, // The (possibly nudged) minimum weight to add.\n dtype: 'uint16'|'uint8'|'float16' // The dtype of the quantized weights.\n };\n}\n\n/**\n * Options for saving a model.\n * @innamespace io\n */\nexport interface SaveConfig {\n /**\n * Whether to save only the trainable weights of the model, ignoring the\n * non-trainable ones.\n */\n trainableOnly?: boolean;\n\n /**\n * Whether the optimizer will be saved (if exists).\n *\n * Default: `false`.\n */\n includeOptimizer?: boolean;\n}\n\n/**\n * Result of a saving operation.\n */\nexport interface SaveResult {\n /**\n * Information about the model artifacts saved.\n */\n modelArtifactsInfo: ModelArtifactsInfo;\n\n /**\n * HTTP responses from the server that handled the model-saving request (if\n * any). This is applicable only to server-based saving routes.\n */\n responses?: Response[];\n\n /**\n * Error messages and related data (if any).\n */\n errors?: Array<{}|string>;\n}\n\nexport declare interface ModelArtifactsInfo {\n /**\n * Timestamp for when the model is saved.\n */\n dateSaved: Date;\n\n /**\n * TODO (cais,yassogba) consider removing GraphDef as GraphDefs now\n * come in a JSON format and none of our IOHandlers support a non json\n * format. We could conder replacing this with 'Binary' if we want to\n * allow future handlers to save to non json formats (though they will\n * probably want more information than 'Binary').\n * Type of the model topology\n *\n * Type of the model topology\n *\n * Possible values:\n * - JSON: JSON config (human-readable, e.g., Keras JSON).\n * - GraphDef: TensorFlow\n * [GraphDef](https://www.tensorflow.org/extend/tool_developers/#graphdef)\n * protocol buffer (binary).\n */\n modelTopologyType: 'JSON'|'GraphDef';\n\n /**\n * Size of model topology (Keras JSON or GraphDef), in bytes.\n */\n modelTopologyBytes?: number;\n\n /**\n * Size of weight specification or manifest, in bytes.\n */\n weightSpecsBytes?: number;\n\n /**\n * Size of weight value data, in bytes.\n */\n weightDataBytes?: number;\n}\n\n/** Model training configuration. */\nexport declare interface TrainingConfig {\n // TODO(cais): Tighten the typing once keras spec is available to tfjs-core.\n // See\n // tslint:disable-next-line:max-line-length\n // https://github.com/tensorflow/tfjs-layers/blob/master/src/keras_format/training_config.ts\n /** Optimizer used for the model training. */\n optimizer_config: {};\n\n // TODO(cais): Tighten the typing once keras spec is available to tfjs-core.\n /** Loss function(s) for the model's output(s). */\n loss: string|string[]|{[key: string]: string};\n\n // TODO(cais): Tighten the typing once keras spec is available to tfjs-core.\n /** Metric function(s) for the model's output(s). */\n metrics?: string[]|{[key: string]: string};\n\n // TODO(cais): Tighten the typing once keras spec is available to tfjs-core.\n weighted_metrics?: string[];\n\n // TODO(cais): Tighten the typing once keras spec is available to tfjs-core.\n sample_weight_mode?: string;\n\n loss_weights?: number[]|{[key: string]: number};\n}\n\n/**\n * The serialized artifacts of a model, including topology and weights.\n *\n * The `modelTopology`, `trainingConfig`, `weightSpecs` and `weightData` fields\n * of this interface are optional, in order to support topology- or weights-only\n * saving and loading.\n *\n * Note this interface is used internally in IOHandlers. For the file format\n * written to disk as `model.json`, see `ModelJSON`.\n */\nexport declare interface ModelArtifacts {\n /**\n * Model topology.\n *\n * For Keras-style `tf.Model`s, this is a JSON object.\n * For TensorFlow-style models (e.g., `SavedModel`), this is the JSON\n * encoding of the `GraphDef` protocol buffer.\n */\n modelTopology?: {}|ArrayBuffer;\n\n /**\n * Serialized configuration for the model's training.\n */\n trainingConfig?: TrainingConfig;\n\n /**\n * Weight specifications.\n *\n * This corresponds to the weightsData below.\n */\n weightSpecs?: WeightsManifestEntry[];\n\n /**\n * Binary buffer for all weight values concatenated in the order specified\n * by `weightSpecs`.\n */\n weightData?: ArrayBuffer;\n\n /**\n * Hard-coded format name for models saved from TensorFlow.js or converted\n * by TensorFlow.js Converter.\n */\n format?: string;\n\n /**\n * What library is responsible for originally generating this artifact.\n *\n * Used for debugging purposes. E.g., 'TensorFlow.js v1.0.0'.\n */\n generatedBy?: string;\n\n /**\n * What library or tool is responsible for converting the original model\n * to this format, applicable only if the model is output by a converter.\n *\n * Used for debugging purposes. E.g., 'TensorFlow.js Converter v1.0.0'.\n *\n * A value of `null` means the model artifacts are generated without any\n * conversion process (e.g., saved directly from a TensorFlow.js\n * `tf.LayersModel` instance.)\n */\n convertedBy?: string|null;\n\n /**\n * User-defined metadata about the model.\n */\n userDefinedMetadata?: {};\n\n /**\n * Initializer for the model.\n */\n modelInitializer?: {};\n}\n\n/**\n * The on-disk format of the `model.json` file.\n *\n * TF.js 1.0 always populates the optional fields when writing model.json.\n * Prior versions did not provide those fields.\n */\nexport declare interface ModelJSON {\n /**\n * Model topology.\n *\n * For Keras-style `tf.Model`s, this is a JSON object.\n * For TensorFlow-style models (e.g., `SavedModel`), this is the JSON\n * encoding of the `GraphDef` protocol buffer.\n */\n modelTopology: {};\n\n /** Model training configuration. */\n trainingConfig?: TrainingConfig;\n\n /**\n * Weights manifest.\n *\n * The weights manifest consists of an ordered list of weight-manifest\n * groups. Each weight-manifest group consists of a number of weight values\n * stored in a number of paths. See the documentation of\n * `WeightsManifestConfig` for more details.\n */\n weightsManifest: WeightsManifestConfig;\n\n /**\n * Hard-coded format name for models saved from TensorFlow.js or converted\n * by TensorFlow.js Converter.\n */\n format?: string;\n\n /**\n * What library is responsible for originally generating this artifact.\n *\n * Used for debugging purposes. E.g., 'TensorFlow.js v1.0.0'.\n */\n generatedBy?: string;\n\n /**\n * What library or tool is responsible for converting the original model\n * to this format, applicable only if the model is output by a converter.\n *\n * Used for debugging purposes. E.g., 'TensorFlow.js Converter v1.0.0'.\n *\n * A value of `null` means the model artifacts are generated without any\n * conversion process (e.g., saved directly from a TensorFlow.js\n * `tf.LayersModel` instance.)\n */\n convertedBy?: string|null;\n\n /**\n * User-defined metadata about the model.\n */\n userDefinedMetadata?: {};\n\n /**\n * Initializer for the model.\n */\n modelInitializer?: {};\n}\n\n/**\n * Type definition for handlers of loading operations.\n */\nexport type LoadHandler = () => Promise;\n\n/**\n * Type definition for handlers of saving operations.\n */\nexport type SaveHandler = (modelArtifact: ModelArtifacts) =>\n Promise;\n\n/**\n * Interface for a model import/export handler.\n *\n * The `save` and `load` handlers are both optional, in order to allow handlers\n * that support only saving or loading.\n */\n// tslint:disable-next-line:interface-name\nexport interface IOHandler {\n save?: SaveHandler;\n load?: LoadHandler;\n}\n\n/**\n * An interface for the manager of a model store.\n *\n * A model store is defined as a storage medium on which multiple models can\n * be stored. Each stored model has a unique `path` as its identifier.\n * A `ModelStoreManager` for the store allows actions including\n *\n * - Listing the models stored in the store.\n * - Deleting a model from the store.\n */\nexport interface ModelStoreManager {\n /**\n * List all models in the model store.\n *\n * @returns A dictionary mapping paths of existing models to their\n * model artifacts info. Model artifacts info include type of the model's\n * topology, byte sizes of the topology, weights, etc.\n */\n listModels(): Promise<{[path: string]: ModelArtifactsInfo}>;\n\n /**\n * Remove a model specified by `path`.\n *\n * @param path\n * @returns ModelArtifactsInfo of the deleted model (if and only if deletion\n * is successful).\n * @throws Error if deletion fails, e.g., if no model exists at `path`.\n */\n removeModel(path: string): Promise;\n}\n\n/**\n * Callback for the progress of a long-running action such as an HTTP\n * request for a large binary object.\n *\n * `fraction` should be a number in the [0, 1] interval, indicating how\n * much of the action has completed.\n */\nexport type OnProgressCallback = (fraction: number) => void;\n\n/** @innamespace io */\nexport interface LoadOptions {\n /**\n * RequestInit (options) for HTTP requests.\n *\n * For detailed information on the supported fields, see\n * [https://developer.mozilla.org/en-US/docs/Web/API/Request/Request](\n * https://developer.mozilla.org/en-US/docs/Web/API/Request/Request)\n */\n requestInit?: RequestInit;\n\n /**\n * Progress callback.\n */\n onProgress?: OnProgressCallback;\n\n /**\n * A function used to override the `window.fetch` function.\n */\n fetchFunc?: Function;\n\n /**\n * Strict loading model: whether extraneous weights or missing\n * weights should trigger an `Error`.\n *\n * If `true`, require that the provided weights exactly match those\n * required by the layers. `false` means that both extra weights\n * and missing weights will be silently ignored.\n *\n * Default: `true`.\n */\n strict?: boolean;\n\n /**\n * Path prefix for weight files, by default this is calculated from the\n * path of the model JSON file.\n *\n * For instance, if the path to the model JSON file is\n * `http://localhost/foo/model.json`, then the default path prefix will be\n * `http://localhost/foo/`. If a weight file has the path value\n * `group1-shard1of2` in the weight manifest, then the weight file will be\n * loaded from `http://localhost/foo/group1-shard1of2` by default. However,\n * if you provide a `weightPathPrefix` value of\n * `http://localhost/foo/alt-weights`, then the weight file will be loaded\n * from the path `http://localhost/foo/alt-weights/group1-shard1of2` instead.\n */\n weightPathPrefix?: string;\n\n /**\n * Whether the module or model is to be loaded from TF Hub.\n *\n * Setting this to `true` allows passing a TF-Hub module URL, omitting the\n * standard model file name and the query parameters.\n *\n * Default: `false`.\n */\n fromTFHub?: boolean;\n\n /**\n * An async function to convert weight file name to URL. The weight file\n * names are stored in model.json's weightsManifest.paths field. By default we\n * consider weight files are colocated with the model.json file. For example:\n * model.json URL: https://www.google.com/models/1/model.json\n * group1-shard1of1.bin url:\n * https://www.google.com/models/1/group1-shard1of1.bin\n *\n * With this func you can convert the weight file name to any URL.\n */\n weightUrlConverter?: (weightFileName: string) => Promise;\n}\n\n/**\n * Additional options for Platform.fetch\n */\nexport interface RequestDetails {\n /**\n * Is this request for a binary file (as opposed to a json file)\n */\n isBinary?: boolean;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {complex} from '../ops/complex';\n\nimport {tensor} from '../ops/tensor';\nimport {NamedTensor, NamedTensorMap} from '../tensor_types';\nimport {TypedArray} from '../types';\nimport {sizeFromShape} from '../util';\n\nimport {DTYPE_VALUE_SIZE_MAP, ModelArtifacts, ModelArtifactsInfo, WeightGroup, WeightsManifestEntry} from './types';\n\n/** Number of bytes reserved for the length of the string. (32bit integer). */\nconst NUM_BYTES_STRING_LENGTH = 4;\n\n/**\n * Encode a map from names to weight values as an ArrayBuffer, along with an\n * `Array` of `WeightsManifestEntry` as specification of the encoded weights.\n *\n * This function does not perform sharding.\n *\n * This function is the reverse of `decodeWeights`.\n *\n * @param tensors A map (\"dict\") from names to tensors.\n * @param group Group to which the weights belong (optional).\n * @returns A `Promise` of\n * - A flat `ArrayBuffer` with all the binary values of the `Tensor`s\n * concatenated.\n * - An `Array` of `WeightManifestEntry`s, carrying information including\n * tensor names, `dtype`s and shapes.\n * @throws Error: on unsupported tensor `dtype`.\n */\nexport async function encodeWeights(\n tensors: NamedTensorMap|NamedTensor[], group?: WeightGroup):\n Promise<{data: ArrayBuffer, specs: WeightsManifestEntry[]}> {\n // TODO(adarob, cais): Support quantization.\n const specs: WeightsManifestEntry[] = [];\n const dataPromises: Array> = [];\n\n const names: string[] = Array.isArray(tensors) ?\n tensors.map(tensor => tensor.name) :\n Object.keys(tensors);\n\n for (let i = 0; i < names.length; ++i) {\n const name = names[i];\n const t = Array.isArray(tensors) ? tensors[i].tensor : tensors[name];\n if (t.dtype !== 'float32' && t.dtype !== 'int32' && t.dtype !== 'bool' &&\n t.dtype !== 'string' && t.dtype !== 'complex64') {\n throw new Error(`Unsupported dtype in weight '${name}': ${t.dtype}`);\n }\n const spec: WeightsManifestEntry = {name, shape: t.shape, dtype: t.dtype};\n if (t.dtype === 'string') {\n const utf8bytes = new Promise(async resolve => {\n const vals = await t.bytes() as Uint8Array[];\n const totalNumBytes = vals.reduce((p, c) => p + c.length, 0) +\n NUM_BYTES_STRING_LENGTH * vals.length;\n const bytes = new Uint8Array(totalNumBytes);\n let offset = 0;\n for (let i = 0; i < vals.length; i++) {\n const val = vals[i];\n const bytesOfLength =\n new Uint8Array(new Uint32Array([val.length]).buffer);\n bytes.set(bytesOfLength, offset);\n offset += NUM_BYTES_STRING_LENGTH;\n bytes.set(val, offset);\n offset += val.length;\n }\n resolve(bytes);\n });\n dataPromises.push(utf8bytes);\n } else {\n dataPromises.push(t.data());\n }\n if (group != null) {\n spec.group = group;\n }\n specs.push(spec);\n }\n\n const tensorValues = await Promise.all(dataPromises);\n return {data: concatenateTypedArrays(tensorValues), specs};\n}\n\n/**\n * Decode flat ArrayBuffer as weights.\n *\n * This function does not handle sharding.\n *\n * This function is the reverse of `encodeWeights`.\n *\n * @param buffer A flat ArrayBuffer carrying the binary values of the tensors\n * concatenated in the order specified in `specs`.\n * @param specs Specifications of the names, dtypes and shapes of the tensors\n * whose value are encoded by `buffer`.\n * @return A map from tensor name to tensor value, with the names corresponding\n * to names in `specs`.\n * @throws Error, if any of the tensors has unsupported dtype.\n */\nexport function decodeWeights(\n buffer: ArrayBuffer, specs: WeightsManifestEntry[]): NamedTensorMap {\n // TODO(adarob, cais): Support quantization.\n const out: NamedTensorMap = {};\n let float16Decode: (buffer: Uint16Array) => Float32Array | undefined;\n let offset = 0;\n for (const spec of specs) {\n const name = spec.name;\n const dtype = spec.dtype;\n const shape = spec.shape;\n const size = sizeFromShape(shape);\n let values: TypedArray|string[]|Uint8Array[];\n\n if ('quantization' in spec) {\n const quantization = spec.quantization;\n if (quantization.dtype === 'uint8' || quantization.dtype === 'uint16') {\n if (!('min' in quantization && 'scale' in quantization)) {\n throw new Error(\n `Weight ${spec.name} with quantization ${quantization.dtype} ` +\n `doesn't have corresponding metadata min and scale.`);\n }\n } else if (quantization.dtype === 'float16') {\n if (dtype !== 'float32') {\n throw new Error(\n `Weight ${spec.name} is quantized with ${quantization.dtype} ` +\n `which only supports weights of type float32 not ${dtype}.`);\n }\n } else {\n throw new Error(\n `Weight ${spec.name} has unknown ` +\n `quantization dtype ${quantization.dtype}. ` +\n `Supported quantization dtypes are: ` +\n `'uint8', 'uint16', and 'float16'.`);\n }\n const quantizationSizeFactor = DTYPE_VALUE_SIZE_MAP[quantization.dtype];\n const byteBuffer =\n buffer.slice(offset, offset + size * quantizationSizeFactor);\n const quantizedArray = (quantization.dtype === 'uint8') ?\n new Uint8Array(byteBuffer) :\n new Uint16Array(byteBuffer);\n if (dtype === 'float32') {\n if (quantization.dtype === 'uint8' || quantization.dtype === 'uint16') {\n values = new Float32Array(quantizedArray.length);\n for (let i = 0; i < quantizedArray.length; i++) {\n const v = quantizedArray[i];\n values[i] = v * quantization.scale + quantization.min;\n }\n } else if (quantization.dtype === 'float16') {\n if (float16Decode === undefined) {\n float16Decode = getFloat16Decoder();\n }\n values = float16Decode(quantizedArray as Uint16Array);\n } else {\n throw new Error(\n `Unsupported quantization type ${quantization.dtype} ` +\n `for weight type float32.`);\n }\n } else if (dtype === 'int32') {\n if (quantization.dtype !== 'uint8' && quantization.dtype !== 'uint16') {\n throw new Error(\n `Unsupported quantization type ${quantization.dtype} ` +\n `for weight type int32.`);\n }\n values = new Int32Array(quantizedArray.length);\n for (let i = 0; i < quantizedArray.length; i++) {\n const v = quantizedArray[i];\n values[i] = Math.round(v * quantization.scale + quantization.min);\n }\n } else {\n throw new Error(`Unsupported dtype in weight '${name}': ${dtype}`);\n }\n offset += size * quantizationSizeFactor;\n } else if (dtype === 'string') {\n const size = sizeFromShape(spec.shape);\n values = [];\n for (let i = 0; i < size; i++) {\n const byteLength = new Uint32Array(\n buffer.slice(offset, offset + NUM_BYTES_STRING_LENGTH))[0];\n offset += NUM_BYTES_STRING_LENGTH;\n const bytes = new Uint8Array(buffer.slice(offset, offset + byteLength));\n (values as Uint8Array[]).push(bytes);\n offset += byteLength;\n }\n } else {\n const dtypeFactor = DTYPE_VALUE_SIZE_MAP[dtype];\n const byteBuffer = buffer.slice(offset, offset + size * dtypeFactor);\n\n if (dtype === 'float32') {\n values = new Float32Array(byteBuffer);\n } else if (dtype === 'int32') {\n values = new Int32Array(byteBuffer);\n } else if (dtype === 'bool') {\n values = new Uint8Array(byteBuffer);\n } else if (dtype === 'complex64') {\n values = new Float32Array(byteBuffer);\n const real = new Float32Array(values.length / 2);\n const image = new Float32Array(values.length / 2);\n for (let i = 0; i < real.length; i++) {\n real[i] = values[i * 2];\n image[i] = values[i * 2 + 1];\n }\n const realTensor = tensor(real, shape, 'float32');\n const imageTensor = tensor(image, shape, 'float32');\n out[name] = complex(realTensor, imageTensor);\n } else {\n throw new Error(`Unsupported dtype in weight '${name}': ${dtype}`);\n }\n offset += size * dtypeFactor;\n }\n if (dtype !== 'complex64') {\n out[name] = tensor(values, shape, dtype);\n }\n }\n return out;\n}\n\n/**\n * Concatenate TypedArrays into an ArrayBuffer.\n */\nexport function concatenateTypedArrays(xs: TypedArray[]): ArrayBuffer {\n // TODO(adarob, cais): Support quantization.\n if (xs === null) {\n throw new Error(`Invalid input value: ${JSON.stringify(xs)}`);\n }\n\n let totalByteLength = 0;\n\n // `normalizedXs` is here for this reason: a `TypedArray`'s `buffer'\n // can have a different byte length from that of the `TypedArray` itself,\n // for example, when the `TypedArray` is created from an offset in an\n // `ArrayBuffer`. `normliazedXs` holds `TypedArray`s whose `buffer`s match\n // the `TypedArray` in byte length. If an element of `xs` does not show\n // this property, a new `TypedArray` that satisfy this property will be\n // constructed and pushed into `normalizedXs`.\n const normalizedXs: TypedArray[] = [];\n xs.forEach((x: TypedArray) => {\n totalByteLength += x.byteLength;\n // tslint:disable:no-any\n normalizedXs.push(\n x.byteLength === x.buffer.byteLength ? x :\n new (x.constructor as any)(x));\n if (!(x as any instanceof Float32Array || x as any instanceof Int32Array ||\n x as any instanceof Uint8Array)) {\n throw new Error(`Unsupported TypedArray subtype: ${x.constructor.name}`);\n }\n // tslint:enable:no-any\n });\n\n const y = new Uint8Array(totalByteLength);\n let offset = 0;\n normalizedXs.forEach((x: TypedArray) => {\n y.set(new Uint8Array(x.buffer), offset);\n offset += x.byteLength;\n });\n\n return y.buffer;\n}\n\n// Use Buffer on Node.js instead of Blob/atob/btoa\nconst useNodeBuffer = typeof Buffer !== 'undefined' &&\n (typeof Blob === 'undefined' || typeof atob === 'undefined' ||\n typeof btoa === 'undefined');\n\n/**\n * Calculate the byte length of a JavaScript string.\n *\n * Note that a JavaScript string can contain wide characters, therefore the\n * length of the string is not necessarily equal to the byte length.\n *\n * @param str Input string.\n * @returns Byte length.\n */\nexport function stringByteLength(str: string): number {\n if (useNodeBuffer) {\n return Buffer.byteLength(str);\n }\n return new Blob([str]).size;\n}\n\n/**\n * Encode an ArrayBuffer as a base64 encoded string.\n *\n * @param buffer `ArrayBuffer` to be converted.\n * @returns A string that base64-encodes `buffer`.\n */\nexport function arrayBufferToBase64String(buffer: ArrayBuffer): string {\n if (useNodeBuffer) {\n return Buffer.from(buffer).toString('base64');\n }\n const buf = new Uint8Array(buffer);\n let s = '';\n for (let i = 0, l = buf.length; i < l; i++) {\n s += String.fromCharCode(buf[i]);\n }\n return btoa(s);\n}\n\n/**\n * Decode a base64 string as an ArrayBuffer.\n *\n * @param str Base64 string.\n * @returns Decoded `ArrayBuffer`.\n */\nexport function base64StringToArrayBuffer(str: string): ArrayBuffer {\n if (useNodeBuffer) {\n const buf = Buffer.from(str, 'base64');\n return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);\n }\n const s = atob(str);\n const buffer = new Uint8Array(s.length);\n for (let i = 0; i < s.length; ++i) {\n buffer.set([s.charCodeAt(i)], i);\n }\n return buffer.buffer;\n}\n\n/**\n * Concatenate a number of ArrayBuffers into one.\n *\n * @param buffers A number of array buffers to concatenate.\n * @returns Result of concatenating `buffers` in order.\n */\nexport function concatenateArrayBuffers(buffers: ArrayBuffer[]): ArrayBuffer {\n if (buffers.length === 1) {\n return buffers[0];\n }\n\n let totalByteLength = 0;\n buffers.forEach((buffer: ArrayBuffer) => {\n totalByteLength += buffer.byteLength;\n });\n\n const temp = new Uint8Array(totalByteLength);\n let offset = 0;\n buffers.forEach((buffer: ArrayBuffer) => {\n temp.set(new Uint8Array(buffer), offset);\n offset += buffer.byteLength;\n });\n return temp.buffer;\n}\n\n/**\n * Get the basename of a path.\n *\n * Behaves in a way analogous to Linux's basename command.\n *\n * @param path\n */\nexport function basename(path: string): string {\n const SEPARATOR = '/';\n path = path.trim();\n while (path.endsWith(SEPARATOR)) {\n path = path.slice(0, path.length - 1);\n }\n const items = path.split(SEPARATOR);\n return items[items.length - 1];\n}\n\n/**\n * Populate ModelArtifactsInfo fields for a model with JSON topology.\n * @param modelArtifacts\n * @returns A ModelArtifactsInfo object.\n */\nexport function getModelArtifactsInfoForJSON(modelArtifacts: ModelArtifacts):\n ModelArtifactsInfo {\n if (modelArtifacts.modelTopology instanceof ArrayBuffer) {\n throw new Error('Expected JSON model topology, received ArrayBuffer.');\n }\n\n return {\n dateSaved: new Date(),\n modelTopologyType: 'JSON',\n modelTopologyBytes: modelArtifacts.modelTopology == null ?\n 0 :\n stringByteLength(JSON.stringify(modelArtifacts.modelTopology)),\n weightSpecsBytes: modelArtifacts.weightSpecs == null ?\n 0 :\n stringByteLength(JSON.stringify(modelArtifacts.weightSpecs)),\n weightDataBytes: modelArtifacts.weightData == null ?\n 0 :\n modelArtifacts.weightData.byteLength,\n };\n}\n\n/**\n * Computes mantisa table for casting Float16 to Float32\n * See http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n *\n * @returns Uint32Array, 2048 mantissa lookup values.\n */\nfunction computeFloat16MantisaTable(): Uint32Array {\n const convertMantissa = (i: number): number => {\n let m = i << 13;\n let e = 0;\n\n while ((m & 0x00800000) === 0) {\n e -= 0x00800000;\n m <<= 1;\n }\n m &= ~0x00800000;\n e += 0x38800000;\n\n return m | e;\n };\n\n const mantisaTable = new Uint32Array(2048);\n\n mantisaTable[0] = 0;\n for (let i = 1; i < 1024; i++) {\n mantisaTable[i] = convertMantissa(i);\n }\n for (let i = 1024; i < 2048; i++) {\n mantisaTable[i] = 0x38000000 + ((i - 1024) << 13);\n }\n\n return mantisaTable;\n}\n\n/**\n * Computes exponent table for casting Float16 to Float32\n * See http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n *\n * @returns Uint32Array, 64 exponent lookup values.\n */\nfunction computeFloat16ExponentTable(): Uint32Array {\n const exponentTable = new Uint32Array(64);\n\n exponentTable[0] = 0;\n exponentTable[31] = 0x47800000;\n exponentTable[32] = 0x80000000;\n exponentTable[63] = 0xc7800000;\n for (let i = 1; i < 31; i++) {\n exponentTable[i] = i << 23;\n }\n for (let i = 33; i < 63; i++) {\n exponentTable[i] = 0x80000000 + ((i - 32) << 23);\n }\n\n return exponentTable;\n}\n\n/**\n * Computes offset table for casting Float16 to Float32\n * See http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n *\n * @returns Uint32Array, 6d offset values.\n */\nfunction computeFloat16OffsetTable(): Uint32Array {\n const offsetTable = new Uint32Array(64);\n\n for (let i = 0; i < 64; i++) {\n offsetTable[i] = 1024;\n }\n offsetTable[0] = offsetTable[32] = 0;\n\n return offsetTable;\n}\n\n/**\n * Retrieve a Float16 decoder which will decode a ByteArray of Float16 values\n * to a Float32Array.\n *\n * @returns Function (buffer: Uint16Array) => Float32Array which decodes\n * the Uint16Array of Float16 bytes to a Float32Array.\n */\nexport function getFloat16Decoder(): (buffer: Uint16Array) => Float32Array {\n // Algorithm is based off of\n // http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n\n // Cache lookup tables\n const mantisaTable = computeFloat16MantisaTable();\n const exponentTable = computeFloat16ExponentTable();\n const offsetTable = computeFloat16OffsetTable();\n\n return (quantizedArray: Uint16Array) => {\n const buffer = new ArrayBuffer(4 * quantizedArray.length);\n const bufferUint32View = new Uint32Array(buffer);\n for (let index = 0; index < quantizedArray.length; index++) {\n const float16Bits = quantizedArray[index];\n const float32Bits =\n mantisaTable[offsetTable[float16Bits >> 10] + (float16Bits & 0x3ff)] +\n exponentTable[float16Bits >> 10];\n bufferUint32View[index] = float32Bits;\n }\n return new Float32Array(buffer);\n };\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {IOHandler, LoadOptions} from './types';\n\nexport type IORouter = (url: string|string[], loadOptions?: LoadOptions) =>\n IOHandler;\n\nexport class IORouterRegistry {\n // Singleton instance.\n private static instance: IORouterRegistry;\n\n private saveRouters: IORouter[];\n private loadRouters: IORouter[];\n\n private constructor() {\n this.saveRouters = [];\n this.loadRouters = [];\n }\n\n private static getInstance(): IORouterRegistry {\n if (IORouterRegistry.instance == null) {\n IORouterRegistry.instance = new IORouterRegistry();\n }\n return IORouterRegistry.instance;\n }\n\n /**\n * Register a save-handler router.\n *\n * @param saveRouter A function that maps a URL-like string onto an instance\n * of `IOHandler` with the `save` method defined or `null`.\n */\n static registerSaveRouter(saveRouter: IORouter) {\n IORouterRegistry.getInstance().saveRouters.push(saveRouter);\n }\n\n /**\n * Register a load-handler router.\n *\n * @param loadRouter A function that maps a URL-like string onto an instance\n * of `IOHandler` with the `load` method defined or `null`.\n */\n static registerLoadRouter(loadRouter: IORouter) {\n IORouterRegistry.getInstance().loadRouters.push(loadRouter);\n }\n\n /**\n * Look up IOHandler for saving, given a URL-like string.\n *\n * @param url\n * @returns If only one match is found, an instance of IOHandler with the\n * `save` method defined. If no match is found, `null`.\n * @throws Error, if more than one match is found.\n */\n static getSaveHandlers(url: string|string[]): IOHandler[] {\n return IORouterRegistry.getHandlers(url, 'save');\n }\n\n /**\n * Look up IOHandler for loading, given a URL-like string.\n *\n * @param url\n * @param loadOptions Optional, custom load options.\n * @returns All valid handlers for `url`, given the currently registered\n * handler routers.\n */\n static getLoadHandlers(url: string|string[], loadOptions?: LoadOptions):\n IOHandler[] {\n return IORouterRegistry.getHandlers(url, 'load', loadOptions);\n }\n\n private static getHandlers(\n url: string|string[], handlerType: 'save'|'load',\n loadOptions?: LoadOptions): IOHandler[] {\n const validHandlers: IOHandler[] = [];\n const routers = handlerType === 'load' ?\n IORouterRegistry.getInstance().loadRouters :\n IORouterRegistry.getInstance().saveRouters;\n routers.forEach(router => {\n const handler = router(url, loadOptions);\n if (handler !== null) {\n validHandlers.push(handler);\n }\n });\n return validHandlers;\n }\n}\n\nexport const registerSaveRouter = (loudRouter: IORouter) =>\n IORouterRegistry.registerSaveRouter(loudRouter);\nexport const registerLoadRouter = (loudRouter: IORouter) =>\n IORouterRegistry.registerLoadRouter(loudRouter);\nexport const getSaveHandlers = (url: string|string[]) =>\n IORouterRegistry.getSaveHandlers(url);\nexport const getLoadHandlers =\n (url: string|string[], loadOptions?: LoadOptions) =>\n IORouterRegistry.getLoadHandlers(url, loadOptions);\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport '../flags';\n\nimport {env} from '../environment';\n\nimport {getModelArtifactsInfoForJSON} from './io_utils';\nimport {IORouter, IORouterRegistry} from './router_registry';\nimport {IOHandler, ModelArtifacts, ModelArtifactsInfo, ModelStoreManager, SaveResult} from './types';\n\nconst DATABASE_NAME = 'tensorflowjs';\nconst DATABASE_VERSION = 1;\n\n// Model data and ModelArtifactsInfo (metadata) are stored in two separate\n// stores for efficient access of the list of stored models and their metadata.\n// 1. The object store for model data: topology, weights and weight manifests.\nconst MODEL_STORE_NAME = 'models_store';\n// 2. The object store for ModelArtifactsInfo, including meta-information such\n// as the type of topology (JSON vs binary), byte size of the topology, byte\n// size of the weights, etc.\nconst INFO_STORE_NAME = 'model_info_store';\n\n/**\n * Delete the entire database for tensorflow.js, including the models store.\n */\nexport async function deleteDatabase(): Promise {\n const idbFactory = getIndexedDBFactory();\n\n return new Promise((resolve, reject) => {\n const deleteRequest = idbFactory.deleteDatabase(DATABASE_NAME);\n deleteRequest.onsuccess = () => resolve();\n deleteRequest.onerror = error => reject(error);\n });\n}\n\nfunction getIndexedDBFactory(): IDBFactory {\n if (!env().getBool('IS_BROWSER')) {\n // TODO(cais): Add more info about what IOHandler subtypes are available.\n // Maybe point to a doc page on the web and/or automatically determine\n // the available IOHandlers and print them in the error message.\n throw new Error(\n 'Failed to obtain IndexedDB factory because the current environment' +\n 'is not a web browser.');\n }\n // tslint:disable-next-line:no-any\n const theWindow: any = typeof window === 'undefined' ? self : window;\n const factory = theWindow.indexedDB || theWindow.mozIndexedDB ||\n theWindow.webkitIndexedDB || theWindow.msIndexedDB ||\n theWindow.shimIndexedDB;\n if (factory == null) {\n throw new Error(\n 'The current browser does not appear to support IndexedDB.');\n }\n return factory;\n}\n\nfunction setUpDatabase(openRequest: IDBRequest) {\n const db = openRequest.result as IDBDatabase;\n db.createObjectStore(MODEL_STORE_NAME, {keyPath: 'modelPath'});\n db.createObjectStore(INFO_STORE_NAME, {keyPath: 'modelPath'});\n}\n\n/**\n * IOHandler subclass: Browser IndexedDB.\n *\n * See the doc string of `browserIndexedDB` for more details.\n */\nexport class BrowserIndexedDB implements IOHandler {\n protected readonly indexedDB: IDBFactory;\n protected readonly modelPath: string;\n\n static readonly URL_SCHEME = 'indexeddb://';\n\n constructor(modelPath: string) {\n this.indexedDB = getIndexedDBFactory();\n\n if (modelPath == null || !modelPath) {\n throw new Error(\n 'For IndexedDB, modelPath must not be null, undefined or empty.');\n }\n this.modelPath = modelPath;\n }\n\n async save(modelArtifacts: ModelArtifacts): Promise {\n // TODO(cais): Support saving GraphDef models.\n if (modelArtifacts.modelTopology instanceof ArrayBuffer) {\n throw new Error(\n 'BrowserLocalStorage.save() does not support saving model topology ' +\n 'in binary formats yet.');\n }\n\n return this.databaseAction(this.modelPath, modelArtifacts) as\n Promise;\n }\n\n async load(): Promise {\n return this.databaseAction(this.modelPath) as Promise;\n }\n\n /**\n * Perform database action to put model artifacts into or read model artifacts\n * from IndexedDB object store.\n *\n * Whether the action is put or get depends on whether `modelArtifacts` is\n * specified. If it is specified, the action will be put; otherwise the action\n * will be get.\n *\n * @param modelPath A unique string path for the model.\n * @param modelArtifacts If specified, it will be the model artifacts to be\n * stored in IndexedDB.\n * @returns A `Promise` of `SaveResult`, if the action is put, or a `Promise`\n * of `ModelArtifacts`, if the action is get.\n */\n private databaseAction(modelPath: string, modelArtifacts?: ModelArtifacts):\n Promise {\n return new Promise((resolve, reject) => {\n const openRequest = this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);\n openRequest.onupgradeneeded = () => setUpDatabase(openRequest);\n\n openRequest.onsuccess = () => {\n const db = openRequest.result;\n\n if (modelArtifacts == null) {\n // Read model out from object store.\n const modelTx = db.transaction(MODEL_STORE_NAME, 'readonly');\n const modelStore = modelTx.objectStore(MODEL_STORE_NAME);\n const getRequest = modelStore.get(this.modelPath);\n getRequest.onsuccess = () => {\n if (getRequest.result == null) {\n db.close();\n return reject(new Error(\n `Cannot find model with path '${this.modelPath}' ` +\n `in IndexedDB.`));\n } else {\n resolve(getRequest.result.modelArtifacts);\n }\n };\n getRequest.onerror = error => {\n db.close();\n return reject(getRequest.error);\n };\n modelTx.oncomplete = () => db.close();\n } else {\n // Put model into object store.\n const modelArtifactsInfo: ModelArtifactsInfo =\n getModelArtifactsInfoForJSON(modelArtifacts);\n // First, put ModelArtifactsInfo into info store.\n const infoTx = db.transaction(INFO_STORE_NAME, 'readwrite');\n let infoStore = infoTx.objectStore(INFO_STORE_NAME);\n const putInfoRequest =\n infoStore.put({modelPath: this.modelPath, modelArtifactsInfo});\n let modelTx: IDBTransaction;\n putInfoRequest.onsuccess = () => {\n // Second, put model data into model store.\n modelTx = db.transaction(MODEL_STORE_NAME, 'readwrite');\n const modelStore = modelTx.objectStore(MODEL_STORE_NAME);\n const putModelRequest = modelStore.put({\n modelPath: this.modelPath,\n modelArtifacts,\n modelArtifactsInfo\n });\n putModelRequest.onsuccess = () => resolve({modelArtifactsInfo});\n putModelRequest.onerror = error => {\n // If the put-model request fails, roll back the info entry as\n // well.\n infoStore = infoTx.objectStore(INFO_STORE_NAME);\n const deleteInfoRequest = infoStore.delete(this.modelPath);\n deleteInfoRequest.onsuccess = () => {\n db.close();\n return reject(putModelRequest.error);\n };\n deleteInfoRequest.onerror = error => {\n db.close();\n return reject(putModelRequest.error);\n };\n };\n };\n putInfoRequest.onerror = error => {\n db.close();\n return reject(putInfoRequest.error);\n };\n infoTx.oncomplete = () => {\n if (modelTx == null) {\n db.close();\n } else {\n modelTx.oncomplete = () => db.close();\n }\n };\n }\n };\n openRequest.onerror = error => reject(openRequest.error);\n });\n }\n}\n\nexport const indexedDBRouter: IORouter = (url: string|string[]) => {\n if (!env().getBool('IS_BROWSER')) {\n return null;\n } else {\n if (!Array.isArray(url) && url.startsWith(BrowserIndexedDB.URL_SCHEME)) {\n return browserIndexedDB(url.slice(BrowserIndexedDB.URL_SCHEME.length));\n } else {\n return null;\n }\n }\n};\nIORouterRegistry.registerSaveRouter(indexedDBRouter);\nIORouterRegistry.registerLoadRouter(indexedDBRouter);\n\n/**\n * Creates a browser IndexedDB IOHandler for saving and loading models.\n *\n * ```js\n * const model = tf.sequential();\n * model.add(\n * tf.layers.dense({units: 1, inputShape: [100], activation: 'sigmoid'}));\n *\n * const saveResult = await model.save('indexeddb://MyModel'));\n * console.log(saveResult);\n * ```\n *\n * @param modelPath A unique identifier for the model to be saved. Must be a\n * non-empty string.\n * @returns An instance of `BrowserIndexedDB` (sublcass of `IOHandler`),\n * which can be used with, e.g., `tf.Model.save`.\n */\nexport function browserIndexedDB(modelPath: string): IOHandler {\n return new BrowserIndexedDB(modelPath);\n}\n\nfunction maybeStripScheme(key: string) {\n return key.startsWith(BrowserIndexedDB.URL_SCHEME) ?\n key.slice(BrowserIndexedDB.URL_SCHEME.length) :\n key;\n}\n\nexport class BrowserIndexedDBManager implements ModelStoreManager {\n private indexedDB: IDBFactory;\n\n constructor() {\n this.indexedDB = getIndexedDBFactory();\n }\n\n async listModels(): Promise<{[path: string]: ModelArtifactsInfo}> {\n return new Promise<{[path: string]: ModelArtifactsInfo}>(\n (resolve, reject) => {\n const openRequest =\n this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);\n openRequest.onupgradeneeded = () => setUpDatabase(openRequest);\n\n openRequest.onsuccess = () => {\n const db = openRequest.result;\n const tx = db.transaction(INFO_STORE_NAME, 'readonly');\n const store = tx.objectStore(INFO_STORE_NAME);\n // tslint:disable:max-line-length\n // Need to cast `store` as `any` here because TypeScript's DOM\n // library does not have the `getAll()` method even though the\n // method is supported in the latest version of most mainstream\n // browsers:\n // https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/getAll\n // tslint:enable:max-line-length\n // tslint:disable-next-line:no-any\n const getAllInfoRequest = (store as any).getAll() as IDBRequest;\n getAllInfoRequest.onsuccess = () => {\n const out: {[path: string]: ModelArtifactsInfo} = {};\n for (const item of getAllInfoRequest.result) {\n out[item.modelPath] = item.modelArtifactsInfo;\n }\n resolve(out);\n };\n getAllInfoRequest.onerror = error => {\n db.close();\n return reject(getAllInfoRequest.error);\n };\n tx.oncomplete = () => db.close();\n };\n openRequest.onerror = error => reject(openRequest.error);\n });\n }\n\n async removeModel(path: string): Promise {\n path = maybeStripScheme(path);\n return new Promise((resolve, reject) => {\n const openRequest = this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);\n openRequest.onupgradeneeded = () => setUpDatabase(openRequest);\n\n openRequest.onsuccess = () => {\n const db = openRequest.result;\n const infoTx = db.transaction(INFO_STORE_NAME, 'readwrite');\n const infoStore = infoTx.objectStore(INFO_STORE_NAME);\n\n const getInfoRequest = infoStore.get(path);\n let modelTx: IDBTransaction;\n getInfoRequest.onsuccess = () => {\n if (getInfoRequest.result == null) {\n db.close();\n return reject(new Error(\n `Cannot find model with path '${path}' ` +\n `in IndexedDB.`));\n } else {\n // First, delete the entry in the info store.\n const deleteInfoRequest = infoStore.delete(path);\n const deleteModelData = () => {\n // Second, delete the entry in the model store.\n modelTx = db.transaction(MODEL_STORE_NAME, 'readwrite');\n const modelStore = modelTx.objectStore(MODEL_STORE_NAME);\n const deleteModelRequest = modelStore.delete(path);\n deleteModelRequest.onsuccess = () =>\n resolve(getInfoRequest.result.modelArtifactsInfo);\n deleteModelRequest.onerror = error =>\n reject(getInfoRequest.error);\n };\n // Proceed with deleting model data regardless of whether deletion\n // of info data succeeds or not.\n deleteInfoRequest.onsuccess = deleteModelData;\n deleteInfoRequest.onerror = error => {\n deleteModelData();\n db.close();\n return reject(getInfoRequest.error);\n };\n }\n };\n getInfoRequest.onerror = error => {\n db.close();\n return reject(getInfoRequest.error);\n };\n\n infoTx.oncomplete = () => {\n if (modelTx == null) {\n db.close();\n } else {\n modelTx.oncomplete = () => db.close();\n }\n };\n };\n openRequest.onerror = error => reject(openRequest.error);\n });\n }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport '../flags';\nimport {env} from '../environment';\n\nimport {assert} from '../util';\nimport {arrayBufferToBase64String, base64StringToArrayBuffer, getModelArtifactsInfoForJSON} from './io_utils';\nimport {IORouter, IORouterRegistry} from './router_registry';\nimport {IOHandler, ModelArtifacts, ModelArtifactsInfo, ModelStoreManager, SaveResult} from './types';\n\nconst PATH_SEPARATOR = '/';\nconst PATH_PREFIX = 'tensorflowjs_models';\nconst INFO_SUFFIX = 'info';\nconst MODEL_TOPOLOGY_SUFFIX = 'model_topology';\nconst WEIGHT_SPECS_SUFFIX = 'weight_specs';\nconst WEIGHT_DATA_SUFFIX = 'weight_data';\nconst MODEL_METADATA_SUFFIX = 'model_metadata';\n\n/**\n * Purge all tensorflow.js-saved model artifacts from local storage.\n *\n * @returns Paths of the models purged.\n */\nexport function purgeLocalStorageArtifacts(): string[] {\n if (!env().getBool('IS_BROWSER') || typeof window === 'undefined' ||\n typeof window.localStorage === 'undefined') {\n throw new Error(\n 'purgeLocalStorageModels() cannot proceed because local storage is ' +\n 'unavailable in the current environment.');\n }\n const LS = window.localStorage;\n const purgedModelPaths: string[] = [];\n for (let i = 0; i < LS.length; ++i) {\n const key = LS.key(i);\n const prefix = PATH_PREFIX + PATH_SEPARATOR;\n if (key.startsWith(prefix) && key.length > prefix.length) {\n LS.removeItem(key);\n const modelName = getModelPathFromKey(key);\n if (purgedModelPaths.indexOf(modelName) === -1) {\n purgedModelPaths.push(modelName);\n }\n }\n }\n return purgedModelPaths;\n}\n\nfunction getModelKeys(path: string): {\n info: string,\n topology: string,\n weightSpecs: string,\n weightData: string,\n modelMetadata: string\n} {\n return {\n info: [PATH_PREFIX, path, INFO_SUFFIX].join(PATH_SEPARATOR),\n topology: [PATH_PREFIX, path, MODEL_TOPOLOGY_SUFFIX].join(PATH_SEPARATOR),\n weightSpecs: [PATH_PREFIX, path, WEIGHT_SPECS_SUFFIX].join(PATH_SEPARATOR),\n weightData: [PATH_PREFIX, path, WEIGHT_DATA_SUFFIX].join(PATH_SEPARATOR),\n modelMetadata:\n [PATH_PREFIX, path, MODEL_METADATA_SUFFIX].join(PATH_SEPARATOR)\n };\n}\n\n/**\n * Get model path from a local-storage key.\n *\n * E.g., 'tensorflowjs_models/my/model/1/info' --> 'my/model/1'\n *\n * @param key\n */\nfunction getModelPathFromKey(key: string) {\n const items = key.split(PATH_SEPARATOR);\n if (items.length < 3) {\n throw new Error(`Invalid key format: ${key}`);\n }\n return items.slice(1, items.length - 1).join(PATH_SEPARATOR);\n}\n\nfunction maybeStripScheme(key: string) {\n return key.startsWith(BrowserLocalStorage.URL_SCHEME) ?\n key.slice(BrowserLocalStorage.URL_SCHEME.length) :\n key;\n}\n\ndeclare type LocalStorageKeys = {\n info: string,\n topology: string,\n weightSpecs: string,\n weightData: string,\n modelMetadata: string\n};\n\n/**\n * IOHandler subclass: Browser Local Storage.\n *\n * See the doc string to `browserLocalStorage` for more details.\n */\nexport class BrowserLocalStorage implements IOHandler {\n protected readonly LS: Storage;\n protected readonly modelPath: string;\n protected readonly keys: LocalStorageKeys;\n\n static readonly URL_SCHEME = 'localstorage://';\n\n constructor(modelPath: string) {\n if (!env().getBool('IS_BROWSER') || typeof window === 'undefined' ||\n typeof window.localStorage === 'undefined') {\n // TODO(cais): Add more info about what IOHandler subtypes are\n // available.\n // Maybe point to a doc page on the web and/or automatically determine\n // the available IOHandlers and print them in the error message.\n throw new Error(\n 'The current environment does not support local storage.');\n }\n this.LS = window.localStorage;\n\n if (modelPath == null || !modelPath) {\n throw new Error(\n 'For local storage, modelPath must not be null, undefined or empty.');\n }\n this.modelPath = modelPath;\n this.keys = getModelKeys(this.modelPath);\n }\n\n /**\n * Save model artifacts to browser local storage.\n *\n * See the documentation to `browserLocalStorage` for details on the saved\n * artifacts.\n *\n * @param modelArtifacts The model artifacts to be stored.\n * @returns An instance of SaveResult.\n */\n async save(modelArtifacts: ModelArtifacts): Promise {\n if (modelArtifacts.modelTopology instanceof ArrayBuffer) {\n throw new Error(\n 'BrowserLocalStorage.save() does not support saving model topology ' +\n 'in binary formats yet.');\n } else {\n const topology = JSON.stringify(modelArtifacts.modelTopology);\n const weightSpecs = JSON.stringify(modelArtifacts.weightSpecs);\n\n const modelArtifactsInfo: ModelArtifactsInfo =\n getModelArtifactsInfoForJSON(modelArtifacts);\n\n try {\n this.LS.setItem(this.keys.info, JSON.stringify(modelArtifactsInfo));\n this.LS.setItem(this.keys.topology, topology);\n this.LS.setItem(this.keys.weightSpecs, weightSpecs);\n this.LS.setItem(\n this.keys.weightData,\n arrayBufferToBase64String(modelArtifacts.weightData));\n this.LS.setItem(this.keys.modelMetadata, JSON.stringify({\n format: modelArtifacts.format,\n generatedBy: modelArtifacts.generatedBy,\n convertedBy: modelArtifacts.convertedBy,\n userDefinedMetadata: modelArtifacts.userDefinedMetadata\n }));\n\n return {modelArtifactsInfo};\n } catch (err) {\n // If saving failed, clean up all items saved so far.\n this.LS.removeItem(this.keys.info);\n this.LS.removeItem(this.keys.topology);\n this.LS.removeItem(this.keys.weightSpecs);\n this.LS.removeItem(this.keys.weightData);\n this.LS.removeItem(this.keys.modelMetadata);\n\n throw new Error(\n `Failed to save model '${this.modelPath}' to local storage: ` +\n `size quota being exceeded is a possible cause of this failure: ` +\n `modelTopologyBytes=${modelArtifactsInfo.modelTopologyBytes}, ` +\n `weightSpecsBytes=${modelArtifactsInfo.weightSpecsBytes}, ` +\n `weightDataBytes=${modelArtifactsInfo.weightDataBytes}.`);\n }\n }\n }\n\n /**\n * Load a model from local storage.\n *\n * See the documentation to `browserLocalStorage` for details on the saved\n * artifacts.\n *\n * @returns The loaded model (if loading succeeds).\n */\n async load(): Promise {\n const info =\n JSON.parse(this.LS.getItem(this.keys.info)) as ModelArtifactsInfo;\n if (info == null) {\n throw new Error(\n `In local storage, there is no model with name '${this.modelPath}'`);\n }\n\n if (info.modelTopologyType !== 'JSON') {\n throw new Error(\n 'BrowserLocalStorage does not support loading non-JSON model ' +\n 'topology yet.');\n }\n\n const out: ModelArtifacts = {};\n\n // Load topology.\n const topology = JSON.parse(this.LS.getItem(this.keys.topology));\n if (topology == null) {\n throw new Error(\n `In local storage, the topology of model '${this.modelPath}' ` +\n `is missing.`);\n }\n out.modelTopology = topology;\n\n // Load weight specs.\n const weightSpecs = JSON.parse(this.LS.getItem(this.keys.weightSpecs));\n if (weightSpecs == null) {\n throw new Error(\n `In local storage, the weight specs of model '${this.modelPath}' ` +\n `are missing.`);\n }\n out.weightSpecs = weightSpecs;\n\n // Load meta-data fields.\n const metadataString = this.LS.getItem(this.keys.modelMetadata);\n if (metadataString != null) {\n const metadata = JSON.parse(metadataString) as ModelArtifacts;\n out.format = metadata['format'];\n out.generatedBy = metadata['generatedBy'];\n out.convertedBy = metadata['convertedBy'];\n out.userDefinedMetadata = metadata['userDefinedMetadata'];\n }\n\n // Load weight data.\n const weightDataBase64 = this.LS.getItem(this.keys.weightData);\n if (weightDataBase64 == null) {\n throw new Error(\n `In local storage, the binary weight values of model ` +\n `'${this.modelPath}' are missing.`);\n }\n out.weightData = base64StringToArrayBuffer(weightDataBase64);\n\n return out;\n }\n}\n\nexport const localStorageRouter: IORouter = (url: string|string[]) => {\n if (!env().getBool('IS_BROWSER')) {\n return null;\n } else {\n if (!Array.isArray(url) && url.startsWith(BrowserLocalStorage.URL_SCHEME)) {\n return browserLocalStorage(\n url.slice(BrowserLocalStorage.URL_SCHEME.length));\n } else {\n return null;\n }\n }\n};\nIORouterRegistry.registerSaveRouter(localStorageRouter);\nIORouterRegistry.registerLoadRouter(localStorageRouter);\n\n/**\n * Factory function for local storage IOHandler.\n *\n * This `IOHandler` supports both `save` and `load`.\n *\n * For each model's saved artifacts, four items are saved to local storage.\n * - `${PATH_SEPARATOR}/${modelPath}/info`: Contains meta-info about the\n * model, such as date saved, type of the topology, size in bytes, etc.\n * - `${PATH_SEPARATOR}/${modelPath}/topology`: Model topology. For Keras-\n * style models, this is a stringized JSON.\n * - `${PATH_SEPARATOR}/${modelPath}/weight_specs`: Weight specs of the\n * model, can be used to decode the saved binary weight values (see\n * item below).\n * - `${PATH_SEPARATOR}/${modelPath}/weight_data`: Concatenated binary\n * weight values, stored as a base64-encoded string.\n *\n * Saving may throw an `Error` if the total size of the artifacts exceed the\n * browser-specific quota.\n *\n * @param modelPath A unique identifier for the model to be saved. Must be a\n * non-empty string.\n * @returns An instance of `IOHandler`, which can be used with, e.g.,\n * `tf.Model.save`.\n */\nexport function browserLocalStorage(modelPath: string): IOHandler {\n return new BrowserLocalStorage(modelPath);\n}\n\nexport class BrowserLocalStorageManager implements ModelStoreManager {\n private readonly LS: Storage;\n\n constructor() {\n assert(\n env().getBool('IS_BROWSER'),\n () => 'Current environment is not a web browser');\n assert(\n typeof window === 'undefined' ||\n typeof window.localStorage !== 'undefined',\n () => 'Current browser does not appear to support localStorage');\n this.LS = window.localStorage;\n }\n\n async listModels(): Promise<{[path: string]: ModelArtifactsInfo}> {\n const out: {[path: string]: ModelArtifactsInfo} = {};\n const prefix = PATH_PREFIX + PATH_SEPARATOR;\n const suffix = PATH_SEPARATOR + INFO_SUFFIX;\n for (let i = 0; i < this.LS.length; ++i) {\n const key = this.LS.key(i);\n if (key.startsWith(prefix) && key.endsWith(suffix)) {\n const modelPath = getModelPathFromKey(key);\n out[modelPath] = JSON.parse(this.LS.getItem(key)) as ModelArtifactsInfo;\n }\n }\n return out;\n }\n\n async removeModel(path: string): Promise {\n path = maybeStripScheme(path);\n const keys = getModelKeys(path);\n if (this.LS.getItem(keys.info) == null) {\n throw new Error(`Cannot find model at path '${path}'`);\n }\n const info = JSON.parse(this.LS.getItem(keys.info)) as ModelArtifactsInfo;\n\n this.LS.removeItem(keys.info);\n this.LS.removeItem(keys.topology);\n this.LS.removeItem(keys.weightSpecs);\n this.LS.removeItem(keys.weightData);\n return info;\n }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * Classes and functions for model management across multiple storage mediums.\n *\n * Supported client actions:\n * - Listing models on all registered storage mediums.\n * - Remove model by URL from any registered storage mediums, by using URL\n * string.\n * - Moving or copying model from one path to another in the same medium or from\n * one medium to another, by using URL strings.\n */\n\nimport {assert} from '../util';\n\nimport {IORouterRegistry} from './router_registry';\nimport {ModelArtifactsInfo, ModelStoreManager} from './types';\n\nconst URL_SCHEME_SUFFIX = '://';\n\nexport class ModelStoreManagerRegistry {\n // Singleton instance.\n private static instance: ModelStoreManagerRegistry;\n\n private managers: {[scheme: string]: ModelStoreManager};\n\n private constructor() {\n this.managers = {};\n }\n\n private static getInstance(): ModelStoreManagerRegistry {\n if (ModelStoreManagerRegistry.instance == null) {\n ModelStoreManagerRegistry.instance = new ModelStoreManagerRegistry();\n }\n return ModelStoreManagerRegistry.instance;\n }\n\n /**\n * Register a save-handler router.\n *\n * @param saveRouter A function that maps a URL-like string onto an instance\n * of `IOHandler` with the `save` method defined or `null`.\n */\n static registerManager(scheme: string, manager: ModelStoreManager) {\n assert(scheme != null, () => 'scheme must not be undefined or null.');\n if (scheme.endsWith(URL_SCHEME_SUFFIX)) {\n scheme = scheme.slice(0, scheme.indexOf(URL_SCHEME_SUFFIX));\n }\n assert(scheme.length > 0, () => 'scheme must not be an empty string.');\n const registry = ModelStoreManagerRegistry.getInstance();\n assert(\n registry.managers[scheme] == null,\n () => `A model store manager is already registered for scheme '${\n scheme}'.`);\n registry.managers[scheme] = manager;\n }\n\n static getManager(scheme: string): ModelStoreManager {\n const manager = this.getInstance().managers[scheme];\n if (manager == null) {\n throw new Error(`Cannot find model manager for scheme '${scheme}'`);\n }\n return manager;\n }\n\n static getSchemes(): string[] {\n return Object.keys(this.getInstance().managers);\n }\n}\n\n/**\n * Helper method for parsing a URL string into a scheme and a path.\n *\n * @param url E.g., 'localstorage://my-model'\n * @returns A dictionary with two fields: scheme and path.\n * Scheme: e.g., 'localstorage' in the example above.\n * Path: e.g., 'my-model' in the example above.\n */\nfunction parseURL(url: string): {scheme: string, path: string} {\n if (url.indexOf(URL_SCHEME_SUFFIX) === -1) {\n throw new Error(\n `The url string provided does not contain a scheme. ` +\n `Supported schemes are: ` +\n `${ModelStoreManagerRegistry.getSchemes().join(',')}`);\n }\n return {\n scheme: url.split(URL_SCHEME_SUFFIX)[0],\n path: url.split(URL_SCHEME_SUFFIX)[1],\n };\n}\n\nasync function cloneModelInternal(\n sourceURL: string, destURL: string,\n deleteSource = false): Promise {\n assert(\n sourceURL !== destURL,\n () => `Old path and new path are the same: '${sourceURL}'`);\n\n const loadHandlers = IORouterRegistry.getLoadHandlers(sourceURL);\n assert(\n loadHandlers.length > 0,\n () => `Copying failed because no load handler is found for source URL ${\n sourceURL}.`);\n assert(\n loadHandlers.length < 2,\n () => `Copying failed because more than one (${loadHandlers.length}) ` +\n `load handlers for source URL ${sourceURL}.`);\n const loadHandler = loadHandlers[0];\n\n const saveHandlers = IORouterRegistry.getSaveHandlers(destURL);\n assert(\n saveHandlers.length > 0,\n () => `Copying failed because no save handler is found for destination ` +\n `URL ${destURL}.`);\n assert(\n saveHandlers.length < 2,\n () => `Copying failed because more than one (${loadHandlers.length}) ` +\n `save handlers for destination URL ${destURL}.`);\n const saveHandler = saveHandlers[0];\n\n const sourceScheme = parseURL(sourceURL).scheme;\n const sourcePath = parseURL(sourceURL).path;\n const sameMedium = sourceScheme === parseURL(sourceURL).scheme;\n\n const modelArtifacts = await loadHandler.load();\n\n // If moving within the same storage medium, remove the old model as soon as\n // the loading is done. Without doing this, it is possible that the combined\n // size of the two models will cause the cloning to fail.\n if (deleteSource && sameMedium) {\n await ModelStoreManagerRegistry.getManager(sourceScheme)\n .removeModel(sourcePath);\n }\n\n const saveResult = await saveHandler.save(modelArtifacts);\n\n // If moving between mediums, the deletion is done after the save succeeds.\n // This guards against the case in which saving to the destination medium\n // fails.\n if (deleteSource && !sameMedium) {\n await ModelStoreManagerRegistry.getManager(sourceScheme)\n .removeModel(sourcePath);\n }\n\n return saveResult.modelArtifactsInfo;\n}\n\n/**\n * List all models stored in registered storage mediums.\n *\n * For a web browser environment, the registered mediums are Local Storage and\n * IndexedDB.\n *\n * ```js\n * // First create and save a model.\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n * {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * await model.save('localstorage://demo/management/model1');\n *\n * // Then list existing models.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Delete the model.\n * await tf.io.removeModel('localstorage://demo/management/model1');\n *\n * // List models again.\n * console.log(JSON.stringify(await tf.io.listModels()));\n * ```\n *\n * @returns A `Promise` of a dictionary mapping URLs of existing models to\n * their model artifacts info. URLs include medium-specific schemes, e.g.,\n * 'indexeddb://my/model/1'. Model artifacts info include type of the\n * model's topology, byte sizes of the topology, weights, etc.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Management',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nasync function listModels(): Promise<{[url: string]: ModelArtifactsInfo}> {\n const schemes = ModelStoreManagerRegistry.getSchemes();\n const out: {[url: string]: ModelArtifactsInfo} = {};\n for (const scheme of schemes) {\n const schemeOut =\n await ModelStoreManagerRegistry.getManager(scheme).listModels();\n for (const path in schemeOut) {\n const url = scheme + URL_SCHEME_SUFFIX + path;\n out[url] = schemeOut[path];\n }\n }\n return out;\n}\n\n/**\n * Remove a model specified by URL from a reigstered storage medium.\n *\n * ```js\n * // First create and save a model.\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n * {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * await model.save('localstorage://demo/management/model1');\n *\n * // Then list existing models.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Delete the model.\n * await tf.io.removeModel('localstorage://demo/management/model1');\n *\n * // List models again.\n * console.log(JSON.stringify(await tf.io.listModels()));\n * ```\n *\n * @param url A URL to a stored model, with a scheme prefix, e.g.,\n * 'localstorage://my-model-1', 'indexeddb://my/model/2'.\n * @returns ModelArtifactsInfo of the deleted model (if and only if deletion\n * is successful).\n * @throws Error if deletion fails, e.g., if no model exists at `path`.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Management',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nasync function removeModel(url: string): Promise {\n const schemeAndPath = parseURL(url);\n const manager = ModelStoreManagerRegistry.getManager(schemeAndPath.scheme);\n return manager.removeModel(schemeAndPath.path);\n}\n\n/**\n * Copy a model from one URL to another.\n *\n * This function supports:\n *\n * 1. Copying within a storage medium, e.g.,\n * `tf.io.copyModel('localstorage://model-1', 'localstorage://model-2')`\n * 2. Copying between two storage mediums, e.g.,\n * `tf.io.copyModel('localstorage://model-1', 'indexeddb://model-1')`\n *\n * ```js\n * // First create and save a model.\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n * {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * await model.save('localstorage://demo/management/model1');\n *\n * // Then list existing models.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Copy the model, from Local Storage to IndexedDB.\n * await tf.io.copyModel(\n * 'localstorage://demo/management/model1',\n * 'indexeddb://demo/management/model1');\n *\n * // List models again.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Remove both models.\n * await tf.io.removeModel('localstorage://demo/management/model1');\n * await tf.io.removeModel('indexeddb://demo/management/model1');\n * ```\n *\n * @param sourceURL Source URL of copying.\n * @param destURL Destination URL of copying.\n * @returns ModelArtifactsInfo of the copied model (if and only if copying\n * is successful).\n * @throws Error if copying fails, e.g., if no model exists at `sourceURL`, or\n * if `oldPath` and `newPath` are identical.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Management',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nasync function copyModel(\n sourceURL: string, destURL: string): Promise {\n const deleteSource = false;\n return cloneModelInternal(sourceURL, destURL, deleteSource);\n}\n\n/**\n * Move a model from one URL to another.\n *\n * This function supports:\n *\n * 1. Moving within a storage medium, e.g.,\n * `tf.io.moveModel('localstorage://model-1', 'localstorage://model-2')`\n * 2. Moving between two storage mediums, e.g.,\n * `tf.io.moveModel('localstorage://model-1', 'indexeddb://model-1')`\n *\n * ```js\n * // First create and save a model.\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n * {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * await model.save('localstorage://demo/management/model1');\n *\n * // Then list existing models.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Move the model, from Local Storage to IndexedDB.\n * await tf.io.moveModel(\n * 'localstorage://demo/management/model1',\n * 'indexeddb://demo/management/model1');\n *\n * // List models again.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Remove the moved model.\n * await tf.io.removeModel('indexeddb://demo/management/model1');\n * ```\n *\n * @param sourceURL Source URL of moving.\n * @param destURL Destination URL of moving.\n * @returns ModelArtifactsInfo of the copied model (if and only if copying\n * is successful).\n * @throws Error if moving fails, e.g., if no model exists at `sourceURL`, or\n * if `oldPath` and `newPath` are identical.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Management',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nasync function moveModel(\n sourceURL: string, destURL: string): Promise {\n const deleteSource = true;\n return cloneModelInternal(sourceURL, destURL, deleteSource);\n}\n\nexport {moveModel, copyModel, removeModel, listModels};\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport '../flags';\n\nimport {env} from '../environment';\nimport {BrowserIndexedDB, BrowserIndexedDBManager} from '../io/indexed_db';\nimport {BrowserLocalStorage, BrowserLocalStorageManager} from '../io/local_storage';\nimport {ModelStoreManagerRegistry} from '../io/model_management';\n\nimport {Platform} from './platform';\n\nexport class PlatformBrowser implements Platform {\n // According to the spec, the built-in encoder can do only UTF-8 encoding.\n // https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder/TextEncoder\n private textEncoder: TextEncoder;\n\n fetch(path: string, init?: RequestInit): Promise {\n return fetch(path, init);\n }\n\n now(): number {\n return performance.now();\n }\n\n encode(text: string, encoding: string): Uint8Array {\n if (encoding !== 'utf-8' && encoding !== 'utf8') {\n throw new Error(\n `Browser's encoder only supports utf-8, but got ${encoding}`);\n }\n if (this.textEncoder == null) {\n this.textEncoder = new TextEncoder();\n }\n return this.textEncoder.encode(text);\n }\n decode(bytes: Uint8Array, encoding: string): string {\n return new TextDecoder(encoding).decode(bytes);\n }\n}\n\nif (env().get('IS_BROWSER')) {\n env().setPlatform('browser', new PlatformBrowser());\n\n // Register LocalStorage IOHandler\n try {\n ModelStoreManagerRegistry.registerManager(\n BrowserLocalStorage.URL_SCHEME, new BrowserLocalStorageManager());\n } catch (err) {\n }\n\n // Register IndexedDB IOHandler\n try {\n ModelStoreManagerRegistry.registerManager(\n BrowserIndexedDB.URL_SCHEME, new BrowserIndexedDBManager());\n } catch (err) {\n }\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {env} from '../environment';\n\nimport {Platform} from './platform';\n\n// We are wrapping this within an object so it can be stubbed by Jasmine.\nexport const getNodeFetch = {\n // tslint:disable-next-line:no-require-imports\n importFetch: () => require('node-fetch')\n};\n\ntype FetchFn = (url: string, init?: RequestInit) => Promise;\nlet systemFetch: FetchFn;\n// These getters and setters are for testing so we don't export a mutable\n// variable.\nexport function resetSystemFetch() {\n systemFetch = null;\n}\nexport function setSystemFetch(fetchFn: FetchFn) {\n systemFetch = fetchFn;\n}\nexport function getSystemFetch(): FetchFn {\n return systemFetch;\n}\n\nexport class PlatformNode implements Platform {\n private textEncoder: TextEncoder;\n // tslint:disable-next-line:no-any\n util: any;\n\n constructor() {\n // tslint:disable-next-line:no-require-imports\n this.util = require('util');\n // According to the spec, the built-in encoder can do only UTF-8 encoding.\n // https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder/TextEncoder\n this.textEncoder = new this.util.TextEncoder();\n }\n\n fetch(path: string, requestInits?: RequestInit): Promise {\n if (env().global.fetch != null) {\n return env().global.fetch(path, requestInits);\n }\n\n if (systemFetch == null) {\n systemFetch = getNodeFetch.importFetch();\n }\n return systemFetch(path, requestInits);\n }\n\n now(): number {\n const time = process.hrtime();\n return time[0] * 1000 + time[1] / 1000000;\n }\n\n encode(text: string, encoding: string): Uint8Array {\n if (encoding !== 'utf-8' && encoding !== 'utf8') {\n throw new Error(\n `Node built-in encoder only supports utf-8, but got ${encoding}`);\n }\n return this.textEncoder.encode(text);\n }\n decode(bytes: Uint8Array, encoding: string): string {\n if (bytes.length === 0) {\n return '';\n }\n return new this.util.TextDecoder(encoding).decode(bytes);\n }\n}\n\nif (env().get('IS_NODE')) {\n env().setPlatform('node', new PlatformNode());\n}\n", "/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {TensorBuffer} from '../tensor';\nimport {DataType, DataTypeMap, Rank, ShapeMap} from '../types';\nimport * as util from '../util';\n\n/**\n * Creates an empty `tf.TensorBuffer` with the specified `shape` and `dtype`.\n *\n * The values are stored in CPU as `TypedArray`. Fill the buffer using\n * `buffer.set()`, or by modifying directly `buffer.values`.\n *\n * When done, call `buffer.toTensor()` to get an immutable `tf.Tensor` with\n * those values.\n *\n * ```js\n * // Create a buffer and set values at particular indices.\n * const buffer = tf.buffer([2, 2]);\n * buffer.set(3, 0, 0);\n * buffer.set(5, 1, 0);\n *\n * // Convert the buffer back to a tensor.\n * buffer.toTensor().print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param dtype The dtype of the buffer. Defaults to 'float32'.\n * @param values The values of the buffer as `TypedArray`. Defaults to\n * zeros.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function buffer(\n shape: ShapeMap[R], dtype: D = 'float32' as D,\n values?: DataTypeMap[D]): TensorBuffer {\n dtype = dtype || 'float32' as D;\n util.assertNonNegativeIntegerDimensions(shape);\n return new TensorBuffer(shape, dtype, values);\n}\n", "/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Cast, CastAttrs, CastInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {DataType, TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Casts a `tf.Tensor` to a new dtype.\n *\n * ```js\n * const x = tf.tensor1d([1.5, 2.5, 3]);\n * tf.cast(x, 'int32').print();\n * ```\n * @param x The input tensor to be casted.\n * @param dtype The dtype to cast the input tensor to.\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction cast_(x: T|TensorLike, dtype: DataType): T {\n const $x = convertToTensor(x, 'x', 'cast');\n\n // Sanity checks.\n if (!util.isValidDtype(dtype)) {\n throw new Error(`Failed to cast to unknown dtype ${dtype}`);\n }\n if (dtype === 'string' && $x.dtype !== 'string' ||\n dtype !== 'string' && $x.dtype === 'string') {\n throw new Error('Only strings can be casted to strings');\n }\n\n const inputs: CastInputs = {x: $x};\n const attrs: CastAttrs = {dtype};\n\n return ENGINE.runKernelFunc(\n backend => backend.cast($x, dtype), inputs as {} as NamedTensorMap,\n null /* grad */, Cast, attrs as {} as NamedAttrMap);\n}\n\nexport const cast = op({cast_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Identity, IdentityInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Creates a new tensor with the same values and shape as the specified\n * tensor.\n *\n * ```js\n * const x = tf.tensor([1, 2]);\n *\n * x.clone().print();\n * ```\n *\n * @param x The tensor to clone.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction clone_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'clone', null);\n const forward = () =>\n ENGINE.makeTensorFromDataId($x.dataId, $x.shape, $x.dtype) as T;\n\n const inputs: IdentityInputs = {x: $x};\n\n // Note this op is called tf.identity in python. Hence the kernel name used\n // here.\n return ENGINE.runKernelFunc(\n forward, inputs as {} as NamedTensorMap, null /* grad */, Identity);\n}\n\nexport const clone = op({clone_});\n", "/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\n\n/**\n * Prints information about the `tf.Tensor` including its data.\n *\n * ```js\n * const verbose = true;\n * tf.tensor2d([1, 2, 3, 4], [2, 2]).print(verbose);\n * ```\n * @param x The tensor to be printed.\n * @param verbose Whether to print verbose information about the ` Tensor`,\n * including dtype and size.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function print(x: T, verbose = false): void {\n console.log(x.toString(verbose));\n}\n", "/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Required side effectful code for tfjs-core\n\n// Set up Engine and ENV\nimport {getOrMakeEngine} from './engine';\ngetOrMakeEngine();\n\n// Register backend-agnostic flags.\nimport './flags';\n// Register platforms\nimport './platforms/platform_browser';\nimport './platforms/platform_node';\n\n// Set up OpHandler\nimport {buffer} from './ops/buffer';\nimport {cast} from './ops/cast';\nimport {clone} from './ops/clone';\nimport {print} from './ops/print';\nimport {OpHandler, setOpHandler} from './tensor';\nconst opHandler: OpHandler = {\n buffer,\n cast,\n clone,\n print\n};\nsetOpHandler(opHandler);\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * IOHandlers related to files, such as browser-triggered file downloads,\n * user-selected files in browser.\n */\n\nimport '../flags';\nimport {env} from '../environment';\n\nimport {basename, concatenateArrayBuffers, getModelArtifactsInfoForJSON} from './io_utils';\nimport {IORouter, IORouterRegistry} from './router_registry';\nimport {IOHandler, ModelArtifacts, ModelJSON, SaveResult, WeightsManifestConfig, WeightsManifestEntry} from './types';\n\nconst DEFAULT_FILE_NAME_PREFIX = 'model';\nconst DEFAULT_JSON_EXTENSION_NAME = '.json';\nconst DEFAULT_WEIGHT_DATA_EXTENSION_NAME = '.weights.bin';\n\nfunction defer(f: () => T): Promise {\n return new Promise(resolve => setTimeout(resolve)).then(f);\n}\n\nexport class BrowserDownloads implements IOHandler {\n private readonly modelTopologyFileName: string;\n private readonly weightDataFileName: string;\n private readonly jsonAnchor: HTMLAnchorElement;\n private readonly weightDataAnchor: HTMLAnchorElement;\n\n static readonly URL_SCHEME = 'downloads://';\n\n constructor(fileNamePrefix?: string) {\n if (!env().getBool('IS_BROWSER')) {\n // TODO(cais): Provide info on what IOHandlers are available under the\n // current environment.\n throw new Error(\n 'browserDownloads() cannot proceed because the current environment ' +\n 'is not a browser.');\n }\n\n if (fileNamePrefix.startsWith(BrowserDownloads.URL_SCHEME)) {\n fileNamePrefix = fileNamePrefix.slice(BrowserDownloads.URL_SCHEME.length);\n }\n if (fileNamePrefix == null || fileNamePrefix.length === 0) {\n fileNamePrefix = DEFAULT_FILE_NAME_PREFIX;\n }\n\n this.modelTopologyFileName = fileNamePrefix + DEFAULT_JSON_EXTENSION_NAME;\n this.weightDataFileName =\n fileNamePrefix + DEFAULT_WEIGHT_DATA_EXTENSION_NAME;\n }\n\n async save(modelArtifacts: ModelArtifacts): Promise {\n if (typeof (document) === 'undefined') {\n throw new Error(\n 'Browser downloads are not supported in ' +\n 'this environment since `document` is not present');\n }\n const weightsURL = window.URL.createObjectURL(new Blob(\n [modelArtifacts.weightData], {type: 'application/octet-stream'}));\n\n if (modelArtifacts.modelTopology instanceof ArrayBuffer) {\n throw new Error(\n 'BrowserDownloads.save() does not support saving model topology ' +\n 'in binary formats yet.');\n } else {\n const weightsManifest: WeightsManifestConfig = [{\n paths: ['./' + this.weightDataFileName],\n weights: modelArtifacts.weightSpecs\n }];\n const modelTopologyAndWeightManifest: ModelJSON = {\n modelTopology: modelArtifacts.modelTopology,\n format: modelArtifacts.format,\n generatedBy: modelArtifacts.generatedBy,\n convertedBy: modelArtifacts.convertedBy,\n weightsManifest\n };\n const modelTopologyAndWeightManifestURL =\n window.URL.createObjectURL(new Blob(\n [JSON.stringify(modelTopologyAndWeightManifest)],\n {type: 'application/json'}));\n\n // If anchor elements are not provided, create them without attaching them\n // to parents, so that the downloaded file names can be controlled.\n const jsonAnchor = this.jsonAnchor == null ? document.createElement('a') :\n this.jsonAnchor;\n jsonAnchor.download = this.modelTopologyFileName;\n jsonAnchor.href = modelTopologyAndWeightManifestURL;\n // Trigger downloads by evoking a click event on the download anchors.\n // When multiple downloads are started synchronously, Firefox will only\n // save the last one.\n await defer(() => jsonAnchor.dispatchEvent(new MouseEvent('click')));\n\n if (modelArtifacts.weightData != null) {\n const weightDataAnchor = this.weightDataAnchor == null ?\n document.createElement('a') :\n this.weightDataAnchor;\n weightDataAnchor.download = this.weightDataFileName;\n weightDataAnchor.href = weightsURL;\n await defer(\n () => weightDataAnchor.dispatchEvent(new MouseEvent('click')));\n }\n\n return {modelArtifactsInfo: getModelArtifactsInfoForJSON(modelArtifacts)};\n }\n }\n}\n\nclass BrowserFiles implements IOHandler {\n private readonly files: File[];\n\n constructor(files: File[]) {\n if (files == null || files.length < 1) {\n throw new Error(\n `When calling browserFiles, at least 1 file is required, ` +\n `but received ${files}`);\n }\n this.files = files;\n }\n\n async load(): Promise {\n const jsonFile = this.files[0];\n const weightFiles = this.files.slice(1);\n\n return new Promise((resolve, reject) => {\n const jsonReader = new FileReader();\n jsonReader.onload = (event: Event) => {\n // tslint:disable-next-line:no-any\n const modelJSON = JSON.parse((event.target as any).result) as ModelJSON;\n const modelTopology = modelJSON.modelTopology;\n if (modelTopology == null) {\n reject(new Error(\n `modelTopology field is missing from file ${jsonFile.name}`));\n return;\n }\n\n if (weightFiles.length === 0) {\n resolve({modelTopology});\n }\n\n const weightsManifest = modelJSON.weightsManifest;\n if (weightsManifest == null) {\n reject(new Error(\n `weightManifest field is missing from file ${jsonFile.name}`));\n return;\n }\n\n let pathToFile: {[path: string]: File};\n try {\n pathToFile =\n this.checkManifestAndWeightFiles(weightsManifest, weightFiles);\n } catch (err) {\n reject(err);\n return;\n }\n\n const weightSpecs: WeightsManifestEntry[] = [];\n const paths: string[] = [];\n const perFileBuffers: ArrayBuffer[] = [];\n weightsManifest.forEach(weightsGroup => {\n weightsGroup.paths.forEach(path => {\n paths.push(path);\n perFileBuffers.push(null);\n });\n weightSpecs.push(...weightsGroup.weights);\n });\n\n weightsManifest.forEach(weightsGroup => {\n weightsGroup.paths.forEach(path => {\n const weightFileReader = new FileReader();\n weightFileReader.onload = (event: Event) => {\n // tslint:disable-next-line:no-any\n const weightData = (event.target as any).result as ArrayBuffer;\n const index = paths.indexOf(path);\n perFileBuffers[index] = weightData;\n if (perFileBuffers.indexOf(null) === -1) {\n resolve({\n modelTopology,\n weightSpecs,\n weightData: concatenateArrayBuffers(perFileBuffers),\n format: modelJSON.format,\n generatedBy: modelJSON.generatedBy,\n convertedBy: modelJSON.convertedBy,\n userDefinedMetadata: modelJSON.userDefinedMetadata\n });\n }\n };\n weightFileReader.onerror = error =>\n reject(`Failed to weights data from file of path '${path}'.`);\n weightFileReader.readAsArrayBuffer(pathToFile[path]);\n });\n });\n };\n jsonReader.onerror = error => reject(\n `Failed to read model topology and weights manifest JSON ` +\n `from file '${jsonFile.name}'. BrowserFiles supports loading ` +\n `Keras-style tf.Model artifacts only.`);\n jsonReader.readAsText(jsonFile);\n });\n }\n\n /**\n * Check the compatibility between weights manifest and weight files.\n */\n private checkManifestAndWeightFiles(\n manifest: WeightsManifestConfig, files: File[]): {[path: string]: File} {\n const basenames: string[] = [];\n const fileNames = files.map(file => basename(file.name));\n const pathToFile: {[path: string]: File} = {};\n for (const group of manifest) {\n group.paths.forEach(path => {\n const pathBasename = basename(path);\n if (basenames.indexOf(pathBasename) !== -1) {\n throw new Error(\n `Duplicate file basename found in weights manifest: ` +\n `'${pathBasename}'`);\n }\n basenames.push(pathBasename);\n if (fileNames.indexOf(pathBasename) === -1) {\n throw new Error(\n `Weight file with basename '${pathBasename}' is not provided.`);\n } else {\n pathToFile[path] = files[fileNames.indexOf(pathBasename)];\n }\n });\n }\n\n if (basenames.length !== files.length) {\n throw new Error(\n `Mismatch in the number of files in weights manifest ` +\n `(${basenames.length}) and the number of weight files provided ` +\n `(${files.length}).`);\n }\n return pathToFile;\n }\n}\n\nexport const browserDownloadsRouter: IORouter = (url: string|string[]) => {\n if (!env().getBool('IS_BROWSER')) {\n return null;\n } else {\n if (!Array.isArray(url) && url.startsWith(BrowserDownloads.URL_SCHEME)) {\n return browserDownloads(url.slice(BrowserDownloads.URL_SCHEME.length));\n } else {\n return null;\n }\n }\n};\nIORouterRegistry.registerSaveRouter(browserDownloadsRouter);\n\n/**\n * Creates an IOHandler that triggers file downloads from the browser.\n *\n * The returned `IOHandler` instance can be used as model exporting methods such\n * as `tf.Model.save` and supports only saving.\n *\n * ```js\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n * {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * const saveResult = await model.save('downloads://mymodel');\n * // This will trigger downloading of two files:\n * // 'mymodel.json' and 'mymodel.weights.bin'.\n * console.log(saveResult);\n * ```\n *\n * @param fileNamePrefix Prefix name of the files to be downloaded. For use with\n * `tf.Model`, `fileNamePrefix` should follow either of the following two\n * formats:\n * 1. `null` or `undefined`, in which case the default file\n * names will be used:\n * - 'model.json' for the JSON file containing the model topology and\n * weights manifest.\n * - 'model.weights.bin' for the binary file containing the binary weight\n * values.\n * 2. A single string or an Array of a single string, as the file name prefix.\n * For example, if `'foo'` is provided, the downloaded JSON\n * file and binary weights file will be named 'foo.json' and\n * 'foo.weights.bin', respectively.\n * @param config Additional configuration for triggering downloads.\n * @returns An instance of `BrowserDownloads` `IOHandler`.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Loading',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nexport function browserDownloads(fileNamePrefix = 'model'): IOHandler {\n return new BrowserDownloads(fileNamePrefix);\n}\n\n/**\n * Creates an IOHandler that loads model artifacts from user-selected files.\n *\n * This method can be used for loading from files such as user-selected files\n * in the browser.\n * When used in conjunction with `tf.loadLayersModel`, an instance of\n * `tf.LayersModel` (Keras-style) can be constructed from the loaded artifacts.\n *\n * ```js\n * // Note: This code snippet won't run properly without the actual file input\n * // elements in the HTML DOM.\n *\n * // Suppose there are two HTML file input (``)\n * // elements.\n * const uploadJSONInput = document.getElementById('upload-json');\n * const uploadWeightsInput = document.getElementById('upload-weights');\n * const model = await tf.loadLayersModel(tf.io.browserFiles(\n * [uploadJSONInput.files[0], uploadWeightsInput.files[0]]));\n * ```\n *\n * @param files `File`s to load from. Currently, this function supports only\n * loading from files that contain Keras-style models (i.e., `tf.Model`s), for\n * which an `Array` of `File`s is expected (in that order):\n * - A JSON file containing the model topology and weight manifest.\n * - Optionally, One or more binary files containing the binary weights.\n * These files must have names that match the paths in the `weightsManifest`\n * contained by the aforementioned JSON file, or errors will be thrown\n * during loading. These weights files have the same format as the ones\n * generated by `tensorflowjs_converter` that comes with the `tensorflowjs`\n * Python PIP package. If no weights files are provided, only the model\n * topology will be loaded from the JSON file above.\n * @returns An instance of `Files` `IOHandler`.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Loading',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nexport function browserFiles(files: File[]): IOHandler {\n return new BrowserFiles(files);\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {assert} from '../util';\n\nimport {OnProgressCallback} from './types';\n\n/**\n * Monitor Promise.all progress, fire onProgress callback function.\n *\n * @param promises Promise list going to be monitored\n * @param onProgress Callback function. Fired when a promise resolved.\n * @param startFraction Optional fraction start. Default to 0.\n * @param endFraction Optional fraction end. Default to 1.\n */\nexport function monitorPromisesProgress(\n promises: Array>, onProgress: OnProgressCallback,\n startFraction?: number, endFraction?: number) {\n checkPromises(promises);\n startFraction = startFraction == null ? 0 : startFraction;\n endFraction = endFraction == null ? 1 : endFraction;\n checkFraction(startFraction, endFraction);\n let resolvedPromise = 0;\n\n const registerMonitor = (promise: Promise<{}>) => {\n promise.then(value => {\n const fraction = startFraction +\n ++resolvedPromise / promises.length * (endFraction - startFraction);\n // pass fraction as parameter to callback function.\n onProgress(fraction);\n return value;\n });\n return promise;\n };\n\n function checkPromises(promises: Array>): void {\n assert(\n promises != null && Array.isArray(promises) && promises.length > 0,\n () => 'promises must be a none empty array');\n }\n\n function checkFraction(startFraction: number, endFraction: number): void {\n assert(\n startFraction >= 0 && startFraction <= 1,\n () => `Progress fraction must be in range [0, 1], but ` +\n `got startFraction ${startFraction}`);\n assert(\n endFraction >= 0 && endFraction <= 1,\n () => `Progress fraction must be in range [0, 1], but ` +\n `got endFraction ${endFraction}`);\n assert(\n endFraction >= startFraction,\n () => `startFraction must be no more than endFraction, but ` +\n `got startFraction ${startFraction} and endFraction ` +\n `${endFraction}`);\n }\n\n return Promise.all(promises.map(registerMonitor));\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env} from '../environment';\n\nimport {NamedTensorMap} from '../tensor_types';\nimport * as util from '../util';\nimport {decodeWeights} from './io_utils';\nimport {monitorPromisesProgress} from './progress';\nimport {DTYPE_VALUE_SIZE_MAP, LoadOptions, WeightsManifestConfig, WeightsManifestEntry} from './types';\n\n/**\n * Reads binary weights data from a number of URLs.\n *\n * @param fetchURLs URLs to send the HTTP requests at, using `fetch` calls.\n * @param requestOptions RequestInit (options) for the HTTP requests.\n * @param fetchFunc Optional overriding value for the `window.fetch` function.\n * @param onProgress Optional, progress callback function, fired periodically\n * before the load is completed.\n * @returns A `Promise` of an Array of `ArrayBuffer`. The Array has the same\n * length as `fetchURLs`.\n */\nexport async function loadWeightsAsArrayBuffer(\n fetchURLs: string[], loadOptions?: LoadOptions): Promise {\n if (loadOptions == null) {\n loadOptions = {};\n }\n\n const fetchFunc = loadOptions.fetchFunc == null ? env().platform.fetch :\n loadOptions.fetchFunc;\n\n // Create the requests for all of the weights in parallel.\n const requests = fetchURLs.map(\n fetchURL =>\n fetchFunc(fetchURL, loadOptions.requestInit, {isBinary: true}));\n\n const fetchStartFraction = 0;\n const fetchEndFraction = 0.5;\n\n const responses = loadOptions.onProgress == null ?\n await Promise.all(requests) :\n await monitorPromisesProgress(\n requests, loadOptions.onProgress, fetchStartFraction,\n fetchEndFraction);\n\n const bufferPromises = responses.map(response => response.arrayBuffer());\n\n const bufferStartFraction = 0.5;\n const bufferEndFraction = 1;\n\n const buffers = loadOptions.onProgress == null ?\n await Promise.all(bufferPromises) :\n await monitorPromisesProgress(\n bufferPromises, loadOptions.onProgress, bufferStartFraction,\n bufferEndFraction);\n return buffers;\n}\n\n/**\n * Reads a weights manifest JSON configuration, fetches the weights and\n * returns them as `Tensor`s.\n *\n * @param manifest The weights manifest JSON.\n * @param filePathPrefix The path prefix for filenames given in the manifest.\n * Defaults to the empty string.\n * @param weightNames The names of the weights to be fetched.\n */\nexport async function loadWeights(\n manifest: WeightsManifestConfig, filePathPrefix = '',\n weightNames?: string[],\n requestInit?: RequestInit): Promise {\n // TODO(nsthorat): Groups are currently fetched atomically. If you need a\n // single weight from a group, the whole group will be fetched. At a future\n // date, we should support fetching only the individual shards within a\n // group that are needed to reconstruct the requested weight.\n // TODO(cais): Use `decodeWeights` for implementation.\n\n const fetchWeights = (fetchUrls: string[]) =>\n loadWeightsAsArrayBuffer(fetchUrls, {requestInit});\n const loadWeights = weightsLoaderFactory(fetchWeights);\n\n return loadWeights(manifest, filePathPrefix, weightNames);\n}\n\n/**\n * Creates a function, which reads a weights manifest JSON configuration,\n * fetches the weight files using the specified function and returns them as\n * `Tensor`s.\n *\n * ```js\n * // example for creating a nodejs weight loader, which reads the weight files\n * // from disk using fs.readFileSync\n *\n * import * as fs from 'fs'\n *\n * const fetchWeightsFromDisk = (filePaths: string[]) =>\n * filePaths.map(filePath => fs.readFileSync(filePath).buffer)\n *\n * const loadWeights = tf.io.weightsLoaderFactory(fetchWeightsFromDisk)\n *\n * const manifest = JSON.parse(\n * fs.readFileSync('./my_model-weights_manifest').toString()\n * )\n * const weightMap = await loadWeights(manifest, './')\n * ```\n * @param fetchWeightsFunction The function used for fetching the weight files.\n * @returns Weight loading function.\n */\nexport function weightsLoaderFactory(\n fetchWeightsFunction: (fetchUrls: string[]) => Promise):\n (manifest: WeightsManifestConfig, filePathPrefix?: string,\n weightNames?: string[]) => Promise {\n return async(\n manifest: WeightsManifestConfig, filePathPrefix = '',\n weightNames?: string[]): Promise => {\n // Collect all the groups, weights, and their relative offsets to be\n // fetched.\n const groupIndicesToFetchMap = manifest.map(() => false);\n const groupWeightsToFetch: {\n [group: number]: Array<{\n manifestEntry: WeightsManifestEntry; groupOffset: number;\n sizeBytes: number;\n }>\n } = {};\n const weightsFound =\n weightNames != null ? weightNames.map(() => false) : [];\n const allManifestWeightNames: string[] = [];\n manifest.forEach((manifestGroupConfig, groupIndex) => {\n let groupOffset = 0;\n manifestGroupConfig.weights.forEach(weightsEntry => {\n const rawDtype = ('quantization' in weightsEntry) ?\n weightsEntry.quantization.dtype :\n weightsEntry.dtype;\n\n const weightsBytes = DTYPE_VALUE_SIZE_MAP[rawDtype] *\n util.sizeFromShape(weightsEntry.shape);\n\n const enqueueWeightsForFetchingFn = () => {\n groupIndicesToFetchMap[groupIndex] = true;\n if (groupWeightsToFetch[groupIndex] == null) {\n groupWeightsToFetch[groupIndex] = [];\n }\n\n groupWeightsToFetch[groupIndex].push({\n manifestEntry: weightsEntry,\n groupOffset,\n sizeBytes: weightsBytes\n });\n };\n\n if (weightNames != null) {\n weightNames.forEach((weightName, weightIndex) => {\n if (weightName === weightsEntry.name) {\n enqueueWeightsForFetchingFn();\n weightsFound[weightIndex] = true;\n }\n });\n } else {\n enqueueWeightsForFetchingFn();\n }\n\n allManifestWeightNames.push(weightsEntry.name);\n groupOffset += weightsBytes;\n });\n });\n\n if (!weightsFound.every(found => found)) {\n const weightsNotFound = weightNames.filter((_, i) => !weightsFound[i]);\n throw new Error(\n `Could not find weights in manifest with names: ` +\n `${weightsNotFound.join(', ')}. \\n` +\n `Manifest JSON has weights with names: ` +\n `${allManifestWeightNames.join(', ')}.`);\n }\n\n // Convert the one-hot boolean groupId => shouldFetch map to a list of group\n // IDs.\n const groupIndicesToFetch =\n groupIndicesToFetchMap.reduce((accumulator, shouldFetch, i) => {\n if (shouldFetch) {\n accumulator.push(i);\n }\n return accumulator;\n }, []);\n\n const fetchUrls: string[] = [];\n groupIndicesToFetch.forEach(i => {\n manifest[i].paths.forEach(filepath => {\n const fetchUrl = filePathPrefix +\n (!filePathPrefix.endsWith('/') ? '/' : '') + filepath;\n fetchUrls.push(fetchUrl);\n });\n });\n const buffers = await fetchWeightsFunction(fetchUrls);\n\n const weightsTensorMap: NamedTensorMap = {};\n let bufferIndexOffset = 0;\n groupIndicesToFetch.forEach(i => {\n const numBuffers = manifest[i].paths.length;\n\n let groupBytes = 0;\n for (let i = 0; i < numBuffers; i++) {\n groupBytes += buffers[bufferIndexOffset + i].byteLength;\n }\n\n // Create a buffer for the whole group.\n const groupBuffer = new ArrayBuffer(groupBytes);\n const groupByteBuffer = new Uint8Array(groupBuffer);\n let groupBufferOffset = 0;\n for (let i = 0; i < numBuffers; i++) {\n const buffer = new Uint8Array(buffers[bufferIndexOffset + i]);\n groupByteBuffer.set(buffer, groupBufferOffset);\n groupBufferOffset += buffer.byteLength;\n }\n\n const weightsEntries = groupWeightsToFetch[i];\n weightsEntries.forEach(weightsEntry => {\n const byteBuffer = groupBuffer.slice(\n weightsEntry.groupOffset,\n weightsEntry.groupOffset + weightsEntry.sizeBytes);\n const nameToTensorMap =\n decodeWeights(byteBuffer, [weightsEntry.manifestEntry]);\n for (const name in nameToTensorMap) {\n weightsTensorMap[name] = nameToTensorMap[name];\n }\n });\n\n bufferIndexOffset += numBuffers;\n });\n\n return weightsTensorMap;\n };\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * IOHandler implementations based on HTTP requests in the web browser.\n *\n * Uses [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).\n */\n\nimport {env} from '../environment';\n\nimport {assert} from '../util';\nimport {concatenateArrayBuffers, getModelArtifactsInfoForJSON} from './io_utils';\nimport {IORouter, IORouterRegistry} from './router_registry';\nimport {IOHandler, LoadOptions, ModelArtifacts, ModelJSON, OnProgressCallback, SaveResult, WeightsManifestConfig, WeightsManifestEntry} from './types';\nimport {loadWeightsAsArrayBuffer} from './weights_loader';\n\nconst OCTET_STREAM_MIME_TYPE = 'application/octet-stream';\nconst JSON_TYPE = 'application/json';\nexport class HTTPRequest implements IOHandler {\n protected readonly path: string;\n protected readonly requestInit: RequestInit;\n\n private readonly fetch: Function;\n private readonly weightUrlConverter: (weightName: string) => Promise;\n\n readonly DEFAULT_METHOD = 'POST';\n\n static readonly URL_SCHEME_REGEX = /^https?:\\/\\//;\n\n private readonly weightPathPrefix: string;\n private readonly onProgress: OnProgressCallback;\n\n constructor(path: string, loadOptions?: LoadOptions) {\n if (loadOptions == null) {\n loadOptions = {};\n }\n this.weightPathPrefix = loadOptions.weightPathPrefix;\n this.onProgress = loadOptions.onProgress;\n this.weightUrlConverter = loadOptions.weightUrlConverter;\n\n if (loadOptions.fetchFunc != null) {\n assert(\n typeof loadOptions.fetchFunc === 'function',\n () => 'Must pass a function that matches the signature of ' +\n '`fetch` (see ' +\n 'https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)');\n this.fetch = loadOptions.fetchFunc;\n } else {\n this.fetch = env().platform.fetch;\n }\n\n assert(\n path != null && path.length > 0,\n () => 'URL path for http must not be null, undefined or ' +\n 'empty.');\n\n if (Array.isArray(path)) {\n assert(\n path.length === 2,\n () => 'URL paths for http must have a length of 2, ' +\n `(actual length is ${path.length}).`);\n }\n this.path = path;\n\n if (loadOptions.requestInit != null &&\n loadOptions.requestInit.body != null) {\n throw new Error(\n 'requestInit is expected to have no pre-existing body, but has one.');\n }\n this.requestInit = loadOptions.requestInit || {};\n }\n\n async save(modelArtifacts: ModelArtifacts): Promise {\n if (modelArtifacts.modelTopology instanceof ArrayBuffer) {\n throw new Error(\n 'BrowserHTTPRequest.save() does not support saving model topology ' +\n 'in binary formats yet.');\n }\n\n const init = Object.assign({method: this.DEFAULT_METHOD}, this.requestInit);\n init.body = new FormData();\n\n const weightsManifest: WeightsManifestConfig = [{\n paths: ['./model.weights.bin'],\n weights: modelArtifacts.weightSpecs,\n }];\n const modelTopologyAndWeightManifest: ModelJSON = {\n modelTopology: modelArtifacts.modelTopology,\n format: modelArtifacts.format,\n generatedBy: modelArtifacts.generatedBy,\n convertedBy: modelArtifacts.convertedBy,\n userDefinedMetadata: modelArtifacts.userDefinedMetadata,\n weightsManifest\n };\n\n init.body.append(\n 'model.json',\n new Blob(\n [JSON.stringify(modelTopologyAndWeightManifest)],\n {type: JSON_TYPE}),\n 'model.json');\n\n if (modelArtifacts.weightData != null) {\n init.body.append(\n 'model.weights.bin',\n new Blob([modelArtifacts.weightData], {type: OCTET_STREAM_MIME_TYPE}),\n 'model.weights.bin');\n }\n\n const response = await this.fetch(this.path, init);\n\n if (response.ok) {\n return {\n modelArtifactsInfo: getModelArtifactsInfoForJSON(modelArtifacts),\n responses: [response],\n };\n } else {\n throw new Error(\n `BrowserHTTPRequest.save() failed due to HTTP response status ` +\n `${response.status}.`);\n }\n }\n\n /**\n * Load model artifacts via HTTP request(s).\n *\n * See the documentation to `tf.io.http` for details on the saved\n * artifacts.\n *\n * @returns The loaded model artifacts (if loading succeeds).\n */\n async load(): Promise {\n const modelConfigRequest = await this.fetch(this.path, this.requestInit);\n\n if (!modelConfigRequest.ok) {\n throw new Error(\n `Request to ${this.path} failed with status code ` +\n `${modelConfigRequest.status}. Please verify this URL points to ` +\n `the model JSON of the model to load.`);\n }\n let modelConfig: ModelJSON;\n try {\n modelConfig = await modelConfigRequest.json();\n } catch (e) {\n let message = `Failed to parse model JSON of response from ${this.path}.`;\n // TODO(nsthorat): Remove this after some time when we're comfortable that\n // .pb files are mostly gone.\n if (this.path.endsWith('.pb')) {\n message += ' Your path contains a .pb file extension. ' +\n 'Support for .pb models have been removed in TensorFlow.js 1.0 ' +\n 'in favor of .json models. You can re-convert your Python ' +\n 'TensorFlow model using the TensorFlow.js 1.0 conversion scripts ' +\n 'or you can convert your.pb models with the \\'pb2json\\'' +\n 'NPM script in the tensorflow/tfjs-converter repository.';\n } else {\n message += ' Please make sure the server is serving valid ' +\n 'JSON for this request.';\n }\n throw new Error(message);\n }\n const modelTopology = modelConfig.modelTopology;\n const weightsManifest = modelConfig.weightsManifest;\n const generatedBy = modelConfig.generatedBy;\n const convertedBy = modelConfig.convertedBy;\n const format = modelConfig.format;\n const userDefinedMetadata = modelConfig.userDefinedMetadata;\n\n // We do not allow both modelTopology and weightsManifest to be missing.\n if (modelTopology == null && weightsManifest == null) {\n throw new Error(\n `The JSON from HTTP path ${this.path} contains neither model ` +\n `topology or manifest for weights.`);\n }\n\n let weightSpecs: WeightsManifestEntry[];\n let weightData: ArrayBuffer;\n if (weightsManifest != null) {\n const results = await this.loadWeights(weightsManifest);\n [weightSpecs, weightData] = results;\n }\n\n const artifacts: ModelArtifacts = {\n modelTopology,\n weightSpecs,\n weightData,\n userDefinedMetadata,\n generatedBy,\n convertedBy,\n format\n };\n\n const initializer = modelConfig.modelInitializer;\n if (initializer) {\n artifacts.modelInitializer = initializer;\n }\n\n return artifacts;\n }\n\n private async loadWeights(weightsManifest: WeightsManifestConfig):\n Promise<[WeightsManifestEntry[], ArrayBuffer]> {\n const weightPath = Array.isArray(this.path) ? this.path[1] : this.path;\n const [prefix, suffix] = parseUrl(weightPath);\n const pathPrefix = this.weightPathPrefix || prefix;\n\n const weightSpecs = [];\n for (const entry of weightsManifest) {\n weightSpecs.push(...entry.weights);\n }\n\n const fetchURLs: string[] = [];\n const urlPromises: Array> = [];\n for (const weightsGroup of weightsManifest) {\n for (const path of weightsGroup.paths) {\n if (this.weightUrlConverter != null) {\n urlPromises.push(this.weightUrlConverter(path));\n } else {\n fetchURLs.push(pathPrefix + path + suffix);\n }\n }\n }\n\n if (this.weightUrlConverter) {\n fetchURLs.push(...await Promise.all(urlPromises));\n }\n\n const buffers = await loadWeightsAsArrayBuffer(fetchURLs, {\n requestInit: this.requestInit,\n fetchFunc: this.fetch,\n onProgress: this.onProgress\n });\n return [weightSpecs, concatenateArrayBuffers(buffers)];\n }\n}\n\n/**\n * Extract the prefix and suffix of the url, where the prefix is the path before\n * the last file, and suffix is the search params after the last file.\n * ```\n * const url = 'http://tfhub.dev/model/1/tensorflowjs_model.pb?tfjs-format=file'\n * [prefix, suffix] = parseUrl(url)\n * // prefix = 'http://tfhub.dev/model/1/'\n * // suffix = '?tfjs-format=file'\n * ```\n * @param url the model url to be parsed.\n */\nexport function parseUrl(url: string): [string, string] {\n const lastSlash = url.lastIndexOf('/');\n const lastSearchParam = url.lastIndexOf('?');\n const prefix = url.substring(0, lastSlash);\n const suffix =\n lastSearchParam > lastSlash ? url.substring(lastSearchParam) : '';\n return [prefix + '/', suffix];\n}\n\nexport function isHTTPScheme(url: string): boolean {\n return url.match(HTTPRequest.URL_SCHEME_REGEX) != null;\n}\n\nexport const httpRouter: IORouter =\n (url: string, loadOptions?: LoadOptions) => {\n if (typeof fetch === 'undefined' &&\n (loadOptions == null || loadOptions.fetchFunc == null)) {\n // `http` uses `fetch` or `node-fetch`, if one wants to use it in\n // an environment that is not the browser or node they have to setup a\n // global fetch polyfill.\n return null;\n } else {\n let isHTTP = true;\n if (Array.isArray(url)) {\n isHTTP = url.every(urlItem => isHTTPScheme(urlItem));\n } else {\n isHTTP = isHTTPScheme(url);\n }\n if (isHTTP) {\n return http(url, loadOptions);\n }\n }\n return null;\n };\nIORouterRegistry.registerSaveRouter(httpRouter);\nIORouterRegistry.registerLoadRouter(httpRouter);\n\n/**\n * Creates an IOHandler subtype that sends model artifacts to HTTP server.\n *\n * An HTTP request of the `multipart/form-data` mime type will be sent to the\n * `path` URL. The form data includes artifacts that represent the topology\n * and/or weights of the model. In the case of Keras-style `tf.Model`, two\n * blobs (files) exist in form-data:\n * - A JSON file consisting of `modelTopology` and `weightsManifest`.\n * - A binary weights file consisting of the concatenated weight values.\n * These files are in the same format as the one generated by\n * [tfjs_converter](https://js.tensorflow.org/tutorials/import-keras.html).\n *\n * The following code snippet exemplifies the client-side code that uses this\n * function:\n *\n * ```js\n * const model = tf.sequential();\n * model.add(\n * tf.layers.dense({units: 1, inputShape: [100], activation: 'sigmoid'}));\n *\n * const saveResult = await model.save(tf.io.http(\n * 'http://model-server:5000/upload', {requestInit: {method: 'PUT'}}));\n * console.log(saveResult);\n * ```\n *\n * If the default `POST` method is to be used, without any custom parameters\n * such as headers, you can simply pass an HTTP or HTTPS URL to `model.save`:\n *\n * ```js\n * const saveResult = await model.save('http://model-server:5000/upload');\n * ```\n *\n * The following GitHub Gist\n * https://gist.github.com/dsmilkov/1b6046fd6132d7408d5257b0976f7864\n * implements a server based on [flask](https://github.com/pallets/flask) that\n * can receive the request. Upon receiving the model artifacts via the requst,\n * this particular server reconsistutes instances of [Keras\n * Models](https://keras.io/models/model/) in memory.\n *\n *\n * @param path A URL path to the model.\n * Can be an absolute HTTP path (e.g.,\n * 'http://localhost:8000/model-upload)') or a relative path (e.g.,\n * './model-upload').\n * @param requestInit Request configurations to be used when sending\n * HTTP request to server using `fetch`. It can contain fields such as\n * `method`, `credentials`, `headers`, `mode`, etc. See\n * https://developer.mozilla.org/en-US/docs/Web/API/Request/Request\n * for more information. `requestInit` must not have a body, because the\n * body will be set by TensorFlow.js. File blobs representing the model\n * topology (filename: 'model.json') and the weights of the model (filename:\n * 'model.weights.bin') will be appended to the body. If `requestInit` has a\n * `body`, an Error will be thrown.\n * @param loadOptions Optional configuration for the loading. It includes the\n * following fields:\n * - weightPathPrefix Optional, this specifies the path prefix for weight\n * files, by default this is calculated from the path param.\n * - fetchFunc Optional, custom `fetch` function. E.g., in Node.js,\n * the `fetch` from node-fetch can be used here.\n * - onProgress Optional, progress callback function, fired periodically\n * before the load is completed.\n * @returns An instance of `IOHandler`.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Loading',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nexport function http(path: string, loadOptions?: LoadOptions): IOHandler {\n return new HTTPRequest(path, loadOptions);\n}\n\n/**\n * Deprecated. Use `tf.io.http`.\n * @param path\n * @param loadOptions\n */\nexport function browserHTTPRequest(\n path: string, loadOptions?: LoadOptions): IOHandler {\n return http(path, loadOptions);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * IOHandlers that pass through the in-memory ModelArtifacts format.\n */\n\nimport {IOHandler, ModelArtifacts, SaveResult, TrainingConfig, WeightsManifestEntry} from './types';\n\nclass PassthroughLoader implements IOHandler {\n constructor(private readonly modelArtifacts?: ModelArtifacts) {}\n\n async load(): Promise {\n return this.modelArtifacts;\n }\n}\n\nclass PassthroughSaver implements IOHandler {\n constructor(\n private readonly saveHandler:\n (artifacts: ModelArtifacts) => Promise) {}\n\n async save(modelArtifacts: ModelArtifacts) {\n return this.saveHandler(modelArtifacts);\n }\n}\n\n/**\n * Creates an IOHandler that loads model artifacts from memory.\n *\n * When used in conjunction with `tf.loadLayersModel`, an instance of\n * `tf.LayersModel` (Keras-style) can be constructed from the loaded artifacts.\n *\n * ```js\n * const model = await tf.loadLayersModel(tf.io.fromMemory(\n * modelTopology, weightSpecs, weightData));\n * ```\n *\n * @param modelArtifacts a object containing model topology (i.e., parsed from\n * the JSON format).\n * @param weightSpecs An array of `WeightsManifestEntry` objects describing the\n * names, shapes, types, and quantization of the weight data.\n * @param weightData A single `ArrayBuffer` containing the weight data,\n * concatenated in the order described by the weightSpecs.\n * @param trainingConfig Model training configuration. Optional.\n *\n * @returns A passthrough `IOHandler` that simply loads the provided data.\n */\nexport function fromMemory(\n modelArtifacts: {}|ModelArtifacts, weightSpecs?: WeightsManifestEntry[],\n weightData?: ArrayBuffer, trainingConfig?: TrainingConfig): IOHandler {\n if (arguments.length === 1) {\n const isModelArtifacts =\n (modelArtifacts as ModelArtifacts).modelTopology != null ||\n (modelArtifacts as ModelArtifacts).weightSpecs != null;\n if (isModelArtifacts) {\n return new PassthroughLoader(modelArtifacts as ModelArtifacts);\n } else {\n // Legacy support: with only modelTopology.\n // TODO(cais): Remove this deprecated API.\n console.warn(\n 'Please call tf.io.fromMemory() with only one argument. ' +\n 'The argument should be of type ModelArtifacts. ' +\n 'The multi-argument signature of tf.io.fromMemory() has been ' +\n 'deprecated and will be removed in a future release.');\n return new PassthroughLoader({modelTopology: modelArtifacts as {}});\n }\n } else {\n // Legacy support.\n // TODO(cais): Remove this deprecated API.\n console.warn(\n 'Please call tf.io.fromMemory() with only one argument. ' +\n 'The argument should be of type ModelArtifacts. ' +\n 'The multi-argument signature of tf.io.fromMemory() has been ' +\n 'deprecated and will be removed in a future release.');\n return new PassthroughLoader({\n modelTopology: modelArtifacts as {},\n weightSpecs,\n weightData,\n trainingConfig\n });\n }\n}\n\n/**\n * Creates an IOHandler that passes saved model artifacts to a callback.\n *\n * ```js\n * function handleSave(artifacts) {\n * // ... do something with the artifacts ...\n * return {modelArtifactsInfo: {...}, ...};\n * }\n *\n * const saveResult = model.save(tf.io.withSaveHandler(handleSave));\n * ```\n *\n * @param saveHandler A function that accepts a `ModelArtifacts` and returns a\n * `SaveResult`.\n */\nexport function withSaveHandler(\n saveHandler: (artifacts: ModelArtifacts) =>\n Promise): IOHandler {\n return new PassthroughSaver(saveHandler);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Importing local_storage and indexed_db is necessary for the routers to be\n// registered.\nimport './indexed_db';\nimport './local_storage';\n\nimport {browserFiles} from './browser_files';\nimport {browserHTTPRequest, http, isHTTPScheme} from './http';\nimport {concatenateArrayBuffers, decodeWeights, encodeWeights, getModelArtifactsInfoForJSON} from './io_utils';\nimport {fromMemory, withSaveHandler} from './passthrough';\nimport {getLoadHandlers, getSaveHandlers, registerLoadRouter, registerSaveRouter} from './router_registry';\nimport {IOHandler, LoadHandler, LoadOptions, ModelArtifacts, ModelArtifactsInfo, ModelJSON, ModelStoreManager, OnProgressCallback, RequestDetails, SaveConfig, SaveHandler, SaveResult, WeightGroup, WeightsManifestConfig, WeightsManifestEntry} from './types';\nimport {loadWeights, weightsLoaderFactory} from './weights_loader';\n\nexport {copyModel, listModels, moveModel, removeModel} from './model_management';\nexport {\n browserFiles,\n browserHTTPRequest,\n concatenateArrayBuffers,\n decodeWeights,\n encodeWeights,\n fromMemory,\n getLoadHandlers,\n getModelArtifactsInfoForJSON,\n getSaveHandlers,\n http,\n IOHandler,\n isHTTPScheme,\n LoadHandler,\n LoadOptions,\n loadWeights,\n ModelArtifacts,\n ModelArtifactsInfo,\n ModelJSON,\n ModelStoreManager,\n OnProgressCallback,\n registerLoadRouter,\n registerSaveRouter,\n RequestDetails,\n SaveConfig,\n SaveHandler,\n SaveResult,\n WeightGroup,\n weightsLoaderFactory,\n WeightsManifestConfig,\n WeightsManifestEntry,\n withSaveHandler\n};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelBackend} from '../backends/backend';\nimport {ENGINE, ForwardFunc} from '../engine';\nimport {Reshape, ReshapeAttrs, ReshapeInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {GradSaveFunc, NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {Rank, ShapeMap, TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Reshapes a `tf.Tensor` to a given shape.\n *\n * Given an input tensor, returns a new tensor with the same values as the\n * input tensor with shape `shape`.\n *\n * If one component of shape is the special value -1, the size of that\n * dimension is computed so that the total size remains constant. In\n * particular, a shape of [-1] flattens into 1-D. At most one component of\n * shape can be -1.\n *\n * If shape is 1-D or higher, then the operation returns a tensor with shape\n * shape filled with the values of tensor. In this case, the number of\n * elements implied by shape must be the same as the number of elements in\n * tensor.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n * x.reshape([2, 2]).print();\n * ```\n *\n * @param x The input tensor to be reshaped.\n * @param shape An array of integers defining the output tensor shape.\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction reshape_(\n x: Tensor|TensorLike, shape: ShapeMap[R]): Tensor {\n const $x = convertToTensor(x, 'x', 'reshape', null);\n\n const inputs: ReshapeInputs = {x: $x};\n const attrs: ReshapeAttrs = {shape};\n const forward: ForwardFunc<\n Tensor> = (backend: KernelBackend, save: GradSaveFunc) => {\n shape = util.inferFromImplicitShape(shape, $x.size) as ShapeMap[R];\n util.assert(\n $x.size === util.sizeFromShape(shape),\n () => 'new shape and old shape must have the same number of elements.');\n save([$x]);\n return backend.reshape($x, shape);\n };\n return ENGINE.runKernelFunc(\n forward, inputs as {} as NamedTensorMap, null /* grad */, Reshape,\n attrs as {} as NamedAttrMap);\n}\nexport const reshape = op({reshape_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE, ForwardFunc} from '../engine';\nimport {BatchMatMul, BatchMatMulAttrs, BatchMatMulInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor, Tensor3D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the dot product of two matrices, A * B. These must be matrices.\n *\n * ```js\n * const a = tf.tensor2d([1, 2], [1, 2]);\n * const b = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * a.matMul(b).print(); // or tf.matMul(a, b)\n * ```\n * @param a First matrix in dot product operation.\n * @param b Second matrix in dot product operation.\n * @param transposeA If true, `a` is transposed before multiplication.\n * @param transposeB If true, `b` is transposed before multiplication.\n *\n * @doc {heading: 'Operations', subheading: 'Matrices'}\n */\nfunction matMul_(\n a: T|TensorLike, b: T|TensorLike, transposeA = false,\n transposeB = false): T {\n let $a = convertToTensor(a, 'a', 'matMul');\n let $b = convertToTensor(b, 'b', 'matMul');\n [$a, $b] = makeTypesMatch($a, $b);\n\n util.assert(\n $a.rank >= 2 && $b.rank >= 2 && $a.rank === $b.rank,\n () => `Error in matMul: inputs must have the same rank of at least 2, ` +\n `got ranks ${$a.rank} and ${$b.rank}.`);\n\n const innerShapeA =\n transposeA ? $a.shape[$a.rank - 2] : $a.shape[$a.rank - 1];\n const innerShapeB =\n transposeB ? $b.shape[$b.rank - 1] : $b.shape[$b.rank - 2];\n\n const outerShapeA =\n transposeA ? $a.shape[$a.rank - 1] : $a.shape[$a.rank - 2];\n const outerShapeB =\n transposeB ? $b.shape[$b.rank - 2] : $b.shape[$b.rank - 1];\n\n const outerDimsA = $a.shape.slice(0, -2);\n const outerDimsB = $b.shape.slice(0, -2);\n const batchDimA = util.sizeFromShape(outerDimsA);\n const batchDimB = util.sizeFromShape(outerDimsB);\n\n util.assert(\n util.arraysEqual(outerDimsA, outerDimsB),\n () => `Error in matMul: outer dimensions (${outerDimsA}) and (` +\n `${outerDimsB}) of Tensors with shapes ${$a.shape} and ` +\n `${$b.shape} must match.`);\n\n util.assert(\n innerShapeA === innerShapeB,\n () => `Error in matMul: inner shapes (${innerShapeA}) and (` +\n `${innerShapeB}) of Tensors with shapes ${$a.shape} and ` +\n `${$b.shape} and transposeA=${transposeA}` +\n ` and transposeB=${transposeB} must match.`);\n\n const outShape = $a.shape.slice(0, -2).concat([outerShapeA, outerShapeB]);\n\n const a3D = transposeA ? reshape($a, [batchDimA, innerShapeA, outerShapeA]) :\n reshape($a, [batchDimA, outerShapeA, innerShapeA]);\n const b3D = transposeB ? reshape($b, [batchDimB, outerShapeB, innerShapeB]) :\n reshape($b, [batchDimB, innerShapeB, outerShapeB]);\n\n const forward: ForwardFunc = (backend, save) => {\n save([a3D, b3D]);\n\n return backend.batchMatMul(\n a3D as Tensor3D, b3D as Tensor3D, transposeA, transposeB);\n };\n\n const inputs: BatchMatMulInputs = {a: a3D, b: b3D};\n\n const attrs: BatchMatMulAttrs = {transposeA, transposeB};\n\n const res = ENGINE.runKernelFunc(\n forward, inputs as {} as NamedTensorMap, null /* grad */, BatchMatMul,\n attrs as {} as NamedAttrMap);\n\n return reshape(res, outShape) as T;\n}\n\nexport const matMul = op({matMul_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE, ForwardFunc} from '../engine';\nimport {OneHot, OneHotAttrs, OneHotInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Creates a one-hot `tf.Tensor`. The locations represented by `indices` take\n * value `onValue` (defaults to 1), while all other locations take value\n * `offValue` (defaults to 0). If `indices` is rank `R`, the output has rank\n * `R+1` with the last axis of size `depth`.\n *\n * ```js\n * tf.oneHot(tf.tensor1d([0, 1], 'int32'), 3).print();\n * ```\n *\n * @param indices `tf.Tensor` of indices with dtype `int32`.\n * @param depth The depth of the one hot dimension.\n * @param onValue A number used to fill in the output when the index matches\n * the location.\n * @param offValue A number used to fill in the output when the index does\n * not match the location.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction oneHot_(\n indices: Tensor|TensorLike, depth: number, onValue = 1,\n offValue = 0): Tensor {\n if (depth < 2) {\n throw new Error(`Error in oneHot: depth must be >=2, but it is ${depth}`);\n }\n const $indices = convertToTensor(indices, 'indices', 'oneHot', 'int32');\n const outShape = [...$indices.shape, depth];\n\n const forward: ForwardFunc = (backend, save) => {\n save([$indices]);\n return reshape(\n backend.oneHot(\n reshape($indices, [$indices.size]), depth, onValue, offValue),\n outShape);\n };\n\n const inputs: OneHotInputs = {indices: $indices};\n const attrs: OneHotAttrs = {depth, onValue, offValue};\n\n return ENGINE.runKernelFunc(\n forward, inputs as unknown as NamedTensorMap, null /* grad */, OneHot,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const oneHot = op({oneHot_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Transpose, TransposeAttrs, TransposeInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Transposes the `tf.Tensor`. Permutes the dimensions according to `perm`.\n *\n * The returned `tf.Tensor`'s dimension `i` will correspond to the input\n * dimension `perm[i]`. If `perm` is not given, it is set to `[n-1...0]`,\n * where `n` is the rank of the input `tf.Tensor`. Hence by default, this\n * operation performs a regular matrix transpose on 2-D input `tf.Tensor`s.\n *\n * ```js\n * const a = tf.tensor2d([1, 2, 3, 4, 5, 6], [2, 3]);\n *\n * a.transpose().print(); // or tf.transpose(a)\n * ```\n *\n * @param x The tensor to transpose.\n * @param perm The permutation of the dimensions of a.\n *\n * @doc {heading: 'Operations', subheading: 'Matrices'}\n */\nfunction transpose_(x: T|TensorLike, perm?: number[]): T {\n const $x = convertToTensor(x, 'x', 'transpose');\n\n if (perm == null) {\n perm = $x.shape.map((s, i) => i).reverse();\n }\n util.assert(\n $x.rank === perm.length,\n () => `Error in transpose: rank of input ${$x.rank} ` +\n `must match length of perm ${perm}.`);\n perm.forEach(axis => {\n util.assert(\n axis >= 0 && axis < $x.rank,\n () => `All entries in 'perm' must be between 0 and ${$x.rank - 1}` +\n ` but got ${perm}`);\n });\n\n if ($x.rank <= 1) {\n return $x.clone();\n }\n\n const inputs: TransposeInputs = {x: $x};\n const attrs: TransposeAttrs = {perm};\n\n return ENGINE.runKernelFunc(\n backend => backend.transpose($x, perm), inputs as {} as NamedTensorMap,\n null /* gradient */, Transpose, attrs as {} as NamedAttrMap);\n}\n\nexport const transpose = op({transpose_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor1D, Tensor2D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {cast} from './cast';\nimport {matMul} from './mat_mul';\nimport {oneHot} from './one_hot';\nimport {op} from './operation';\nimport {transpose} from './transpose';\n\n/**\n * Computes the confusion matrix from true labels and predicted labels.\n *\n * ```js\n * const labels = tf.tensor1d([0, 1, 2, 1, 0], 'int32');\n * const predictions = tf.tensor1d([0, 2, 2, 1, 0], 'int32');\n * const numClasses = 3;\n * const out = tf.math.confusionMatrix(labels, predictions, numClasses);\n * out.print();\n * // Expected output matrix:\n * // [[2, 0, 0],\n * // [0, 1, 1],\n * // [0, 0, 1]]\n * ```\n *\n * @param labels The target labels, assumed to be 0-based integers\n * for the classes. The shape is `[numExamples]`, where\n * `numExamples` is the number of examples included.\n * @param predictions The predicted classes, assumed to be\n * 0-based integers for the classes. Must have the same shape as `labels`.\n * @param numClasses Number of all classes, as an integer.\n * Its value must be larger than the largest element in `labels` and\n * `predictions`.\n * @returns The confusion matrix as a int32-type 2D tensor. The value at\n * row `r` and column `c` is the number of times examples of actual class\n * `r` were predicted as class `c`.\n *\n * @doc {heading: 'Operations', subheading: 'Evaluation'}\n */\nexport function confusionMatrix_(\n labels: Tensor1D|TensorLike, predictions: Tensor1D|TensorLike,\n numClasses: number): Tensor2D {\n const $labels = convertToTensor(labels, 'labels', 'confusionMatrix');\n const $predictions =\n convertToTensor(predictions, 'predictions', 'confusionMatrix');\n\n util.assert(\n numClasses == null || numClasses > 0 && Number.isInteger(numClasses),\n () => `If provided, numClasses must be a positive integer, ` +\n `but got ${numClasses}`);\n util.assert(\n $labels.rank === 1,\n () => `Expected the rank of labels to be 1, but got ${$labels.rank}`);\n util.assert(\n $predictions.rank === 1,\n () => `Expected the rank of predictions to be 1, ` +\n `but got ${$predictions.rank}`);\n util.assert(\n $labels.shape[0] === $predictions.shape[0],\n () => `Mismatch in the number of examples: ` +\n `${$labels.shape[0]} vs. ${$predictions.shape[0]}. ` +\n `Labels and predictions should have the same number of elements.`);\n util.assert(\n numClasses > 0 && Number.isInteger(numClasses),\n () => `numClasses is required to be a positive integer, but got ` +\n `${numClasses}`);\n // TODO(cais): In the future, if oneHot supports tensors inputs for\n // `numClasses`, `confusionMatrix` can make `numClasses` optional.\n\n const oneHotLabels = oneHot(cast($labels, 'int32'), numClasses) as Tensor2D;\n const oneHotPredictions =\n oneHot(cast($predictions, 'int32'), numClasses) as Tensor2D;\n const oneHotLabelsT: Tensor2D = transpose(oneHotLabels);\n return cast(matMul(oneHotLabelsT, oneHotPredictions), 'int32');\n}\n\nexport const confusionMatrix = op({confusionMatrix_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * Exports under the tf.math.* namespace.\n */\n\nimport {confusionMatrix} from './ops/confusion_matrix';\n\nexport {confusionMatrix};\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor3D} from '../tensor';\nimport {inferShape} from '../tensor_util_env';\nimport {TensorLike3D} from '../types';\nimport {DataType} from '../types';\nimport {assertNonNull} from '../util';\nimport {makeTensor} from './tensor_ops_util';\n\n/**\n * Creates rank-3 `tf.Tensor` with the provided values, shape and dtype.\n *\n * The same functionality can be achieved with `tf.tensor`, but in general\n * we recommend using `tf.tensor3d` as it makes the code more readable.\n *\n * ```js\n * // Pass a nested array.\n * tf.tensor3d([[[1], [2]], [[3], [4]]]).print();\n * ```\n * ```js\n * // Pass a flat array and specify a shape.\n * tf.tensor3d([1, 2, 3, 4], [2, 2, 1]).print();\n * ```\n *\n * @param values The values of the tensor. Can be nested array of numbers,\n * or a flat array, or a `TypedArray`.\n * @param shape The shape of the tensor. If not provided, it is inferred from\n * `values`.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function tensor3d(\n values: TensorLike3D, shape?: [number, number, number],\n dtype?: DataType): Tensor3D {\n assertNonNull(values);\n if (shape != null && shape.length !== 3) {\n throw new Error('tensor3d() requires shape to have three numbers');\n }\n const inferredShape = inferShape(values, dtype);\n if (inferredShape.length !== 3 && inferredShape.length !== 1) {\n throw new Error(\n 'tensor3d() requires values to be number[][][] or flat/TypedArray');\n }\n if (inferredShape.length === 1 && shape == null) {\n throw new Error(\n 'tensor3d() requires shape to be provided when `values` ' +\n 'are a flat array');\n }\n return makeTensor(values, shape, inferredShape, dtype) as Tensor3D;\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {FromPixels, FromPixelsAttrs, FromPixelsInputs} from '../kernel_names';\nimport {getKernel, NamedAttrMap} from '../kernel_registry';\nimport {Tensor, Tensor2D, Tensor3D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {PixelData, TensorLike} from '../types';\n\nimport {cast} from './cast';\nimport {op} from './operation';\nimport {tensor3d} from './tensor3d';\n\nlet fromPixels2DContext: CanvasRenderingContext2D;\n\n/**\n * Creates a `tf.Tensor` from an image.\n *\n * ```js\n * const image = new ImageData(1, 1);\n * image.data[0] = 100;\n * image.data[1] = 150;\n * image.data[2] = 200;\n * image.data[3] = 255;\n *\n * tf.browser.fromPixels(image).print();\n * ```\n *\n * @param pixels The input image to construct the tensor from. The\n * supported image types are all 4-channel. You can also pass in an image\n * object with following attributes:\n * `{data: Uint8Array; width: number; height: number}`\n * @param numChannels The number of channels of the output tensor. A\n * numChannels value less than 4 allows you to ignore channels. Defaults to\n * 3 (ignores alpha channel of input image).\n *\n * @doc {heading: 'Browser', namespace: 'browser', ignoreCI: true}\n */\nfunction fromPixels_(\n pixels: PixelData|ImageData|HTMLImageElement|HTMLCanvasElement|\n HTMLVideoElement,\n numChannels = 3): Tensor3D {\n // Sanity checks.\n if (numChannels > 4) {\n throw new Error(\n 'Cannot construct Tensor with more than 4 channels from pixels.');\n }\n if (pixels == null) {\n throw new Error('pixels passed to tf.browser.fromPixels() can not be null');\n }\n let isPixelData = false;\n let isImageData = false;\n let isVideo = false;\n let isImage = false;\n let isCanvasLike = false;\n if ((pixels as PixelData).data instanceof Uint8Array) {\n isPixelData = true;\n } else if (\n typeof (ImageData) !== 'undefined' && pixels instanceof ImageData) {\n isImageData = true;\n } else if (\n typeof (HTMLVideoElement) !== 'undefined' &&\n pixels instanceof HTMLVideoElement) {\n isVideo = true;\n } else if (\n typeof (HTMLImageElement) !== 'undefined' &&\n pixels instanceof HTMLImageElement) {\n isImage = true;\n // tslint:disable-next-line: no-any\n } else if ((pixels as any).getContext != null) {\n isCanvasLike = true;\n } else {\n throw new Error(\n 'pixels passed to tf.browser.fromPixels() must be either an ' +\n `HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData ` +\n `in browser, or OffscreenCanvas, ImageData in webworker` +\n ` or {data: Uint32Array, width: number, height: number}, ` +\n `but was ${(pixels as {}).constructor.name}`);\n }\n if (isVideo) {\n const HAVE_CURRENT_DATA_READY_STATE = 2;\n if (isVideo &&\n (pixels as HTMLVideoElement).readyState <\n HAVE_CURRENT_DATA_READY_STATE) {\n throw new Error(\n 'The video element has not loaded data yet. Please wait for ' +\n '`loadeddata` event on the