1234567 |
- /*
- Face-API
- homepage: <https://github.com/vladmandic/face-api>
- author: <https://github.com/vladmandic>'
- */
- "use strict";var ln=Object.create;var tr=Object.defineProperty;var dn=Object.getOwnPropertyDescriptor;var hn=Object.getOwnPropertyNames;var bn=Object.getPrototypeOf,gn=Object.prototype.hasOwnProperty;var xn=(o,t)=>()=>(t||o((t={exports:{}}).exports,t),t.exports),Sr=(o,t)=>{for(var e in t)tr(o,e,{get:t[e],enumerable:!0})},_o=(o,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of hn(t))!gn.call(o,n)&&n!==e&&tr(o,n,{get:()=>t[n],enumerable:!(r=dn(t,n))||r.enumerable});return o};var v=(o,t,e)=>(e=o!=null?ln(bn(o)):{},_o(t||!o||!o.__esModule?tr(e,"default",{value:o,enumerable:!0}):e,o)),vn=o=>_o(tr({},"__esModule",{value:!0}),o);var x=xn((Ya,Br)=>{"use strict";var Wr=Object.defineProperty,yn=Object.getOwnPropertyDescriptor,_n=Object.getOwnPropertyNames,Tn=Object.prototype.hasOwnProperty,Pn=(o,t)=>{for(var e in t)Wr(o,e,{get:t[e],enumerable:!0})},Ar=(o,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of _n(t))!Tn.call(o,n)&&n!==e&&Wr(o,n,{get:()=>t[n],enumerable:!(r=yn(t,n))||r.enumerable});return o},wn=(o,t,e)=>(Ar(o,t,"default"),e&&Ar(e,t,"default")),Fn=o=>Ar(Wr({},"__esModule",{value:!0}),o),kr={};Pn(kr,{version:()=>In});Br.exports=Fn(kr);wn(kr,require("@tensorflow/tfjs-node-gpu"),Br.exports);var To="4.21.0",Dn="4.21.0",En="4.21.0",Mn="4.21.0",Cn="4.21.0",In={tfjs:To,"tfjs-core":To,"tfjs-converter":Dn,"tfjs-backend-cpu":En,"tfjs-backend-webgl":Mn,"tfjs-backend-wasm":Cn}});var Ba={};Sr(Ba,{AgeGenderNet:()=>He,BoundingBox:()=>Ot,Box:()=>L,ComposableTask:()=>J,ComputeAllFaceDescriptorsTask:()=>_t,ComputeFaceDescriptorsTaskBase:()=>Ue,ComputeSingleFaceDescriptorTask:()=>Tt,DetectAllFaceLandmarksTask:()=>qe,DetectAllFacesTask:()=>Ie,DetectFaceLandmarksTaskBase:()=>Je,DetectFacesTaskBase:()=>Ke,DetectSingleFaceLandmarksTask:()=>Ze,DetectSingleFaceTask:()=>Qe,Dimensions:()=>R,FACE_EXPRESSION_LABELS:()=>so,FaceDetection:()=>M,FaceDetectionNet:()=>lo,FaceExpressionNet:()=>Oe,FaceExpressions:()=>gt,FaceLandmark68Net:()=>Zt,FaceLandmark68TinyNet:()=>ze,FaceLandmarkNet:()=>po,FaceLandmarks:()=>H,FaceLandmarks5:()=>jr,FaceLandmarks68:()=>Yt,FaceMatch:()=>me,FaceMatcher:()=>vo,FaceRecognitionNet:()=>Kt,Gender:()=>_r,LabeledBox:()=>pe,LabeledFaceDescriptors:()=>Et,NetInput:()=>ut,NeuralNetwork:()=>A,ObjectDetection:()=>Ht,Point:()=>_,PredictedBox:()=>Ur,Rect:()=>zt,SsdMobilenetv1:()=>It,SsdMobilenetv1Options:()=>X,TinyFaceDetector:()=>re,TinyFaceDetectorOptions:()=>je,TinyYolov2:()=>te,TinyYolov2Options:()=>st,allFaces:()=>Sa,allFacesSsdMobilenetv1:()=>un,allFacesTinyYolov2:()=>La,awaitMediaLoaded:()=>to,bufferToImage:()=>eo,computeFaceDescriptor:()=>xa,createCanvas:()=>Xt,createCanvasFromMedia:()=>We,createFaceDetectionNet:()=>ua,createFaceRecognitionNet:()=>ta,createSsdMobilenetv1:()=>Jo,createTinyFaceDetector:()=>Aa,createTinyYolov2:()=>da,detectAllFaces:()=>Lr,detectFaceLandmarks:()=>mn,detectFaceLandmarksTiny:()=>ga,detectLandmarks:()=>Ia,detectSingleFace:()=>Na,draw:()=>co,env:()=>w,euclideanDistance:()=>xo,extendWithAge:()=>Dr,extendWithFaceDescriptor:()=>Fr,extendWithFaceDetection:()=>Vt,extendWithFaceExpressions:()=>gr,extendWithFaceLandmarks:()=>Pe,extendWithGender:()=>Er,extractFaceTensors:()=>le,extractFaces:()=>fe,fetchImage:()=>On,fetchJson:()=>no,fetchNetWeights:()=>Hn,fetchOrThrow:()=>ht,fetchVideo:()=>zn,getContext2dOrThrow:()=>$,getMediaDimensions:()=>Ut,imageTensorToCanvas:()=>ro,imageToSquare:()=>oo,inverseSigmoid:()=>Sn,iou:()=>zr,isMediaElement:()=>sr,isMediaLoaded:()=>Ae,isWithAge:()=>ea,isWithFaceDetection:()=>pt,isWithFaceExpressions:()=>io,isWithFaceLandmarks:()=>qt,isWithGender:()=>ra,loadAgeGenderModel:()=>Ea,loadFaceDetectionModel:()=>Ma,loadFaceExpressionModel:()=>Da,loadFaceLandmarkModel:()=>Pa,loadFaceLandmarkTinyModel:()=>wa,loadFaceRecognitionModel:()=>Fa,loadSsdMobilenetv1Model:()=>pn,loadTinyFaceDetectorModel:()=>_a,loadTinyYolov2Model:()=>Ta,loadWeightMap:()=>ao,locateFaces:()=>Ca,matchDimensions:()=>Yn,minBbox:()=>Yr,nets:()=>F,nonMaxSuppression:()=>Vr,normalize:()=>rt,padToSquare:()=>Gr,predictAgeAndGender:()=>ya,recognizeFaceExpressions:()=>va,resizeResults:()=>fn,resolveInput:()=>Gt,shuffleArray:()=>Ln,sigmoid:()=>Ne,ssdMobilenetv1:()=>cn,tf:()=>Wa,tinyFaceDetector:()=>ha,tinyYolov2:()=>ba,toNetInput:()=>D,utils:()=>Hr,validateConfig:()=>ho,version:()=>ka});module.exports=vn(Ba);var Wa=v(x());var co={};Sr(co,{AnchorPosition:()=>Qr,DrawBox:()=>Se,DrawBoxOptions:()=>nr,DrawFaceLandmarks:()=>vr,DrawFaceLandmarksOptions:()=>xr,DrawTextField:()=>jt,DrawTextFieldOptions:()=>ue,drawContour:()=>lt,drawDetections:()=>$n,drawFaceExpressions:()=>Vn,drawFaceLandmarks:()=>jn});function lt(o,t,e=!1){if(o.beginPath(),t.slice(1).forEach(({x:r,y:n},s)=>{let a=t[s];o.moveTo(a.x,a.y),o.lineTo(r,n)}),e){let r=t[t.length-1],n=t[0];if(!r||!n)return;o.moveTo(r.x,r.y),o.lineTo(n.x,n.y)}o.stroke()}var Hr={};Sr(Hr,{computeReshapedDimensions:()=>Or,getCenterPoint:()=>$t,isDimensions:()=>rr,isEven:()=>er,isFloat:()=>$r,isTensor:()=>Bt,isTensor1D:()=>Nn,isTensor2D:()=>Rr,isTensor3D:()=>dt,isTensor4D:()=>U,isValidNumber:()=>et,isValidProbablitiy:()=>ce,range:()=>ct,round:()=>Rt});var Po=v(x());var R=class o{constructor(t,e){if(!et(t)||!et(e))throw new Error(`Dimensions.constructor - expected width and height to be valid numbers, instead have ${JSON.stringify({width:t,height:e})}`);this._width=t,this._height=e}get width(){return this._width}get height(){return this._height}reverse(){return new o(1/this.width,1/this.height)}};function Bt(o,t){return o instanceof Po.Tensor&&o.shape.length===t}function Nn(o){return Bt(o,1)}function Rr(o){return Bt(o,2)}function dt(o){return Bt(o,3)}function U(o){return Bt(o,4)}function $r(o){return o%1!==0}function er(o){return o%2===0}function Rt(o,t=2){let e=10**t;return Math.floor(o*e)/e}function rr(o){return o&&o.width&&o.height}function Or({width:o,height:t},e){let r=e/Math.max(t,o);return new R(Math.round(o*r),Math.round(t*r))}function $t(o){return o.reduce((t,e)=>t.add(e),new _(0,0)).div(new _(o.length,o.length))}function ct(o,t,e){return Array(o).fill(0).map((r,n)=>t+n*e)}function et(o){return!!o&&o!==1/0&&o!==-1/0&&!Number.isNaN(o)||o===0}function ce(o){return et(o)&&o>=0&&o<=1}var _=class o{constructor(t,e){this._x=t,this._y=e}get x(){return this._x}get y(){return this._y}add(t){return new o(this.x+t.x,this.y+t.y)}sub(t){return new o(this.x-t.x,this.y-t.y)}mul(t){return new o(this.x*t.x,this.y*t.y)}div(t){return new o(this.x/t.x,this.y/t.y)}abs(){return new o(Math.abs(this.x),Math.abs(this.y))}magnitude(){return Math.sqrt(this.x**2+this.y**2)}floor(){return new o(Math.floor(this.x),Math.floor(this.y))}};var L=class o{static isRect(t){return!!t&&[t.x,t.y,t.width,t.height].every(et)}static assertIsValidBox(t,e,r=!1){if(!o.isRect(t))throw new Error(`${e} - invalid box: ${JSON.stringify(t)}, expected object with properties x, y, width, height`);if(!r&&(t.width<0||t.height<0))throw new Error(`${e} - width (${t.width}) and height (${t.height}) must be positive numbers`)}constructor(t,e=!0){let r=t||{},n=[r.left,r.top,r.right,r.bottom].every(et),s=[r.x,r.y,r.width,r.height].every(et);if(!s&&!n)throw new Error(`Box.constructor - expected box to be IBoundingBox | IRect, instead have ${JSON.stringify(r)}`);let[a,i,c,m]=s?[r.x,r.y,r.width,r.height]:[r.left,r.top,r.right-r.left,r.bottom-r.top];o.assertIsValidBox({x:a,y:i,width:c,height:m},"Box.constructor",e),this._x=a,this._y=i,this._width=c,this._height=m}get x(){return this._x}get y(){return this._y}get width(){return this._width}get height(){return this._height}get left(){return this.x}get top(){return this.y}get right(){return this.x+this.width}get bottom(){return this.y+this.height}get area(){return this.width*this.height}get topLeft(){return new _(this.left,this.top)}get topRight(){return new _(this.right,this.top)}get bottomLeft(){return new _(this.left,this.bottom)}get bottomRight(){return new _(this.right,this.bottom)}round(){let[t,e,r,n]=[this.x,this.y,this.width,this.height].map(s=>Math.round(s));return new o({x:t,y:e,width:r,height:n})}floor(){let[t,e,r,n]=[this.x,this.y,this.width,this.height].map(s=>Math.floor(s));return new o({x:t,y:e,width:r,height:n})}toSquare(){let{x:t,y:e,width:r,height:n}=this,s=Math.abs(r-n);return r<n&&(t-=s/2,r+=s),n<r&&(e-=s/2,n+=s),new o({x:t,y:e,width:r,height:n})}rescale(t){let e=rr(t)?t.width:t,r=rr(t)?t.height:t;return new o({x:this.x*e,y:this.y*r,width:this.width*e,height:this.height*r})}pad(t,e){let[r,n,s,a]=[this.x-t/2,this.y-e/2,this.width+t,this.height+e];return new o({x:r,y:n,width:s,height:a})}clipAtImageBorders(t,e){let{x:r,y:n,right:s,bottom:a}=this,i=Math.max(r,0),c=Math.max(n,0),m=s-i,p=a-c,u=Math.min(m,t-i),f=Math.min(p,e-c);return new o({x:i,y:c,width:u,height:f}).floor()}shift(t,e){let{width:r,height:n}=this,s=this.x+t,a=this.y+e;return new o({x:s,y:a,width:r,height:n})}padAtBorders(t,e){let r=this.width+1,n=this.height+1,s=1,a=1,i=r,c=n,m=this.left,p=this.top,u=this.right,f=this.bottom;return u>e&&(i=-u+e+r,u=e),f>t&&(c=-f+t+n,f=t),m<1&&(c=2-m,m=1),p<1&&(c=2-p,p=1),{dy:a,edy:c,dx:s,edx:i,y:p,ey:f,x:m,ex:u,w:r,h:n}}calibrate(t){return new o({left:this.left+t.left*this.width,top:this.top+t.top*this.height,right:this.right+t.right*this.width,bottom:this.bottom+t.bottom*this.height}).toSquare().round()}};var Ot=class extends L{constructor(t,e,r,n,s=!1){super({left:t,top:e,right:r,bottom:n},s)}};var Ht=class o{constructor(t,e,r,n,s){this._imageDims=new R(s.width,s.height),this._score=t,this._classScore=e,this._className=r,this._box=new L(n).rescale(this._imageDims)}get score(){return this._score}get classScore(){return this._classScore}get className(){return this._className}get box(){return this._box}get imageDims(){return this._imageDims}get imageWidth(){return this.imageDims.width}get imageHeight(){return this.imageDims.height}get relativeBox(){return new L(this._box).rescale(this.imageDims.reverse())}forSize(t,e){return new o(this.score,this.classScore,this.className,this.relativeBox,{width:t,height:e})}};var M=class o extends Ht{constructor(t,e,r){super(t,t,"",e,r)}forSize(t,e){let{score:r,relativeBox:n,imageDims:s}=super.forSize(t,e);return new o(r,n,s)}};function zr(o,t,e=!0){let r=Math.max(0,Math.min(o.right,t.right)-Math.max(o.left,t.left)),n=Math.max(0,Math.min(o.bottom,t.bottom)-Math.max(o.top,t.top)),s=r*n;return e?s/(o.area+t.area-s):s/Math.min(o.area,t.area)}function Yr(o){let t=o.map(i=>i.x),e=o.map(i=>i.y),r=t.reduce((i,c)=>c<i?c:i,1/0),n=e.reduce((i,c)=>c<i?c:i,1/0),s=t.reduce((i,c)=>i<c?c:i,0),a=e.reduce((i,c)=>i<c?c:i,0);return new Ot(r,n,s,a)}function Vr(o,t,e,r=!0){let n=t.map((a,i)=>({score:a,boxIndex:i})).sort((a,i)=>a.score-i.score).map(a=>a.boxIndex),s=[];for(;n.length>0;){let a=n.pop();s.push(a);let i=n,c=[];for(let m=0;m<i.length;m++){let p=i[m],u=o[a],f=o[p];c.push(zr(u,f,r))}n=n.filter((m,p)=>c[p]<=e)}return s}var mt=v(x());function rt(o,t){return mt.tidy(()=>{let[e,r,n]=t,s=mt.fill([...o.shape.slice(0,3),1],e,"float32"),a=mt.fill([...o.shape.slice(0,3),1],r,"float32"),i=mt.fill([...o.shape.slice(0,3),1],n,"float32"),c=mt.concat([s,a,i],3);return mt.sub(o,c)})}var Dt=v(x());function Gr(o,t=!1){return Dt.tidy(()=>{let[e,r]=o.shape.slice(1);if(e===r)return o;let n=Math.abs(e-r),s=Math.round(n*(t?.5:1)),a=e>r?2:1,i=f=>{let l=o.shape.slice();return l[a]=f,Dt.fill(l,0,"float32")},c=i(s),m=n-c.shape[a],u=[t&&m?i(m):null,o,c].filter(f=>!!f).map(f=>Dt.cast(f,"float32"));return Dt.concat(u,a)})}function Ln(o){let t=o.slice();for(let e=t.length-1;e>0;e--){let r=Math.floor(Math.random()*(e+1)),n=t[e];t[e]=t[r],t[r]=n}return t}function Ne(o){return 1/(1+Math.exp(-o))}function Sn(o){return Math.log(o/(1-o))}var zt=class extends L{constructor(t,e,r,n,s=!1){super({x:t,y:e,width:r,height:n},s)}};var An=.5,Wn=.43,kn=.45,H=class{constructor(t,e,r=new _(0,0)){let{width:n,height:s}=e;this._imgDims=new R(n,s),this._shift=r,this._positions=t.map(a=>a.mul(new _(n,s)).add(r))}get shift(){return new _(this._shift.x,this._shift.y)}get imageWidth(){return this._imgDims.width}get imageHeight(){return this._imgDims.height}get positions(){return this._positions}get relativePositions(){return this._positions.map(t=>t.sub(this._shift).div(new _(this.imageWidth,this.imageHeight)))}forSize(t,e){return new this.constructor(this.relativePositions,{width:t,height:e})}shiftBy(t,e){return new this.constructor(this.relativePositions,this._imgDims,new _(t,e))}shiftByPoint(t){return this.shiftBy(t.x,t.y)}align(t,e={}){if(t){let s=t instanceof M?t.box.floor():new L(t);return this.shiftBy(s.x,s.y).align(null,e)}let{useDlibAlignment:r,minBoxPadding:n}={useDlibAlignment:!1,minBoxPadding:.2,...e};return r?this.alignDlib():this.alignMinBbox(n)}alignDlib(){let t=this.getRefPointsForAlignment(),[e,r,n]=t,s=u=>n.sub(u).magnitude(),a=(s(e)+s(r))/2,i=Math.floor(a/kn),c=$t(t),m=Math.floor(Math.max(0,c.x-An*i)),p=Math.floor(Math.max(0,c.y-Wn*i));return new zt(m,p,Math.min(i,this.imageWidth+m),Math.min(i,this.imageHeight+p))}alignMinBbox(t){let e=Yr(this.positions);return e.pad(e.width*t,e.height*t)}getRefPointsForAlignment(){throw new Error("getRefPointsForAlignment not implemented by base class")}};var jr=class extends H{getRefPointsForAlignment(){let t=this.positions;return[t[0],t[1],$t([t[3],t[4]])]}};var Yt=class extends H{getJawOutline(){return this.positions.slice(0,17)}getLeftEyeBrow(){return this.positions.slice(17,22)}getRightEyeBrow(){return this.positions.slice(22,27)}getNose(){return this.positions.slice(27,36)}getLeftEye(){return this.positions.slice(36,42)}getRightEye(){return this.positions.slice(42,48)}getMouth(){return this.positions.slice(48,68)}getRefPointsForAlignment(){return[this.getLeftEye(),this.getRightEye(),this.getMouth()].map($t)}};var me=class{constructor(t,e){this._label=t,this._distance=e}get label(){return this._label}get distance(){return this._distance}toString(t=!0){return`${this.label}${t?` (${Rt(this.distance)})`:""}`}};var pe=class extends L{static assertIsValidLabeledBox(t,e){if(L.assertIsValidBox(t,e),!et(t.label))throw new Error(`${e} - expected property label (${t.label}) to be a number`)}constructor(t,e){super(t),this._label=e}get label(){return this._label}};var Et=class o{constructor(t,e){if(typeof t!="string")throw new Error("LabeledFaceDescriptors - constructor expected label to be a string");if(!Array.isArray(e)||e.some(r=>!(r instanceof Float32Array)))throw new Error("LabeledFaceDescriptors - constructor expected descriptors to be an array of Float32Array");this._label=t,this._descriptors=e}get label(){return this._label}get descriptors(){return this._descriptors}toJSON(){return{label:this.label,descriptors:this.descriptors.map(t=>Array.from(t))}}static fromJSON(t){let e=t.descriptors.map(r=>new Float32Array(r));return new o(t.label,e)}};var Ur=class extends pe{static assertIsValidPredictedBox(t,e){if(pe.assertIsValidLabeledBox(t,e),!ce(t.score)||!ce(t.classScore))throw new Error(`${e} - expected properties score (${t.score}) and (${t.classScore}) to be a number between [0, 1]`)}constructor(t,e,r,n){super(t,e),this._score=r,this._classScore=n}get score(){return this._score}get classScore(){return this._classScore}};function pt(o){return o.detection instanceof M}function Vt(o,t){return{...o,...{detection:t}}}function Xr(){let o=window.fetch;if(!o)throw new Error("fetch - missing fetch implementation for browser environment");return{Canvas:HTMLCanvasElement,CanvasRenderingContext2D,Image:HTMLImageElement,ImageData,Video:HTMLVideoElement,createCanvasElement:()=>document.createElement("canvas"),createImageElement:()=>document.createElement("img"),createVideoElement:()=>document.createElement("video"),fetch:o,readFile:()=>{throw new Error("readFile - filesystem not available for browser environment")}}}function Le(){return typeof global=="object"&&typeof process!="undefined"&&process.versions!=null&&process.versions.node!=null}function or(o){let t="";if(!o&&Le())try{o=require("fs")}catch(r){t=r.toString()}return{readFile:o?r=>new Promise((n,s)=>{o.readFile(r,(a,i)=>a?s(a):n(i))}):()=>{throw new Error(`readFile - failed to require fs in nodejs environment with error: ${t}`)}}}function Jr(){let o=global.Canvas||global.HTMLCanvasElement,t=global.Image||global.HTMLImageElement,e=global.Video||global.HTMLVideoElement,r=()=>{if(o)return new o;throw new Error("createCanvasElement - missing Canvas implementation for nodejs environment")},n=()=>{if(t)return new t;throw new Error("createImageElement - missing Image implementation for nodejs environment")},s=()=>{if(e)return new e;throw new Error("createVideoElement - missing Video implementation for nodejs environment")},a=global.fetch,i=or();return{Canvas:o||class{},CanvasRenderingContext2D:global.CanvasRenderingContext2D||class{},Image:t||class{},ImageData:global.ImageData||class{},Video:global.HTMLVideoElement||class{},createCanvasElement:r,createImageElement:n,createVideoElement:s,fetch:a,...i}}function qr(){return typeof window=="object"&&typeof document!="undefined"&&typeof HTMLImageElement!="undefined"&&typeof HTMLCanvasElement!="undefined"&&typeof HTMLVideoElement!="undefined"&&typeof ImageData!="undefined"&&typeof CanvasRenderingContext2D!="undefined"}var S;function Bn(){if(!S)throw new Error("getEnv - environment is not defined, check isNodejs() and isBrowser()");return S}function Zr(o){S=o}function Kr(){return qr()?Zr(Xr()):Le()?Zr(Jr()):null}function Rn(o){if(S||Kr(),!S)throw new Error("monkeyPatch - environment is not defined, check isNodejs() and isBrowser()");let{Canvas:t=S.Canvas,Image:e=S.Image}=o;S.Canvas=t,S.Image=e,S.createCanvasElement=o.createCanvasElement||(()=>new t),S.createImageElement=o.createImageElement||(()=>new e),S.ImageData=o.ImageData||S.ImageData,S.Video=o.Video||S.Video,S.fetch=o.fetch||S.fetch,S.readFile=o.readFile||S.readFile}var w={getEnv:Bn,setEnv:Zr,initialize:Kr,createBrowserEnv:Xr,createFileSystem:or,createNodejsEnv:Jr,monkeyPatch:Rn,isBrowser:qr,isNodejs:Le};Kr();function Gt(o){return!w.isNodejs()&&typeof o=="string"?document.getElementById(o):o}function $(o){let{Canvas:t,CanvasRenderingContext2D:e}=w.getEnv();if(o instanceof e)return o;let r=Gt(o);if(!(r instanceof t))throw new Error("resolveContext2d - expected canvas to be of instance of Canvas");let n=r.getContext("2d",{willReadFrequently:!0});if(!n)throw new Error("resolveContext2d - canvas 2d context is null");return n}var Qr=(n=>(n.TOP_LEFT="TOP_LEFT",n.TOP_RIGHT="TOP_RIGHT",n.BOTTOM_LEFT="BOTTOM_LEFT",n.BOTTOM_RIGHT="BOTTOM_RIGHT",n))(Qr||{}),ue=class{constructor(t={}){let{anchorPosition:e,backgroundColor:r,fontColor:n,fontSize:s,fontStyle:a,padding:i}=t;this.anchorPosition=e||"TOP_LEFT",this.backgroundColor=r||"rgba(0, 0, 0, 0.5)",this.fontColor=n||"rgba(255, 255, 255, 1)",this.fontSize=s||14,this.fontStyle=a||"Georgia",this.padding=i||4}},jt=class o{constructor(t,e,r={}){this.text=typeof t=="string"?[t]:t instanceof o?t.text:t,this.anchor=e,this.options=new ue(r)}measureWidth(t){let{padding:e}=this.options;return this.text.map(r=>t.measureText(r).width).reduce((r,n)=>r<n?n:r,0)+2*e}measureHeight(){let{fontSize:t,padding:e}=this.options;return this.text.length*t+2*e}getUpperLeft(t,e){let{anchorPosition:r}=this.options,n=r==="BOTTOM_RIGHT"||r==="TOP_RIGHT",s=r==="BOTTOM_LEFT"||r==="BOTTOM_RIGHT",a=this.measureWidth(t),i=this.measureHeight(),c=n?this.anchor.x-a:this.anchor.x,m=s?this.anchor.y-i:this.anchor.y;if(e){let{width:p,height:u}=e,f=Math.max(Math.min(c,p-a),0),l=Math.max(Math.min(m,u-i),0);return{x:f,y:l}}return{x:c,y:m}}draw(t){let e=Gt(t),r=$(e),{backgroundColor:n,fontColor:s,fontSize:a,fontStyle:i,padding:c}=this.options;r.font=`${a}px ${i}`;let m=this.measureWidth(r),p=this.measureHeight();r.fillStyle=n;let u=this.getUpperLeft(r,e);r.fillRect(u.x,u.y,m,p),r.fillStyle=s,this.text.forEach((f,l)=>{let b=c+u.x,T=c+u.y+(l+1)*a;r.fillText(f,b,T)})}};var nr=class{constructor(t={}){let{boxColor:e,lineWidth:r,label:n,drawLabelOptions:s}=t;this.boxColor=e||"rgba(0, 0, 255, 1)",this.lineWidth=r||2,this.label=n;let a={anchorPosition:"BOTTOM_LEFT",backgroundColor:this.boxColor};this.drawLabelOptions=new ue({...a,...s})}},Se=class{constructor(t,e={}){this.box=new L(t),this.options=new nr(e)}draw(t){let e=$(t),{boxColor:r,lineWidth:n}=this.options,{x:s,y:a,width:i,height:c}=this.box;e.strokeStyle=r,e.lineWidth=n,e.strokeRect(s,a,i,c);let{label:m}=this.options;m&&new jt([m],{x:s-n/2,y:a},this.options.drawLabelOptions).draw(t)}};function $n(o,t){(Array.isArray(t)?t:[t]).forEach(r=>{let n=r instanceof M?r.score:pt(r)?r.detection.score:void 0,s=r instanceof M?r.box:pt(r)?r.detection.box:new L(r),a=n?`${Rt(n)}`:void 0;new Se(s,{label:a}).draw(o)})}var Te=v(x());function Ae(o){let{Image:t,Video:e}=w.getEnv();return o instanceof t&&o.complete||o instanceof e&&o.readyState>=3}function to(o){return new Promise((t,e)=>{if(o instanceof w.getEnv().Canvas||Ae(o)){t(null);return}function r(s){s.currentTarget&&(s.currentTarget.removeEventListener("load",n),s.currentTarget.removeEventListener("error",r),e(s))}function n(s){s.currentTarget&&(s.currentTarget.removeEventListener("load",n),s.currentTarget.removeEventListener("error",r),t(s))}o.addEventListener("load",n),o.addEventListener("error",r)})}function eo(o){return new Promise((t,e)=>{o instanceof Blob||e(new Error("bufferToImage - expected buf to be of type: Blob"));let r=new FileReader;r.onload=()=>{typeof r.result!="string"&&e(new Error("bufferToImage - expected reader.result to be a string, in onload"));let n=w.getEnv().createImageElement();n.onload=()=>t(n),n.onerror=e,n.src=r.result},r.onerror=e,r.readAsDataURL(o)})}function Ut(o){let{Image:t,Video:e}=w.getEnv();return o instanceof t?new R(o.naturalWidth,o.naturalHeight):o instanceof e?new R(o.videoWidth,o.videoHeight):new R(o.width,o.height)}function Xt({width:o,height:t}){let{createCanvasElement:e}=w.getEnv(),r=e();return r.width=o,r.height=t,r}function We(o,t){let{ImageData:e}=w.getEnv();if(!(o instanceof e)&&!Ae(o))throw new Error("createCanvasFromMedia - media has not finished loading yet");let{width:r,height:n}=t||Ut(o),s=Xt({width:r,height:n});return o instanceof e?$(s).putImageData(o,0,0):$(s).drawImage(o,0,0,r,n),s}var ar=v(x());async function ro(o,t){let e=t||w.getEnv().createCanvasElement(),[r,n,s]=o.shape.slice(U(o)?1:0),a=ar.tidy(()=>o.as3D(r,n,s).toInt());return await ar.browser.toPixels(a,e),a.dispose(),e}function sr(o){let{Image:t,Canvas:e,Video:r}=w.getEnv();return o instanceof t||o instanceof e||o instanceof r}var z=v(x());function oo(o,t,e=!1){let{Image:r,Canvas:n}=w.getEnv();if(!(o instanceof r||o instanceof n))throw new Error("imageToSquare - expected arg0 to be HTMLImageElement | HTMLCanvasElement");if(t<=0)return Xt({width:1,height:1});let s=Ut(o),a=t/Math.max(s.height,s.width),i=a*s.width,c=a*s.height,m=Xt({width:t,height:t}),p=o instanceof n?o:We(o),u=Math.abs(i-c)/2,f=e&&i<c?u:0,l=e&&c<i?u:0;return p.width>0&&p.height>0&&$(m).drawImage(p,f,l,i,c),m}var ut=class{constructor(t,e=!1){this._imageTensors=[];this._canvases=[];this._treatAsBatchInput=!1;this._inputDimensions=[];this._inputSize=0;if(!Array.isArray(t))throw new Error(`NetInput.constructor - expected inputs to be an Array of TResolvedNetInput or to be instanceof tf.Tensor4D, instead have ${t}`);this._treatAsBatchInput=e,this._batchSize=t.length,t.forEach((r,n)=>{if(dt(r)){this._imageTensors[n]=r,this._inputDimensions[n]=r.shape;return}if(U(r)){let a=r.shape[0];if(a!==1)throw new Error(`NetInput - tf.Tensor4D with batchSize ${a} passed, but not supported in input array`);this._imageTensors[n]=r,this._inputDimensions[n]=r.shape.slice(1);return}let s=r instanceof w.getEnv().Canvas?r:We(r);this._canvases[n]=s,this._inputDimensions[n]=[s.height,s.width,3]})}get imageTensors(){return this._imageTensors}get canvases(){return this._canvases}get isBatchInput(){return this.batchSize>1||this._treatAsBatchInput}get batchSize(){return this._batchSize}get inputDimensions(){return this._inputDimensions}get inputSize(){return this._inputSize}get reshapedInputDimensions(){return ct(this.batchSize,0,1).map((t,e)=>this.getReshapedInputDimensions(e))}getInput(t){return this.canvases[t]||this.imageTensors[t]}getInputDimensions(t){return this._inputDimensions[t]}getInputHeight(t){return this._inputDimensions[t][0]}getInputWidth(t){return this._inputDimensions[t][1]}getReshapedInputDimensions(t){if(typeof this.inputSize!="number")throw new Error("getReshapedInputDimensions - inputSize not set, toBatchTensor has not been called yet");let e=this.getInputWidth(t),r=this.getInputHeight(t);return Or({width:e,height:r},this.inputSize)}toBatchTensor(t,e=!0){return this._inputSize=t,z.tidy(()=>{let r=ct(this.batchSize,0,1).map(s=>{let a=this.getInput(s);if(a instanceof z.Tensor){let i=U(a)?a:z.expandDims(a);return i=Gr(i,e),(i.shape[1]!==t||i.shape[2]!==t)&&(i=z.image.resizeBilinear(i,[t,t],!1,!1)),i.as3D(t,t,3)}if(a instanceof w.getEnv().Canvas)return z.browser.fromPixels(oo(a,t,e));throw new Error(`toBatchTensor - at batchIdx ${s}, expected input to be instanceof tf.Tensor or instanceof HTMLCanvasElement, instead have ${a}`)});return z.stack(r.map(s=>z.cast(s,"float32"))).as4D(this.batchSize,t,t,3)})}};async function D(o){if(o instanceof ut)return o;let t=Array.isArray(o)?o:[o];if(!t.length)throw new Error("toNetInput - empty array passed as input");let e=n=>Array.isArray(o)?` at input index ${n}:`:"",r=t.map(Gt);return r.forEach((n,s)=>{if(!sr(n)&&!dt(n)&&!U(n))throw typeof t[s]=="string"?new Error(`toNetInput -${e(s)} string passed, but could not resolve HTMLElement for element id ${t[s]}`):new Error(`toNetInput -${e(s)} expected media to be of type HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | tf.Tensor3D, or to be an element id`);if(U(n)){let a=n.shape[0];if(a!==1)throw new Error(`toNetInput -${e(s)} tf.Tensor4D with batchSize ${a} passed, but not supported in input array`)}}),await Promise.all(r.map(n=>sr(n)&&to(n))),new ut(r,Array.isArray(o))}async function fe(o,t){let{Canvas:e}=w.getEnv(),r=o;if(!(o instanceof e)){let a=await D(o);if(a.batchSize>1)throw new Error("extractFaces - batchSize > 1 not supported");let i=a.getInput(0);r=i instanceof e?i:await ro(i)}let n=$(r);return t.map(a=>a instanceof M?a.forSize(r.width,r.height).box.floor():a).map(a=>a.clipAtImageBorders(r.width,r.height)).map(({x:a,y:i,width:c,height:m})=>{let p=Xt({width:c,height:m});return c>0&&m>0&&$(p).putImageData(n.getImageData(a,i,c,m),0,0),p})}var ir=v(x());async function le(o,t){if(!dt(o)&&!U(o))throw new Error("extractFaceTensors - expected image tensor to be 3D or 4D");if(U(o)&&o.shape[0]>1)throw new Error("extractFaceTensors - batchSize > 1 not supported");return ir.tidy(()=>{let[e,r,n]=o.shape.slice(U(o)?1:0);return t.map(i=>i instanceof M?i.forSize(r,e).box:i).map(i=>i.clipAtImageBorders(r,e)).filter(i=>i.width>0&&i.height>0).map(({x:i,y:c,width:m,height:p})=>ir.slice3d(o.as3D(e,r,n),[c,i,0],[p,m,n]))})}async function ht(o,t){let{fetch:e}=w.getEnv(),r=await e(o,t);if(!(r.status<400))throw new Error(`failed to fetch: (${r.status}) ${r.statusText}, from url: ${r.url}`);return r}async function On(o){let t=await ht(o),e=await t.blob();if(!e.type.startsWith("image/"))throw new Error(`fetchImage - expected blob type to be of type image/*, instead have: ${e.type}, for url: ${t.url}`);return eo(e)}async function no(o){return(await ht(o)).json()}async function Hn(o){return new Float32Array(await(await ht(o)).arrayBuffer())}function wo(o){return new Promise((t,e)=>{o instanceof Blob||e(new Error("bufferToVideo - expected buf to be of type: Blob"));let r=w.getEnv().createVideoElement();r.oncanplay=()=>t(r),r.onerror=e,r.playsInline=!0,r.muted=!0,r.src=URL.createObjectURL(o),r.play()})}async function zn(o){let t=await ht(o),e=await t.blob();if(!e.type.startsWith("video/"))throw new Error(`fetchVideo - expected blob type to be of type video/*, instead have: ${e.type}, for url: ${t.url}`);return wo(e)}var Fo=v(x());function cr(o,t){let e=`${t}-weights_manifest.json`;if(!o)return{modelBaseUri:"",manifestUri:e};if(o==="/")return{modelBaseUri:"/",manifestUri:`/${e}`};let r=o.startsWith("http://")?"http://":o.startsWith("https://")?"https://":"";o=o.replace(r,"");let n=o.split("/").filter(i=>i),s=o.endsWith(".json")?n[n.length-1]:e,a=r+(o.endsWith(".json")?n.slice(0,n.length-1):n).join("/");return a=o.startsWith("/")?`/${a}`:a,{modelBaseUri:a,manifestUri:a==="/"?`/${s}`:`${a}/${s}`}}async function ao(o,t){let{manifestUri:e,modelBaseUri:r}=cr(o,t),n=await no(e);return Fo.io.loadWeights(n,r)}function Yn(o,t,e=!1){let{width:r,height:n}=e?Ut(t):t;return o.width=r,o.height=n,{width:r,height:n}}var ve=v(x());var bt=v(x());var A=class{constructor(t){this._params=void 0;this._paramMappings=[];this._name=t}get params(){return this._params}get paramMappings(){return this._paramMappings}get isLoaded(){return!!this.params}getParamFromPath(t){let{obj:e,objProp:r}=this.traversePropertyPath(t);return e[r]}reassignParamFromPath(t,e){let{obj:r,objProp:n}=this.traversePropertyPath(t);r[n].dispose(),r[n]=e}getParamList(){return this._paramMappings.map(({paramPath:t})=>({path:t,tensor:this.getParamFromPath(t)}))}getTrainableParams(){return this.getParamList().filter(t=>t.tensor instanceof bt.Variable)}getFrozenParams(){return this.getParamList().filter(t=>!(t.tensor instanceof bt.Variable))}variable(){this.getFrozenParams().forEach(({path:t,tensor:e})=>{this.reassignParamFromPath(t,e.variable())})}freeze(){this.getTrainableParams().forEach(({path:t,tensor:e})=>{let r=bt.tensor(e.dataSync());e.dispose(),this.reassignParamFromPath(t,r)})}dispose(t=!0){this.getParamList().forEach(e=>{if(t&&e.tensor.isDisposed)throw new Error(`param tensor has already been disposed for path ${e.path}`);e.tensor.dispose()}),this._params=void 0}serializeParams(){return new Float32Array(this.getParamList().map(({tensor:t})=>Array.from(t.dataSync())).reduce((t,e)=>t.concat(e)))}async load(t){if(t instanceof Float32Array){this.extractWeights(t);return}await this.loadFromUri(t)}async loadFromUri(t){if(t&&typeof t!="string")throw new Error(`${this._name}.loadFromUri - expected model uri`);let e=await ao(t,this.getDefaultModelName());this.loadFromWeightMap(e)}async loadFromDisk(t){if(t&&typeof t!="string")throw new Error(`${this._name}.loadFromDisk - expected model file path`);let{readFile:e}=w.getEnv(),{manifestUri:r,modelBaseUri:n}=cr(t,this.getDefaultModelName()),s=m=>Promise.all(m.map(p=>e(p).then(u=>typeof u=="string"?Buffer.from(u):u.buffer))),a=bt.io.weightsLoaderFactory(s),i=JSON.parse((await e(r)).toString()),c=await a(i,n);this.loadFromWeightMap(c)}loadFromWeightMap(t){let{paramMappings:e,params:r}=this.extractParamsFromWeightMap(t);this._paramMappings=e,this._params=r}extractWeights(t){let{paramMappings:e,params:r}=this.extractParams(t);this._paramMappings=e,this._params=r}traversePropertyPath(t){if(!this.params)throw new Error("traversePropertyPath - model has no loaded params");let e=t.split("/").reduce((s,a)=>{if(!s.nextObj.hasOwnProperty(a))throw new Error(`traversePropertyPath - object does not have property ${a}, for path ${t}`);return{obj:s.nextObj,objProp:a,nextObj:s.nextObj[a]}},{nextObj:this.params}),{obj:r,objProp:n}=e;if(!r||!n||!(r[n]instanceof bt.Tensor))throw new Error(`traversePropertyPath - parameter is not a tensor, for path ${t}`);return{obj:r,objProp:n}}};var E=v(x());var de=v(x());function O(o,t,e){return de.tidy(()=>{let r=de.separableConv2d(o,t.depthwise_filter,t.pointwise_filter,e,"same");return r=de.add(r,t.bias),r})}function mr(o,t,e=!1){return E.tidy(()=>{let r=E.relu(e?E.add(E.conv2d(o,t.conv0.filters,[2,2],"same"),t.conv0.bias):O(o,t.conv0,[2,2])),n=O(r,t.conv1,[1,1]),s=E.relu(E.add(r,n)),a=O(s,t.conv2,[1,1]);return E.relu(E.add(r,E.add(n,a)))})}function ke(o,t,e=!1,r=!0){return E.tidy(()=>{let n=E.relu(e?E.add(E.conv2d(o,t.conv0.filters,r?[2,2]:[1,1],"same"),t.conv0.bias):O(o,t.conv0,r?[2,2]:[1,1])),s=O(n,t.conv1,[1,1]),a=E.relu(E.add(n,s)),i=O(a,t.conv2,[1,1]),c=E.relu(E.add(n,E.add(s,i))),m=O(c,t.conv3,[1,1]);return E.relu(E.add(n,E.add(s,E.add(i,m))))})}var Mt=v(x());function Jt(o,t,e="same",r=!1){return Mt.tidy(()=>{let n=Mt.add(Mt.conv2d(o,t.filters,[1,1],e),t.bias);return r?Mt.relu(n):n})}function W(o,t){Object.keys(o).forEach(e=>{t.some(r=>r.originalPath===e)||o[e].dispose()})}var pr=v(x());function he(o,t){return(e,r,n,s)=>{let a=pr.tensor4d(o(e*r*n*n),[n,n,e,r]),i=pr.tensor1d(o(r));return t.push({paramPath:`${s}/filters`},{paramPath:`${s}/bias`}),{filters:a,bias:i}}}var ur=v(x());function fr(o,t){return(e,r,n)=>{let s=ur.tensor2d(o(e*r),[e,r]),a=ur.tensor1d(o(r));return t.push({paramPath:`${n}/weights`},{paramPath:`${n}/bias`}),{weights:s,bias:a}}}var Re=v(x());var Be=class{constructor(t,e,r){this.depthwise_filter=t;this.pointwise_filter=e;this.bias=r}};function be(o,t){return(e,r,n)=>{let s=Re.tensor4d(o(9*e),[3,3,e,1]),a=Re.tensor4d(o(e*r),[1,1,e,r]),i=Re.tensor1d(o(r));return t.push({paramPath:`${n}/depthwise_filter`},{paramPath:`${n}/pointwise_filter`},{paramPath:`${n}/bias`}),new Be(s,a,i)}}function ge(o){return t=>{let e=o(`${t}/depthwise_filter`,4),r=o(`${t}/pointwise_filter`,4),n=o(`${t}/bias`,1);return new Be(e,r,n)}}function Y(o,t){return(e,r,n)=>{let s=o[e];if(!Bt(s,r))throw new Error(`expected weightMap[${e}] to be a Tensor${r}D, instead have ${s}`);return t.push({originalPath:e,paramPath:n||e}),s}}function k(o){let t=o;function e(n){let s=t.slice(0,n);return t=t.slice(n),s}function r(){return t}return{extractWeights:e,getRemainingWeights:r}}function lr(o,t){let e=he(o,t),r=be(o,t);function n(a,i,c,m=!1){let p=m?e(a,i,3,`${c}/conv0`):r(a,i,`${c}/conv0`),u=r(i,i,`${c}/conv1`),f=r(i,i,`${c}/conv2`);return{conv0:p,conv1:u,conv2:f}}function s(a,i,c,m=!1){let{conv0:p,conv1:u,conv2:f}=n(a,i,c,m),l=r(i,i,`${c}/conv3`);return{conv0:p,conv1:u,conv2:f,conv3:l}}return{extractDenseBlock3Params:n,extractDenseBlock4Params:s}}function Do(o){let t=[],{extractWeights:e,getRemainingWeights:r}=k(o),{extractDenseBlock4Params:n}=lr(e,t),s=n(3,32,"dense0",!0),a=n(32,64,"dense1"),i=n(64,128,"dense2"),c=n(128,256,"dense3");if(r().length!==0)throw new Error(`weights remaing after extract: ${r().length}`);return{paramMappings:t,params:{dense0:s,dense1:a,dense2:i,dense3:c}}}function dr(o){return t=>{let e=o(`${t}/filters`,4),r=o(`${t}/bias`,1);return{filters:e,bias:r}}}function hr(o,t){let e=Y(o,t),r=dr(e),n=ge(e);function s(i,c=!1){let m=c?r(`${i}/conv0`):n(`${i}/conv0`),p=n(`${i}/conv1`),u=n(`${i}/conv2`);return{conv0:m,conv1:p,conv2:u}}function a(i,c=!1){let m=c?r(`${i}/conv0`):n(`${i}/conv0`),p=n(`${i}/conv1`),u=n(`${i}/conv2`),f=n(`${i}/conv3`);return{conv0:m,conv1:p,conv2:u,conv3:f}}return{extractDenseBlock3Params:s,extractDenseBlock4Params:a}}function Eo(o){let t=[],{extractDenseBlock4Params:e}=hr(o,t),r={dense0:e("dense0",!0),dense1:e("dense1"),dense2:e("dense2"),dense3:e("dense3")};return W(o,t),{params:r,paramMappings:t}}var xe=class extends A{constructor(){super("FaceFeatureExtractor")}forwardInput(t){let{params:e}=this;if(!e)throw new Error("FaceFeatureExtractor - load model before inference");return ve.tidy(()=>{let r=ve.cast(t.toBatchTensor(112,!0),"float32"),s=rt(r,[122.782,117.001,104.298]).div(255),a=ke(s,e.dense0,!0);return a=ke(a,e.dense1),a=ke(a,e.dense2),a=ke(a,e.dense3),a=ve.avgPool(a,[7,7],[2,2],"valid"),a})}async forward(t){return this.forwardInput(await D(t))}getDefaultModelName(){return"face_feature_extractor_model"}extractParamsFromWeightMap(t){return Eo(t)}extractParams(t){return Do(t)}};var Io=v(x());var ye=v(x());function $e(o,t){return ye.tidy(()=>ye.add(ye.matMul(o,t.weights),t.bias))}function Mo(o,t,e){let r=[],{extractWeights:n,getRemainingWeights:s}=k(o),i=fr(n,r)(t,e,"fc");if(s().length!==0)throw new Error(`weights remaing after extract: ${s().length}`);return{paramMappings:r,params:{fc:i}}}function Co(o){let t=[],e=Y(o,t);function r(s){let a=e(`${s}/weights`,2),i=e(`${s}/bias`,1);return{weights:a,bias:i}}let n={fc:r("fc")};return W(o,t),{params:n,paramMappings:t}}function br(o){let t={},e={};return Object.keys(o).forEach(r=>{let n=r.startsWith("fc")?e:t;n[r]=o[r]}),{featureExtractorMap:t,classifierMap:e}}var _e=class extends A{constructor(t,e){super(t),this._faceFeatureExtractor=e}get faceFeatureExtractor(){return this._faceFeatureExtractor}runNet(t){let{params:e}=this;if(!e)throw new Error(`${this._name} - load model before inference`);return Io.tidy(()=>{let r=t instanceof ut?this.faceFeatureExtractor.forwardInput(t):t;return $e(r.as2D(r.shape[0],-1),e.fc)})}dispose(t=!0){this.faceFeatureExtractor.dispose(t),super.dispose(t)}loadClassifierParams(t){let{params:e,paramMappings:r}=this.extractClassifierParams(t);this._params=e,this._paramMappings=r}extractClassifierParams(t){return Mo(t,this.getClassifierChannelsIn(),this.getClassifierChannelsOut())}extractParamsFromWeightMap(t){let{featureExtractorMap:e,classifierMap:r}=br(t);return this.faceFeatureExtractor.loadFromWeightMap(e),Co(r)}extractParams(t){let e=this.getClassifierChannelsIn(),r=this.getClassifierChannelsOut(),n=r*e+r,s=t.slice(0,t.length-n),a=t.slice(t.length-n);return this.faceFeatureExtractor.extractWeights(s),this.extractClassifierParams(a)}};var so=["neutral","happy","sad","angry","fearful","disgusted","surprised"],gt=class{constructor(t){this.neutral=0;this.happy=0;this.sad=0;this.angry=0;this.fearful=0;this.disgusted=0;this.surprised=0;if(t.length!==7)throw new Error(`FaceExpressions.constructor - expected probabilities.length to be 7, have: ${t.length}`);so.forEach((e,r)=>{this[e]=t[r]})}asSortedArray(){return so.map(t=>({expression:t,probability:this[t]})).sort((t,e)=>e.probability-t.probability)}};var Oe=class extends _e{constructor(t=new xe){super("FaceExpressionNet",t)}forwardInput(t){return Te.tidy(()=>Te.softmax(this.runNet(t)))}async forward(t){return this.forwardInput(await D(t))}async predictExpressions(t){let e=await D(t),r=await this.forwardInput(e),n=await Promise.all(Te.unstack(r).map(async a=>{let i=a.dataSync();return a.dispose(),i}));r.dispose();let s=n.map(a=>new gt(a));return e.isBatchInput?s:s[0]}getDefaultModelName(){return"face_expression_model"}getClassifierChannelsIn(){return 256}getClassifierChannelsOut(){return 7}};function io(o){return o.expressions instanceof gt}function gr(o,t){return{...o,...{expressions:t}}}function Vn(o,t,e=.1,r){(Array.isArray(t)?t:[t]).forEach(s=>{let a=s instanceof gt?s:io(s)?s.expressions:void 0;if(!a)throw new Error("drawFaceExpressions - expected faceExpressions to be FaceExpressions | WithFaceExpressions<{}> or array thereof");let c=a.asSortedArray().filter(u=>u.probability>e),m=pt(s)?s.detection.box.bottomLeft:r||new _(0,0);new jt(c.map(u=>`${u.expression} (${Rt(u.probability)})`),m).draw(o)})}function qt(o){return pt(o)&&o.landmarks instanceof H&&o.unshiftedLandmarks instanceof H&&o.alignedRect instanceof M}function Gn(o){let t=c=>c*180/Math.PI,e=(c,m)=>Math.sqrt((c.x-m.x)**2+(c.y-m.y)**2),r={roll:void 0,pitch:void 0,yaw:void 0},n=(c,m,p)=>{let u=Math.floor(c.x-m.x),f=Math.floor(m.x-p.x);return u-f},s=(c,m)=>{let p=Math.hypot(m.x-c.x,m.y-c.y),u=m.y-c.y,f=Math.asin(u/p),l=t(f),b=Math.floor(90-l),T=m.x-c.x<0?-1:1;return b*T},a=(c,m,p)=>{let u=e(c,p),f=new _((c.x+p.x)/2,(c.y+p.y)/2),l=e(m,f),b=Math.atan(l/u),T=Math.floor(t(b)),h=f.y-m.y<0?-1:1;return T*h};if(!o||!o.positions||o.positions.length!==68)return r;let i=o.positions;return r.roll=s(i[27],i[66]),r.pitch=a(i[14],i[30],i[2]),r.yaw=n(i[14],i[33],i[2]),r}function Pe(o,t){let{box:e}=o.detection,r=t.shiftBy(e.x,e.y),n=r.align(),{imageDims:s}=o.detection,a=new M(o.detection.score,n.rescale(s.reverse()),s),i=Gn(t);return{...o,...{landmarks:r,unshiftedLandmarks:t,alignedRect:a,angle:i}}}var xr=class{constructor(t={}){let{drawLines:e=!0,drawPoints:r=!0,lineWidth:n,lineColor:s,pointSize:a,pointColor:i}=t;this.drawLines=e,this.drawPoints=r,this.lineWidth=n||1,this.pointSize=a||2,this.lineColor=s||"rgba(0, 255, 255, 1)",this.pointColor=i||"rgba(255, 0, 255, 1)"}},vr=class{constructor(t,e={}){this.faceLandmarks=t,this.options=new xr(e)}draw(t){let e=$(t),{drawLines:r,drawPoints:n,lineWidth:s,lineColor:a,pointSize:i,pointColor:c}=this.options;if(r&&this.faceLandmarks instanceof Yt&&(e.strokeStyle=a,e.lineWidth=s,lt(e,this.faceLandmarks.getJawOutline()),lt(e,this.faceLandmarks.getLeftEyeBrow()),lt(e,this.faceLandmarks.getRightEyeBrow()),lt(e,this.faceLandmarks.getNose()),lt(e,this.faceLandmarks.getLeftEye(),!0),lt(e,this.faceLandmarks.getRightEye(),!0),lt(e,this.faceLandmarks.getMouth(),!0)),n){e.strokeStyle=c,e.fillStyle=c;let m=p=>{e.beginPath(),e.arc(p.x,p.y,i,0,2*Math.PI),e.fill()};this.faceLandmarks.positions.forEach(m)}}};function jn(o,t){(Array.isArray(t)?t:[t]).forEach(r=>{let n=r instanceof H?r:qt(r)?r.landmarks:void 0;if(!n)throw new Error("drawFaceLandmarks - expected faceExpressions to be FaceLandmarks | WithFaceLandmarks<WithFaceDetection<{}>> or array thereof");new vr(n).draw(o)})}var No="1.7.14";var ft=v(x());var N=v(x());function Jn(o,t){let e=he(o,t),r=be(o,t);function n(a,i,c){let m=r(a,i,`${c}/separable_conv0`),p=r(i,i,`${c}/separable_conv1`),u=e(a,i,1,`${c}/expansion_conv`);return{separable_conv0:m,separable_conv1:p,expansion_conv:u}}function s(a,i){let c=r(a,a,`${i}/separable_conv0`),m=r(a,a,`${i}/separable_conv1`),p=r(a,a,`${i}/separable_conv2`);return{separable_conv0:c,separable_conv1:m,separable_conv2:p}}return{extractConvParams:e,extractSeparableConvParams:r,extractReductionBlockParams:n,extractMainBlockParams:s}}function Lo(o,t){let e=[],{extractWeights:r,getRemainingWeights:n}=k(o),{extractConvParams:s,extractSeparableConvParams:a,extractReductionBlockParams:i,extractMainBlockParams:c}=Jn(r,e),m=s(3,32,3,"entry_flow/conv_in"),p=i(32,64,"entry_flow/reduction_block_0"),u=i(64,128,"entry_flow/reduction_block_1"),f={conv_in:m,reduction_block_0:p,reduction_block_1:u},l={};ct(t,0,1).forEach(g=>{l[`main_block_${g}`]=c(128,`middle_flow/main_block_${g}`)});let b=i(128,256,"exit_flow/reduction_block"),T=a(256,512,"exit_flow/separable_conv"),h={reduction_block:b,separable_conv:T};if(n().length!==0)throw new Error(`weights remaing after extract: ${n().length}`);return{paramMappings:e,params:{entry_flow:f,middle_flow:l,exit_flow:h}}}function qn(o,t){let e=Y(o,t),r=dr(e),n=ge(e);function s(i){let c=n(`${i}/separable_conv0`),m=n(`${i}/separable_conv1`),p=r(`${i}/expansion_conv`);return{separable_conv0:c,separable_conv1:m,expansion_conv:p}}function a(i){let c=n(`${i}/separable_conv0`),m=n(`${i}/separable_conv1`),p=n(`${i}/separable_conv2`);return{separable_conv0:c,separable_conv1:m,separable_conv2:p}}return{extractConvParams:r,extractSeparableConvParams:n,extractReductionBlockParams:s,extractMainBlockParams:a}}function So(o,t){let e=[],{extractConvParams:r,extractSeparableConvParams:n,extractReductionBlockParams:s,extractMainBlockParams:a}=qn(o,e),i=r("entry_flow/conv_in"),c=s("entry_flow/reduction_block_0"),m=s("entry_flow/reduction_block_1"),p={conv_in:i,reduction_block_0:c,reduction_block_1:m},u={};ct(t,0,1).forEach(T=>{u[`main_block_${T}`]=a(`middle_flow/main_block_${T}`)});let f=s("exit_flow/reduction_block"),l=n("exit_flow/separable_conv"),b={reduction_block:f,separable_conv:l};return W(o,e),{params:{entry_flow:p,middle_flow:u,exit_flow:b},paramMappings:e}}function Ao(o,t,e){return N.add(N.conv2d(o,t.filters,e,"same"),t.bias)}function mo(o,t,e=!0){let r=e?N.relu(o):o;return r=O(r,t.separable_conv0,[1,1]),r=O(N.relu(r),t.separable_conv1,[1,1]),r=N.maxPool(r,[3,3],[2,2],"same"),r=N.add(r,Ao(o,t.expansion_conv,[2,2])),r}function Zn(o,t){let e=O(N.relu(o),t.separable_conv0,[1,1]);return e=O(N.relu(e),t.separable_conv1,[1,1]),e=O(N.relu(e),t.separable_conv2,[1,1]),e=N.add(e,o),e}var yr=class extends A{constructor(t){super("TinyXception"),this._numMainBlocks=t}forwardInput(t){let{params:e}=this;if(!e)throw new Error("TinyXception - load model before inference");return N.tidy(()=>{let r=N.cast(t.toBatchTensor(112,!0),"float32"),s=rt(r,[122.782,117.001,104.298]).div(255),a=N.relu(Ao(s,e.entry_flow.conv_in,[2,2]));return a=mo(a,e.entry_flow.reduction_block_0,!1),a=mo(a,e.entry_flow.reduction_block_1),ct(this._numMainBlocks,0,1).forEach(i=>{a=Zn(a,e.middle_flow[`main_block_${i}`])}),a=mo(a,e.exit_flow.reduction_block),a=N.relu(O(a,e.exit_flow.separable_conv,[1,1])),a})}async forward(t){return this.forwardInput(await D(t))}getDefaultModelName(){return"tiny_xception_model"}extractParamsFromWeightMap(t){return So(t,this._numMainBlocks)}extractParams(t){return Lo(t,this._numMainBlocks)}};function Wo(o){let t=[],{extractWeights:e,getRemainingWeights:r}=k(o),n=fr(e,t),s=n(512,1,"fc/age"),a=n(512,2,"fc/gender");if(r().length!==0)throw new Error(`weights remaing after extract: ${r().length}`);return{paramMappings:t,params:{fc:{age:s,gender:a}}}}function ko(o){let t=[],e=Y(o,t);function r(s){let a=e(`${s}/weights`,2),i=e(`${s}/bias`,1);return{weights:a,bias:i}}let n={fc:{age:r("fc/age"),gender:r("fc/gender")}};return W(o,t),{params:n,paramMappings:t}}var _r=(e=>(e.FEMALE="female",e.MALE="male",e))(_r||{});var He=class extends A{constructor(t=new yr(2)){super("AgeGenderNet"),this._faceFeatureExtractor=t}get faceFeatureExtractor(){return this._faceFeatureExtractor}runNet(t){let{params:e}=this;if(!e)throw new Error(`${this._name} - load model before inference`);return ft.tidy(()=>{let r=t instanceof ut?this.faceFeatureExtractor.forwardInput(t):t,n=ft.avgPool(r,[7,7],[2,2],"valid").as2D(r.shape[0],-1),s=$e(n,e.fc.age).as1D(),a=$e(n,e.fc.gender);return{age:s,gender:a}})}forwardInput(t){return ft.tidy(()=>{let{age:e,gender:r}=this.runNet(t);return{age:e,gender:ft.softmax(r)}})}async forward(t){return this.forwardInput(await D(t))}async predictAgeAndGender(t){let e=await D(t),r=await this.forwardInput(e),n=ft.unstack(r.age),s=ft.unstack(r.gender),a=n.map((c,m)=>({ageTensor:c,genderTensor:s[m]})),i=await Promise.all(a.map(async({ageTensor:c,genderTensor:m})=>{let p=c.dataSync()[0],u=m.dataSync()[0],f=u>.5,l=f?"male":"female",b=f?u:1-u;return c.dispose(),m.dispose(),{age:p,gender:l,genderProbability:b}}));return r.age.dispose(),r.gender.dispose(),e.isBatchInput?i:i[0]}getDefaultModelName(){return"age_gender_model"}dispose(t=!0){this.faceFeatureExtractor.dispose(t),super.dispose(t)}loadClassifierParams(t){let{params:e,paramMappings:r}=this.extractClassifierParams(t);this._params=e,this._paramMappings=r}extractClassifierParams(t){return Wo(t)}extractParamsFromWeightMap(t){let{featureExtractorMap:e,classifierMap:r}=br(t);return this.faceFeatureExtractor.loadFromWeightMap(e),ko(r)}extractParams(t){let r=t.slice(0,t.length-1539),n=t.slice(t.length-1539);return this.faceFeatureExtractor.extractWeights(r),this.extractClassifierParams(n)}};var V=v(x());var we=class extends _e{postProcess(t,e,r){let n=r.map(({width:a,height:i})=>{let c=e/Math.max(i,a);return{width:a*c,height:i*c}}),s=n.length;return V.tidy(()=>{let a=(u,f)=>V.stack([V.fill([68],u,"float32"),V.fill([68],f,"float32")],1).as2D(1,136).as1D(),i=(u,f)=>{let{width:l,height:b}=n[u];return f(l,b)?Math.abs(l-b)/2:0},c=u=>i(u,(f,l)=>f<l),m=u=>i(u,(f,l)=>l<f);return t.mul(V.fill([s,136],e,"float32")).sub(V.stack(Array.from(Array(s),(u,f)=>a(c(f),m(f))))).div(V.stack(Array.from(Array(s),(u,f)=>a(n[f].width,n[f].height))))})}forwardInput(t){return V.tidy(()=>{let e=this.runNet(t);return this.postProcess(e,t.inputSize,t.inputDimensions.map(([r,n])=>({height:r,width:n})))})}async forward(t){return this.forwardInput(await D(t))}async detectLandmarks(t){let e=await D(t),r=V.tidy(()=>V.unstack(this.forwardInput(e))),n=await Promise.all(r.map(async(s,a)=>{let i=Array.from(s.dataSync()),c=i.filter((p,u)=>er(u)),m=i.filter((p,u)=>!er(u));return new Yt(Array(68).fill(0).map((p,u)=>new _(c[u],m[u])),{height:e.getInputHeight(a),width:e.getInputWidth(a)})}));return r.forEach(s=>s.dispose()),e.isBatchInput?n:n[0]}getClassifierChannelsOut(){return 136}};var Zt=class extends we{constructor(t=new xe){super("FaceLandmark68Net",t)}getDefaultModelName(){return"face_landmark_68_model"}getClassifierChannelsIn(){return 256}};var Fe=v(x());function Bo(o){let t=[],{extractDenseBlock3Params:e}=hr(o,t),r={dense0:e("dense0",!0),dense1:e("dense1"),dense2:e("dense2")};return W(o,t),{params:r,paramMappings:t}}function Ro(o){let t=[],{extractWeights:e,getRemainingWeights:r}=k(o),{extractDenseBlock3Params:n}=lr(e,t),s=n(3,32,"dense0",!0),a=n(32,64,"dense1"),i=n(64,128,"dense2");if(r().length!==0)throw new Error(`weights remaing after extract: ${r().length}`);return{paramMappings:t,params:{dense0:s,dense1:a,dense2:i}}}var Tr=class extends A{constructor(){super("TinyFaceFeatureExtractor")}forwardInput(t){let{params:e}=this;if(!e)throw new Error("TinyFaceFeatureExtractor - load model before inference");return Fe.tidy(()=>{let r=Fe.cast(t.toBatchTensor(112,!0),"float32"),s=rt(r,[122.782,117.001,104.298]).div(255),a=mr(s,e.dense0,!0);return a=mr(a,e.dense1),a=mr(a,e.dense2),a=Fe.avgPool(a,[14,14],[2,2],"valid"),a})}async forward(t){return this.forwardInput(await D(t))}getDefaultModelName(){return"face_feature_extractor_tiny_model"}extractParamsFromWeightMap(t){return Bo(t)}extractParams(t){return Ro(t)}};var ze=class extends we{constructor(t=new Tr){super("FaceLandmark68TinyNet",t)}getDefaultModelName(){return"face_landmark_68_tiny_model"}getClassifierChannelsIn(){return 128}};var po=class extends Zt{};var nt=v(x());var De=v(x());var Pr=v(x());function $o(o,t){return Pr.add(Pr.mul(o,t.weights),t.biases)}function uo(o,t,e,r,n="same"){let{filters:s,bias:a}=t.conv,i=De.conv2d(o,s,e,n);return i=De.add(i,a),i=$o(i,t.scale),r?De.relu(i):i}function Oo(o,t){return uo(o,t,[1,1],!0)}function fo(o,t){return uo(o,t,[1,1],!1)}function wr(o,t){return uo(o,t,[2,2],!0,"valid")}var G=v(x());function Kn(o,t){function e(i,c,m){let p=o(i),u=p.length/(c*m*m);if($r(u))throw new Error(`depth has to be an integer: ${u}, weights.length: ${p.length}, numFilters: ${c}, filterSize: ${m}`);return G.tidy(()=>G.transpose(G.tensor4d(p,[c,u,m,m]),[2,3,1,0]))}function r(i,c,m,p){let u=e(i,c,m),f=G.tensor1d(o(c));return t.push({paramPath:`${p}/filters`},{paramPath:`${p}/bias`}),{filters:u,bias:f}}function n(i,c){let m=G.tensor1d(o(i)),p=G.tensor1d(o(i));return t.push({paramPath:`${c}/weights`},{paramPath:`${c}/biases`}),{weights:m,biases:p}}function s(i,c,m,p){let u=r(i,c,m,`${p}/conv`),f=n(c,`${p}/scale`);return{conv:u,scale:f}}function a(i,c,m,p,u=!1){let f=s((u?.5:1)*i,c,m,`${p}/conv1`),l=s(i,c,m,`${p}/conv2`);return{conv1:f,conv2:l}}return{extractConvLayerParams:s,extractResidualLayerParams:a}}function Ho(o){let{extractWeights:t,getRemainingWeights:e}=k(o),r=[],{extractConvLayerParams:n,extractResidualLayerParams:s}=Kn(t,r),a=n(4704,32,7,"conv32_down"),i=s(9216,32,3,"conv32_1"),c=s(9216,32,3,"conv32_2"),m=s(9216,32,3,"conv32_3"),p=s(36864,64,3,"conv64_down",!0),u=s(36864,64,3,"conv64_1"),f=s(36864,64,3,"conv64_2"),l=s(36864,64,3,"conv64_3"),b=s(147456,128,3,"conv128_down",!0),T=s(147456,128,3,"conv128_1"),h=s(147456,128,3,"conv128_2"),g=s(589824,256,3,"conv256_down",!0),P=s(589824,256,3,"conv256_1"),y=s(589824,256,3,"conv256_2"),I=s(589824,256,3,"conv256_down_out"),j=G.tidy(()=>G.transpose(G.tensor2d(t(256*128),[128,256]),[1,0]));if(r.push({paramPath:"fc"}),e().length!==0)throw new Error(`weights remaing after extract: ${e().length}`);return{params:{conv32_down:a,conv32_1:i,conv32_2:c,conv32_3:m,conv64_down:p,conv64_1:u,conv64_2:f,conv64_3:l,conv128_down:b,conv128_1:T,conv128_2:h,conv256_down:g,conv256_1:P,conv256_2:y,conv256_down_out:I,fc:j},paramMappings:r}}function Qn(o,t){let e=Y(o,t);function r(a){let i=e(`${a}/scale/weights`,1),c=e(`${a}/scale/biases`,1);return{weights:i,biases:c}}function n(a){let i=e(`${a}/conv/filters`,4),c=e(`${a}/conv/bias`,1),m=r(a);return{conv:{filters:i,bias:c},scale:m}}function s(a){return{conv1:n(`${a}/conv1`),conv2:n(`${a}/conv2`)}}return{extractConvLayerParams:n,extractResidualLayerParams:s}}function zo(o){let t=[],{extractConvLayerParams:e,extractResidualLayerParams:r}=Qn(o,t),n=e("conv32_down"),s=r("conv32_1"),a=r("conv32_2"),i=r("conv32_3"),c=r("conv64_down"),m=r("conv64_1"),p=r("conv64_2"),u=r("conv64_3"),f=r("conv128_down"),l=r("conv128_1"),b=r("conv128_2"),T=r("conv256_down"),h=r("conv256_1"),g=r("conv256_2"),P=r("conv256_down_out"),{fc:y}=o;if(t.push({originalPath:"fc",paramPath:"fc"}),!Rr(y))throw new Error(`expected weightMap[fc] to be a Tensor2D, instead have ${y}`);let I={conv32_down:n,conv32_1:s,conv32_2:a,conv32_3:i,conv64_down:c,conv64_1:m,conv64_2:p,conv64_3:u,conv128_down:f,conv128_1:l,conv128_2:b,conv256_down:T,conv256_1:h,conv256_2:g,conv256_down_out:P,fc:y};return W(o,t),{params:I,paramMappings:t}}var B=v(x());function ot(o,t){let e=Oo(o,t.conv1);return e=fo(e,t.conv2),e=B.add(e,o),e=B.relu(e),e}function Ye(o,t){let e=wr(o,t.conv1);e=fo(e,t.conv2);let r=B.avgPool(o,2,2,"valid"),n=B.zeros(r.shape),s=r.shape[3]!==e.shape[3];if(r.shape[1]!==e.shape[1]||r.shape[2]!==e.shape[2]){let i=[...e.shape];i[1]=1;let c=B.zeros(i);e=B.concat([e,c],1);let m=[...e.shape];m[2]=1;let p=B.zeros(m);e=B.concat([e,p],2)}return r=s?B.concat([r,n],3):r,e=B.add(r,e),e=B.relu(e),e}var Kt=class extends A{constructor(){super("FaceRecognitionNet")}forwardInput(t){let{params:e}=this;if(!e)throw new Error("FaceRecognitionNet - load model before inference");return nt.tidy(()=>{let r=nt.cast(t.toBatchTensor(150,!0),"float32"),s=rt(r,[122.782,117.001,104.298]).div(255),a=wr(s,e.conv32_down);a=nt.maxPool(a,3,2,"valid"),a=ot(a,e.conv32_1),a=ot(a,e.conv32_2),a=ot(a,e.conv32_3),a=Ye(a,e.conv64_down),a=ot(a,e.conv64_1),a=ot(a,e.conv64_2),a=ot(a,e.conv64_3),a=Ye(a,e.conv128_down),a=ot(a,e.conv128_1),a=ot(a,e.conv128_2),a=Ye(a,e.conv256_down),a=ot(a,e.conv256_1),a=ot(a,e.conv256_2),a=Ye(a,e.conv256_down_out);let i=a.mean([1,2]);return nt.matMul(i,e.fc)})}async forward(t){return this.forwardInput(await D(t))}async computeFaceDescriptor(t){var s;if((s=t==null?void 0:t.shape)!=null&&s.some(a=>a<=0))return new Float32Array(128);let e=await D(t),r=nt.tidy(()=>nt.unstack(this.forwardInput(e))),n=await Promise.all(r.map(a=>a.data()));return r.forEach(a=>a.dispose()),e.isBatchInput?n:n[0]}getDefaultModelName(){return"face_recognition_model"}extractParamsFromWeightMap(t){return zo(t)}extractParams(t){return Ho(t)}};function ta(o){let t=new Kt;return t.extractWeights(o),t}function Fr(o,t){return{...o,...{descriptor:t}}}function ea(o){return typeof o.age=="number"}function Dr(o,t){return{...o,...{age:t}}}function ra(o){return(o.gender==="male"||o.gender==="female")&&ce(o.genderProbability)}function Er(o,t,e){return{...o,...{gender:t,genderProbability:e}}}var Nt=v(x());var at=v(x());function oa(o,t){function e(c,m){let p=at.tensor4d(o(9*c),[3,3,c,1]),u=at.tensor1d(o(c)),f=at.tensor1d(o(c)),l=at.tensor1d(o(c)),b=at.tensor1d(o(c));return t.push({paramPath:`${m}/filters`},{paramPath:`${m}/batch_norm_scale`},{paramPath:`${m}/batch_norm_offset`},{paramPath:`${m}/batch_norm_mean`},{paramPath:`${m}/batch_norm_variance`}),{filters:p,batch_norm_scale:u,batch_norm_offset:f,batch_norm_mean:l,batch_norm_variance:b}}function r(c,m,p,u,f){let l=at.tensor4d(o(c*m*p*p),[p,p,c,m]),b=at.tensor1d(o(m));return t.push({paramPath:`${u}/filters`},{paramPath:`${u}/${f?"batch_norm_offset":"bias"}`}),{filters:l,bias:b}}function n(c,m,p,u){let{filters:f,bias:l}=r(c,m,p,u,!0);return{filters:f,batch_norm_offset:l}}function s(c,m,p){let u=e(c,`${p}/depthwise_conv`),f=n(c,m,1,`${p}/pointwise_conv`);return{depthwise_conv:u,pointwise_conv:f}}function a(){let c=n(3,32,3,"mobilenetv1/conv_0"),m=s(32,64,"mobilenetv1/conv_1"),p=s(64,128,"mobilenetv1/conv_2"),u=s(128,128,"mobilenetv1/conv_3"),f=s(128,256,"mobilenetv1/conv_4"),l=s(256,256,"mobilenetv1/conv_5"),b=s(256,512,"mobilenetv1/conv_6"),T=s(512,512,"mobilenetv1/conv_7"),h=s(512,512,"mobilenetv1/conv_8"),g=s(512,512,"mobilenetv1/conv_9"),P=s(512,512,"mobilenetv1/conv_10"),y=s(512,512,"mobilenetv1/conv_11"),I=s(512,1024,"mobilenetv1/conv_12"),j=s(1024,1024,"mobilenetv1/conv_13");return{conv_0:c,conv_1:m,conv_2:p,conv_3:u,conv_4:f,conv_5:l,conv_6:b,conv_7:T,conv_8:h,conv_9:g,conv_10:P,conv_11:y,conv_12:I,conv_13:j}}function i(){let c=n(1024,256,1,"prediction_layer/conv_0"),m=n(256,512,3,"prediction_layer/conv_1"),p=n(512,128,1,"prediction_layer/conv_2"),u=n(128,256,3,"prediction_layer/conv_3"),f=n(256,128,1,"prediction_layer/conv_4"),l=n(128,256,3,"prediction_layer/conv_5"),b=n(256,64,1,"prediction_layer/conv_6"),T=n(64,128,3,"prediction_layer/conv_7"),h=r(512,12,1,"prediction_layer/box_predictor_0/box_encoding_predictor"),g=r(512,9,1,"prediction_layer/box_predictor_0/class_predictor"),P=r(1024,24,1,"prediction_layer/box_predictor_1/box_encoding_predictor"),y=r(1024,18,1,"prediction_layer/box_predictor_1/class_predictor"),I=r(512,24,1,"prediction_layer/box_predictor_2/box_encoding_predictor"),j=r(512,18,1,"prediction_layer/box_predictor_2/class_predictor"),tt=r(256,24,1,"prediction_layer/box_predictor_3/box_encoding_predictor"),it=r(256,18,1,"prediction_layer/box_predictor_3/class_predictor"),q=r(256,24,1,"prediction_layer/box_predictor_4/box_encoding_predictor"),Pt=r(256,18,1,"prediction_layer/box_predictor_4/class_predictor"),wt=r(128,24,1,"prediction_layer/box_predictor_5/box_encoding_predictor"),Ft=r(128,18,1,"prediction_layer/box_predictor_5/class_predictor");return{conv_0:c,conv_1:m,conv_2:p,conv_3:u,conv_4:f,conv_5:l,conv_6:b,conv_7:T,box_predictor_0:{box_encoding_predictor:h,class_predictor:g},box_predictor_1:{box_encoding_predictor:P,class_predictor:y},box_predictor_2:{box_encoding_predictor:I,class_predictor:j},box_predictor_3:{box_encoding_predictor:tt,class_predictor:it},box_predictor_4:{box_encoding_predictor:q,class_predictor:Pt},box_predictor_5:{box_encoding_predictor:wt,class_predictor:Ft}}}return{extractMobilenetV1Params:a,extractPredictionLayerParams:i}}function Yo(o){let t=[],{extractWeights:e,getRemainingWeights:r}=k(o),{extractMobilenetV1Params:n,extractPredictionLayerParams:s}=oa(e,t),a=n(),i=s(),m={extra_dim:at.tensor3d(e(5118*4),[1,5118,4])};if(t.push({paramPath:"output_layer/extra_dim"}),r().length!==0)throw new Error(`weights remaing after extract: ${r().length}`);return{params:{mobilenetv1:a,prediction_layer:i,output_layer:m},paramMappings:t}}function na(o,t){let e=Y(o,t);function r(m,p,u){let f=e(`${m}/Conv2d_${p}_pointwise/weights`,4,`${u}/filters`),l=e(`${m}/Conv2d_${p}_pointwise/convolution_bn_offset`,1,`${u}/batch_norm_offset`);return{filters:f,batch_norm_offset:l}}function n(m){let p=`mobilenetv1/conv_${m}`,u=`MobilenetV1/Conv2d_${m}_depthwise`,f=`${p}/depthwise_conv`,l=`${p}/pointwise_conv`,b=e(`${u}/depthwise_weights`,4,`${f}/filters`),T=e(`${u}/BatchNorm/gamma`,1,`${f}/batch_norm_scale`),h=e(`${u}/BatchNorm/beta`,1,`${f}/batch_norm_offset`),g=e(`${u}/BatchNorm/moving_mean`,1,`${f}/batch_norm_mean`),P=e(`${u}/BatchNorm/moving_variance`,1,`${f}/batch_norm_variance`);return{depthwise_conv:{filters:b,batch_norm_scale:T,batch_norm_offset:h,batch_norm_mean:g,batch_norm_variance:P},pointwise_conv:r("MobilenetV1",m,l)}}function s(){return{conv_0:r("MobilenetV1",0,"mobilenetv1/conv_0"),conv_1:n(1),conv_2:n(2),conv_3:n(3),conv_4:n(4),conv_5:n(5),conv_6:n(6),conv_7:n(7),conv_8:n(8),conv_9:n(9),conv_10:n(10),conv_11:n(11),conv_12:n(12),conv_13:n(13)}}function a(m,p){let u=e(`${m}/weights`,4,`${p}/filters`),f=e(`${m}/biases`,1,`${p}/bias`);return{filters:u,bias:f}}function i(m){let p=a(`Prediction/BoxPredictor_${m}/BoxEncodingPredictor`,`prediction_layer/box_predictor_${m}/box_encoding_predictor`),u=a(`Prediction/BoxPredictor_${m}/ClassPredictor`,`prediction_layer/box_predictor_${m}/class_predictor`);return{box_encoding_predictor:p,class_predictor:u}}function c(){return{conv_0:r("Prediction",0,"prediction_layer/conv_0"),conv_1:r("Prediction",1,"prediction_layer/conv_1"),conv_2:r("Prediction",2,"prediction_layer/conv_2"),conv_3:r("Prediction",3,"prediction_layer/conv_3"),conv_4:r("Prediction",4,"prediction_layer/conv_4"),conv_5:r("Prediction",5,"prediction_layer/conv_5"),conv_6:r("Prediction",6,"prediction_layer/conv_6"),conv_7:r("Prediction",7,"prediction_layer/conv_7"),box_predictor_0:i(0),box_predictor_1:i(1),box_predictor_2:i(2),box_predictor_3:i(3),box_predictor_4:i(4),box_predictor_5:i(5)}}return{extractMobilenetV1Params:s,extractPredictionLayerParams:c}}function Vo(o){let t=[],{extractMobilenetV1Params:e,extractPredictionLayerParams:r}=na(o,t),n=o["Output/extra_dim"];if(t.push({originalPath:"Output/extra_dim",paramPath:"output_layer/extra_dim"}),!dt(n))throw new Error(`expected weightMap['Output/extra_dim'] to be a Tensor3D, instead have ${n}`);let s={mobilenetv1:e(),prediction_layer:r(),output_layer:{extra_dim:n}};return W(o,t),{params:s,paramMappings:t}}var xt=v(x());var Ct=v(x());function Z(o,t,e){return Ct.tidy(()=>{let r=Ct.conv2d(o,t.filters,e,"same");return r=Ct.add(r,t.batch_norm_offset),Ct.clipByValue(r,0,6)})}var aa=.0010000000474974513;function sa(o,t,e){return xt.tidy(()=>{let r=xt.depthwiseConv2d(o,t.filters,e,"same");return r=xt.batchNorm(r,t.batch_norm_mean,t.batch_norm_variance,t.batch_norm_offset,t.batch_norm_scale,aa),xt.clipByValue(r,0,6)})}function ia(o){return[2,4,6,12].some(t=>t===o)?[2,2]:[1,1]}function Go(o,t){return xt.tidy(()=>{let e,r=Z(o,t.conv_0,[2,2]);if([t.conv_1,t.conv_2,t.conv_3,t.conv_4,t.conv_5,t.conv_6,t.conv_7,t.conv_8,t.conv_9,t.conv_10,t.conv_11,t.conv_12,t.conv_13].forEach((s,a)=>{let i=a+1,c=ia(i);r=sa(r,s.depthwise_conv,c),r=Z(r,s.pointwise_conv,[1,1]),i===11&&(e=r)}),e===null)throw new Error("mobileNetV1 - output of conv layer 11 is null");return{out:r,conv11:e}})}function ca(o,t,e){let r=o.arraySync(),n=Math.min(r[t][0],r[t][2]),s=Math.min(r[t][1],r[t][3]),a=Math.max(r[t][0],r[t][2]),i=Math.max(r[t][1],r[t][3]),c=Math.min(r[e][0],r[e][2]),m=Math.min(r[e][1],r[e][3]),p=Math.max(r[e][0],r[e][2]),u=Math.max(r[e][1],r[e][3]),f=(a-n)*(i-s),l=(p-c)*(u-m);if(f<=0||l<=0)return 0;let b=Math.max(n,c),T=Math.max(s,m),h=Math.min(a,p),g=Math.min(i,u),P=Math.max(h-b,0)*Math.max(g-T,0);return P/(f+l-P)}function jo(o,t,e,r,n){let s=o.shape[0],a=Math.min(e,s),i=t.map((p,u)=>({score:p,boxIndex:u})).filter(p=>p.score>n).sort((p,u)=>u.score-p.score),c=p=>p<=r?1:0,m=[];return i.forEach(p=>{if(m.length>=a)return;let u=p.score;for(let f=m.length-1;f>=0;--f){let l=ca(o,p.boxIndex,m[f]);if(l!==0&&(p.score*=c(l),p.score<=n))break}u===p.score&&m.push(p.boxIndex)}),m}var d=v(x());function ma(o){let t=d.unstack(d.transpose(o,[1,0])),e=[d.sub(t[2],t[0]),d.sub(t[3],t[1])],r=[d.add(t[0],d.div(e[0],2)),d.add(t[1],d.div(e[1],2))];return{sizes:e,centers:r}}function pa(o,t){let{sizes:e,centers:r}=ma(o),n=d.unstack(d.transpose(t,[1,0])),s=d.div(d.mul(d.exp(d.div(n[2],5)),e[0]),2),a=d.add(d.mul(d.div(n[0],10),e[0]),r[0]),i=d.div(d.mul(d.exp(d.div(n[3],5)),e[1]),2),c=d.add(d.mul(d.div(n[1],10),e[1]),r[1]);return d.transpose(d.stack([d.sub(a,s),d.sub(c,i),d.add(a,s),d.add(c,i)]),[1,0])}function Uo(o,t,e){return d.tidy(()=>{let r=o.shape[0],n=pa(d.reshape(d.tile(e.extra_dim,[r,1,1]),[-1,4]),d.reshape(o,[-1,4]));n=d.reshape(n,[r,n.shape[0]/r,4]);let s=d.sigmoid(d.slice(t,[0,0,1],[-1,-1,-1])),a=d.slice(s,[0,0,0],[-1,-1,1]);a=d.reshape(a,[r,a.shape[1]]);let i=d.unstack(n),c=d.unstack(a);return{boxes:i,scores:c}})}var Ge=v(x());var Ve=v(x());function Qt(o,t){return Ve.tidy(()=>{let e=o.shape[0],r=Ve.reshape(Jt(o,t.box_encoding_predictor),[e,-1,1,4]),n=Ve.reshape(Jt(o,t.class_predictor),[e,-1,3]);return{boxPredictionEncoding:r,classPrediction:n}})}function Xo(o,t,e){return Ge.tidy(()=>{let r=Z(o,e.conv_0,[1,1]),n=Z(r,e.conv_1,[2,2]),s=Z(n,e.conv_2,[1,1]),a=Z(s,e.conv_3,[2,2]),i=Z(a,e.conv_4,[1,1]),c=Z(i,e.conv_5,[2,2]),m=Z(c,e.conv_6,[1,1]),p=Z(m,e.conv_7,[2,2]),u=Qt(t,e.box_predictor_0),f=Qt(o,e.box_predictor_1),l=Qt(n,e.box_predictor_2),b=Qt(a,e.box_predictor_3),T=Qt(c,e.box_predictor_4),h=Qt(p,e.box_predictor_5),g=Ge.concat([u.boxPredictionEncoding,f.boxPredictionEncoding,l.boxPredictionEncoding,b.boxPredictionEncoding,T.boxPredictionEncoding,h.boxPredictionEncoding],1),P=Ge.concat([u.classPrediction,f.classPrediction,l.classPrediction,b.classPrediction,T.classPrediction,h.classPrediction],1);return{boxPredictions:g,classPredictions:P}})}var X=class{constructor({minConfidence:t,maxResults:e}={}){this._name="SsdMobilenetv1Options";if(this._minConfidence=t||.5,this._maxResults=e||100,typeof this._minConfidence!="number"||this._minConfidence<=0||this._minConfidence>=1)throw new Error(`${this._name} - expected minConfidence to be a number between 0 and 1`);if(typeof this._maxResults!="number")throw new Error(`${this._name} - expected maxResults to be a number`)}get minConfidence(){return this._minConfidence}get maxResults(){return this._maxResults}};var It=class extends A{constructor(){super("SsdMobilenetv1")}forwardInput(t){let{params:e}=this;if(!e)throw new Error("SsdMobilenetv1 - load model before inference");return Nt.tidy(()=>{let r=Nt.cast(t.toBatchTensor(512,!1),"float32"),n=Nt.sub(Nt.div(r,127.5),1),s=Go(n,e.mobilenetv1),{boxPredictions:a,classPredictions:i}=Xo(s.out,s.conv11,e.prediction_layer);return Uo(a,i,e.output_layer)})}async forward(t){return this.forwardInput(await D(t))}async locateFaces(t,e={}){let{maxResults:r,minConfidence:n}=new X(e),s=await D(t),{boxes:a,scores:i}=this.forwardInput(s),c=a[0],m=i[0];for(let y=1;y<a.length;y++)a[y].dispose(),i[y].dispose();let p=Array.from(m.dataSync()),f=jo(c,p,r,.5,n),l=s.getReshapedInputDimensions(0),b=s.inputSize,T=b/l.width,h=b/l.height,g=c.arraySync(),P=f.map(y=>{let[I,j]=[Math.max(0,g[y][0]),Math.min(1,g[y][2])].map(q=>q*h),[tt,it]=[Math.max(0,g[y][1]),Math.min(1,g[y][3])].map(q=>q*T);return new M(p[y],new zt(tt,I,it-tt,j-I),{height:s.getInputHeight(0),width:s.getInputWidth(0)})});return c.dispose(),m.dispose(),P}getDefaultModelName(){return"ssd_mobilenetv1_model"}extractParamsFromWeightMap(t){return Vo(t)}extractParams(t){return Yo(t)}};function Jo(o){let t=new It;return t.extractWeights(o),t}function ua(o){return Jo(o)}var lo=class extends It{};var qo=.4,Zo=[new _(.738768,.874946),new _(2.42204,2.65704),new _(4.30971,7.04493),new _(10.246,4.59428),new _(12.6868,11.8741)],Ko=[new _(1.603231,2.094468),new _(6.041143,7.080126),new _(2.882459,3.518061),new _(4.266906,5.178857),new _(9.041765,10.66308)],Qo=[117.001,114.697,97.404],tn="tiny_yolov2_model",en="tiny_yolov2_separable_conv_model";var C=v(x());var Mr=o=>typeof o=="number";function ho(o){if(!o)throw new Error(`invalid config: ${o}`);if(typeof o.withSeparableConvs!="boolean")throw new Error(`config.withSeparableConvs has to be a boolean, have: ${o.withSeparableConvs}`);if(!Mr(o.iouThreshold)||o.iouThreshold<0||o.iouThreshold>1)throw new Error(`config.iouThreshold has to be a number between [0, 1], have: ${o.iouThreshold}`);if(!Array.isArray(o.classes)||!o.classes.length||!o.classes.every(t=>typeof t=="string"))throw new Error(`config.classes has to be an array class names: string[], have: ${JSON.stringify(o.classes)}`);if(!Array.isArray(o.anchors)||!o.anchors.length||!o.anchors.map(t=>t||{}).every(t=>Mr(t.x)&&Mr(t.y)))throw new Error(`config.anchors has to be an array of { x: number, y: number }, have: ${JSON.stringify(o.anchors)}`);if(o.meanRgb&&(!Array.isArray(o.meanRgb)||o.meanRgb.length!==3||!o.meanRgb.every(Mr)))throw new Error(`config.meanRgb has to be an array of shape [number, number, number], have: ${JSON.stringify(o.meanRgb)}`)}var Q=v(x());var K=v(x());function Ee(o){return K.tidy(()=>{let t=K.mul(o,K.scalar(.10000000149011612));return K.add(K.relu(K.sub(o,t)),t)})}function vt(o,t){return Q.tidy(()=>{let e=Q.pad(o,[[0,0],[1,1],[1,1],[0,0]]);return e=Q.conv2d(e,t.conv.filters,[1,1],"valid"),e=Q.sub(e,t.bn.sub),e=Q.mul(e,t.bn.truediv),e=Q.add(e,t.conv.bias),Ee(e)})}var Lt=v(x());function yt(o,t){return Lt.tidy(()=>{let e=Lt.pad(o,[[0,0],[1,1],[1,1],[0,0]]);return e=Lt.separableConv2d(e,t.depthwise_filter,t.pointwise_filter,[1,1],"valid"),e=Lt.add(e,t.bias),Ee(e)})}var bo=v(x());function fa(o,t){let e=he(o,t);function r(a,i){let c=bo.tensor1d(o(a)),m=bo.tensor1d(o(a));return t.push({paramPath:`${i}/sub`},{paramPath:`${i}/truediv`}),{sub:c,truediv:m}}function n(a,i,c){let m=e(a,i,3,`${c}/conv`),p=r(i,`${c}/bn`);return{conv:m,bn:p}}let s=be(o,t);return{extractConvParams:e,extractConvWithBatchNormParams:n,extractSeparableConvParams:s}}function rn(o,t,e,r){let{extractWeights:n,getRemainingWeights:s}=k(o),a=[],{extractConvParams:i,extractConvWithBatchNormParams:c,extractSeparableConvParams:m}=fa(n,a),p;if(t.withSeparableConvs){let[u,f,l,b,T,h,g,P,y]=r,I=t.isFirstLayerConv2d?i(u,f,3,"conv0"):m(u,f,"conv0"),j=m(f,l,"conv1"),tt=m(l,b,"conv2"),it=m(b,T,"conv3"),q=m(T,h,"conv4"),Pt=m(h,g,"conv5"),wt=P?m(g,P,"conv6"):void 0,Ft=y?m(P,y,"conv7"):void 0,ie=i(y||P||g,5*e,1,"conv8");p={conv0:I,conv1:j,conv2:tt,conv3:it,conv4:q,conv5:Pt,conv6:wt,conv7:Ft,conv8:ie}}else{let[u,f,l,b,T,h,g,P,y]=r,I=c(u,f,"conv0"),j=c(f,l,"conv1"),tt=c(l,b,"conv2"),it=c(b,T,"conv3"),q=c(T,h,"conv4"),Pt=c(h,g,"conv5"),wt=c(g,P,"conv6"),Ft=c(P,y,"conv7"),ie=i(y,5*e,1,"conv8");p={conv0:I,conv1:j,conv2:tt,conv3:it,conv4:q,conv5:Pt,conv6:wt,conv7:Ft,conv8:ie}}if(s().length!==0)throw new Error(`weights remaing after extract: ${s().length}`);return{params:p,paramMappings:a}}function la(o,t){let e=Y(o,t);function r(i){let c=e(`${i}/sub`,1),m=e(`${i}/truediv`,1);return{sub:c,truediv:m}}function n(i){let c=e(`${i}/filters`,4),m=e(`${i}/bias`,1);return{filters:c,bias:m}}function s(i){let c=n(`${i}/conv`),m=r(`${i}/bn`);return{conv:c,bn:m}}let a=ge(e);return{extractConvParams:n,extractConvWithBatchNormParams:s,extractSeparableConvParams:a}}function on(o,t){let e=[],{extractConvParams:r,extractConvWithBatchNormParams:n,extractSeparableConvParams:s}=la(o,e),a;if(t.withSeparableConvs){let i=t.filterSizes&&t.filterSizes.length||9;a={conv0:t.isFirstLayerConv2d?r("conv0"):s("conv0"),conv1:s("conv1"),conv2:s("conv2"),conv3:s("conv3"),conv4:s("conv4"),conv5:s("conv5"),conv6:i>7?s("conv6"):void 0,conv7:i>8?s("conv7"):void 0,conv8:r("conv8")}}else a={conv0:n("conv0"),conv1:n("conv1"),conv2:n("conv2"),conv3:n("conv3"),conv4:n("conv4"),conv5:n("conv5"),conv6:n("conv6"),conv7:n("conv7"),conv8:r("conv8")};return W(o,e),{params:a,paramMappings:e}}var st=class{constructor({inputSize:t,scoreThreshold:e}={}){this._name="TinyYolov2Options";if(this._inputSize=t||416,this._scoreThreshold=e||.5,typeof this._inputSize!="number"||this._inputSize%32!==0)throw new Error(`${this._name} - expected inputSize to be a number divisible by 32`);if(typeof this._scoreThreshold!="number"||this._scoreThreshold<=0||this._scoreThreshold>=1)throw new Error(`${this._name} - expected scoreThreshold to be a number between 0 and 1`)}get inputSize(){return this._inputSize}get scoreThreshold(){return this._scoreThreshold}};var Cr=class Cr extends A{constructor(t){super("TinyYolov2"),ho(t),this._config=t}get config(){return this._config}get withClassScores(){return this.config.withClassScores||this.config.classes.length>1}get boxEncodingSize(){return 5+(this.withClassScores?this.config.classes.length:0)}runTinyYolov2(t,e){let r=vt(t,e.conv0);return r=C.maxPool(r,[2,2],[2,2],"same"),r=vt(r,e.conv1),r=C.maxPool(r,[2,2],[2,2],"same"),r=vt(r,e.conv2),r=C.maxPool(r,[2,2],[2,2],"same"),r=vt(r,e.conv3),r=C.maxPool(r,[2,2],[2,2],"same"),r=vt(r,e.conv4),r=C.maxPool(r,[2,2],[2,2],"same"),r=vt(r,e.conv5),r=C.maxPool(r,[2,2],[1,1],"same"),r=vt(r,e.conv6),r=vt(r,e.conv7),Jt(r,e.conv8,"valid",!1)}runMobilenet(t,e){let r=this.config.isFirstLayerConv2d?Ee(Jt(t,e.conv0,"valid",!1)):yt(t,e.conv0);return r=C.maxPool(r,[2,2],[2,2],"same"),r=yt(r,e.conv1),r=C.maxPool(r,[2,2],[2,2],"same"),r=yt(r,e.conv2),r=C.maxPool(r,[2,2],[2,2],"same"),r=yt(r,e.conv3),r=C.maxPool(r,[2,2],[2,2],"same"),r=yt(r,e.conv4),r=C.maxPool(r,[2,2],[2,2],"same"),r=yt(r,e.conv5),r=C.maxPool(r,[2,2],[1,1],"same"),r=e.conv6?yt(r,e.conv6):r,r=e.conv7?yt(r,e.conv7):r,Jt(r,e.conv8,"valid",!1)}forwardInput(t,e){let{params:r}=this;if(!r)throw new Error("TinyYolov2 - load model before inference");return C.tidy(()=>{let n=C.cast(t.toBatchTensor(e,!1),"float32");return n=this.config.meanRgb?rt(n,this.config.meanRgb):n,n=n.div(255),this.config.withSeparableConvs?this.runMobilenet(n,r):this.runTinyYolov2(n,r)})}async forward(t,e){return this.forwardInput(await D(t),e)}async detect(t,e={}){let{inputSize:r,scoreThreshold:n}=new st(e),s=await D(t),a=await this.forwardInput(s,r),i=C.tidy(()=>C.unstack(a)[0].expandDims()),c={width:s.getInputWidth(0),height:s.getInputHeight(0)},m=await this.extractBoxes(i,s.getReshapedInputDimensions(0),n);a.dispose(),i.dispose();let p=m.map(h=>h.box),u=m.map(h=>h.score),f=m.map(h=>h.classScore),l=m.map(h=>this.config.classes[h.label]);return Vr(p.map(h=>h.rescale(r)),u,this.config.iouThreshold,!0).map(h=>new Ht(u[h],f[h],l[h],p[h],c))}getDefaultModelName(){return""}extractParamsFromWeightMap(t){return on(t,this.config)}extractParams(t){let e=this.config.filterSizes||Cr.DEFAULT_FILTER_SIZES,r=e?e.length:void 0;if(r!==7&&r!==8&&r!==9)throw new Error(`TinyYolov2 - expected 7 | 8 | 9 convolutional filters, but found ${r} filterSizes in config`);return rn(t,this.config,this.boxEncodingSize,e)}async extractBoxes(t,e,r){let{width:n,height:s}=e,a=Math.max(n,s),i=a/n,c=a/s,m=t.shape[1],p=this.config.anchors.length,[u,f,l]=C.tidy(()=>{let g=t.reshape([m,m,p,this.boxEncodingSize]),P=g.slice([0,0,0,0],[m,m,p,4]),y=g.slice([0,0,0,4],[m,m,p,1]),I=this.withClassScores?C.softmax(g.slice([0,0,0,5],[m,m,p,this.config.classes.length]),3):C.scalar(0);return[P,y,I]}),b=[],T=await f.array(),h=await u.array();for(let g=0;g<m;g++)for(let P=0;P<m;P++)for(let y=0;y<p;y++){let I=Ne(T[g][P][y][0]);if(!r||I>r){let j=(P+Ne(h[g][P][y][0]))/m*i,tt=(g+Ne(h[g][P][y][1]))/m*c,it=Math.exp(h[g][P][y][2])*this.config.anchors[y].x/m*i,q=Math.exp(h[g][P][y][3])*this.config.anchors[y].y/m*c,Pt=j-it/2,wt=tt-q/2,Ft={row:g,col:P,anchor:y},{classScore:ie,label:yo}=this.withClassScores?await this.extractPredictedClass(l,Ft):{classScore:1,label:0};b.push({box:new Ot(Pt,wt,Pt+it,wt+q),score:I,classScore:I*ie,label:yo,...Ft})}}return u.dispose(),f.dispose(),l.dispose(),b}async extractPredictedClass(t,e){let{row:r,col:n,anchor:s}=e,a=await t.array();return Array(this.config.classes.length).fill(0).map((i,c)=>a[r][n][s][c]).map((i,c)=>({classScore:i,label:c})).reduce((i,c)=>i.classScore>c.classScore?i:c)}};Cr.DEFAULT_FILTER_SIZES=[3,16,32,64,128,256,512,1024,1024];var Me=Cr;var te=class extends Me{constructor(t=!0){let e={withSeparableConvs:t,iouThreshold:qo,classes:["face"],...t?{anchors:Ko,meanRgb:Qo}:{anchors:Zo,withClassScores:!0}};super(e)}get withSeparableConvs(){return this.config.withSeparableConvs}get anchors(){return this.config.anchors}async locateFaces(t,e){return(await this.detect(t,e)).map(n=>new M(n.score,n.relativeBox,{width:n.imageWidth,height:n.imageHeight}))}getDefaultModelName(){return this.withSeparableConvs?en:tn}extractParamsFromWeightMap(t){return super.extractParamsFromWeightMap(t)}};function da(o,t=!0){let e=new te(t);return e.extractWeights(o),e}var je=class extends st{constructor(){super(...arguments);this._name="TinyFaceDetectorOptions"}};var J=class{async then(t){return t(await this.run())}async run(){throw new Error("ComposableTask - run is not implemented")}};var Xe=v(x());var go=v(x());async function ee(o,t,e,r,n=({alignedRect:s})=>s){let s=o.map(c=>qt(c)?n(c):c.detection),a=r||(t instanceof go.Tensor?await le(t,s):await fe(t,s)),i=await e(a);return a.forEach(c=>c instanceof go.Tensor&&c.dispose()),i}async function Ce(o,t,e,r,n){return ee([o],t,async s=>e(s[0]),r,n)}var nn=.4,an=[new _(1.603231,2.094468),new _(6.041143,7.080126),new _(2.882459,3.518061),new _(4.266906,5.178857),new _(9.041765,10.66308)],sn=[117.001,114.697,97.404];var re=class extends Me{constructor(){let t={withSeparableConvs:!0,iouThreshold:nn,classes:["face"],anchors:an,meanRgb:sn,isFirstLayerConv2d:!0,filterSizes:[3,16,32,64,128,256,512]};super(t)}get anchors(){return this.config.anchors}async locateFaces(t,e){return(await this.detect(t,e)).map(n=>new M(n.score,n.relativeBox,{width:n.imageWidth,height:n.imageHeight}))}getDefaultModelName(){return"tiny_face_detector_model"}extractParamsFromWeightMap(t){return super.extractParamsFromWeightMap(t)}};var F={ssdMobilenetv1:new It,tinyFaceDetector:new re,tinyYolov2:new te,faceLandmark68Net:new Zt,faceLandmark68TinyNet:new ze,faceRecognitionNet:new Kt,faceExpressionNet:new Oe,ageGenderNet:new He},cn=(o,t)=>F.ssdMobilenetv1.locateFaces(o,t),ha=(o,t)=>F.tinyFaceDetector.locateFaces(o,t),ba=(o,t)=>F.tinyYolov2.locateFaces(o,t),mn=o=>F.faceLandmark68Net.detectLandmarks(o),ga=o=>F.faceLandmark68TinyNet.detectLandmarks(o),xa=o=>F.faceRecognitionNet.computeFaceDescriptor(o),va=o=>F.faceExpressionNet.predictExpressions(o),ya=o=>F.ageGenderNet.predictAgeAndGender(o),pn=o=>F.ssdMobilenetv1.load(o),_a=o=>F.tinyFaceDetector.load(o),Ta=o=>F.tinyYolov2.load(o),Pa=o=>F.faceLandmark68Net.load(o),wa=o=>F.faceLandmark68TinyNet.load(o),Fa=o=>F.faceRecognitionNet.load(o),Da=o=>F.faceExpressionNet.load(o),Ea=o=>F.ageGenderNet.load(o),Ma=pn,Ca=cn,Ia=mn;var Ir=class extends J{constructor(e,r,n){super();this.parentTask=e;this.input=r;this.extractedFaces=n}},oe=class extends Ir{async run(){let t=await this.parentTask,e=await ee(t,this.input,async r=>Promise.all(r.map(n=>F.faceExpressionNet.predictExpressions(n))),this.extractedFaces);return t.map((r,n)=>gr(r,e[n]))}withAgeAndGender(){return new ae(this,this.input)}},ne=class extends Ir{async run(){let t=await this.parentTask;if(!t)return;let e=await Ce(t,this.input,r=>F.faceExpressionNet.predictExpressions(r),this.extractedFaces);return gr(t,e)}withAgeAndGender(){return new se(this,this.input)}},St=class extends oe{withAgeAndGender(){return new Wt(this,this.input)}withFaceDescriptors(){return new _t(this,this.input)}},At=class extends ne{withAgeAndGender(){return new kt(this,this.input)}withFaceDescriptor(){return new Tt(this,this.input)}};var Nr=class extends J{constructor(e,r,n){super();this.parentTask=e;this.input=r;this.extractedFaces=n}},ae=class extends Nr{async run(){let t=await this.parentTask,e=await ee(t,this.input,async r=>Promise.all(r.map(n=>F.ageGenderNet.predictAgeAndGender(n))),this.extractedFaces);return t.map((r,n)=>{let{age:s,gender:a,genderProbability:i}=e[n];return Dr(Er(r,a,i),s)})}withFaceExpressions(){return new oe(this,this.input)}},se=class extends Nr{async run(){let t=await this.parentTask;if(!t)return;let{age:e,gender:r,genderProbability:n}=await Ce(t,this.input,s=>F.ageGenderNet.predictAgeAndGender(s),this.extractedFaces);return Dr(Er(t,r,n),e)}withFaceExpressions(){return new ne(this,this.input)}},Wt=class extends ae{withFaceExpressions(){return new St(this,this.input)}withFaceDescriptors(){return new _t(this,this.input)}},kt=class extends se{withFaceExpressions(){return new At(this,this.input)}withFaceDescriptor(){return new Tt(this,this.input)}};var Ue=class extends J{constructor(e,r){super();this.parentTask=e;this.input=r}},_t=class extends Ue{async run(){let t=await this.parentTask;return(await ee(t,this.input,r=>Promise.all(r.map(n=>F.faceRecognitionNet.computeFaceDescriptor(n))),null,r=>r.landmarks.align(null,{useDlibAlignment:!0}))).map((r,n)=>Fr(t[n],r))}withFaceExpressions(){return new St(this,this.input)}withAgeAndGender(){return new Wt(this,this.input)}},Tt=class extends Ue{async run(){let t=await this.parentTask;if(!t)return;let e=await Ce(t,this.input,r=>F.faceRecognitionNet.computeFaceDescriptor(r),null,r=>r.landmarks.align(null,{useDlibAlignment:!0}));return Fr(t,e)}withFaceExpressions(){return new At(this,this.input)}withAgeAndGender(){return new kt(this,this.input)}};var Je=class extends J{constructor(e,r,n){super();this.parentTask=e;this.input=r;this.useTinyLandmarkNet=n}get landmarkNet(){return this.useTinyLandmarkNet?F.faceLandmark68TinyNet:F.faceLandmark68Net}},qe=class extends Je{async run(){let t=await this.parentTask,e=t.map(a=>a.detection),r=this.input instanceof Xe.Tensor?await le(this.input,e):await fe(this.input,e),n=await Promise.all(r.map(a=>this.landmarkNet.detectLandmarks(a)));return r.forEach(a=>a instanceof Xe.Tensor&&a.dispose()),t.filter((a,i)=>n[i]).map((a,i)=>Pe(a,n[i]))}withFaceExpressions(){return new St(this,this.input)}withAgeAndGender(){return new Wt(this,this.input)}withFaceDescriptors(){return new _t(this,this.input)}},Ze=class extends Je{async run(){let t=await this.parentTask;if(!t)return;let{detection:e}=t,r=this.input instanceof Xe.Tensor?await le(this.input,[e]):await fe(this.input,[e]),n=await this.landmarkNet.detectLandmarks(r[0]);return r.forEach(s=>s instanceof Xe.Tensor&&s.dispose()),Pe(t,n)}withFaceExpressions(){return new At(this,this.input)}withAgeAndGender(){return new kt(this,this.input)}withFaceDescriptor(){return new Tt(this,this.input)}};var Ke=class extends J{constructor(e,r=new X){super();this.input=e;this.options=r}},Ie=class extends Ke{async run(){let{input:t,options:e}=this,r;if(e instanceof je)r=F.tinyFaceDetector.locateFaces(t,e);else if(e instanceof X)r=F.ssdMobilenetv1.locateFaces(t,e);else if(e instanceof st)r=F.tinyYolov2.locateFaces(t,e);else throw new Error("detectFaces - expected options to be instance of TinyFaceDetectorOptions | SsdMobilenetv1Options | TinyYolov2Options");return r}runAndExtendWithFaceDetections(){return new Promise((t,e)=>{this.run().then(r=>t(r.map(n=>Vt({},n)))).catch(r=>e(r))})}withFaceLandmarks(t=!1){return new qe(this.runAndExtendWithFaceDetections(),this.input,t)}withFaceExpressions(){return new oe(this.runAndExtendWithFaceDetections(),this.input)}withAgeAndGender(){return new ae(this.runAndExtendWithFaceDetections(),this.input)}},Qe=class extends Ke{async run(){let t=await new Ie(this.input,this.options),e=t[0];return t.forEach(r=>{r.score>e.score&&(e=r)}),e}runAndExtendWithFaceDetection(){return new Promise(async t=>{let e=await this.run();t(e?Vt({},e):void 0)})}withFaceLandmarks(t=!1){return new Ze(this.runAndExtendWithFaceDetection(),this.input,t)}withFaceExpressions(){return new ne(this.runAndExtendWithFaceDetection(),this.input)}withAgeAndGender(){return new se(this.runAndExtendWithFaceDetection(),this.input)}};function Na(o,t=new X){return new Qe(o,t)}function Lr(o,t=new X){return new Ie(o,t)}async function un(o,t){return Lr(o,new X(t?{minConfidence:t}:{})).withFaceLandmarks().withFaceDescriptors()}async function La(o,t={}){return Lr(o,new st(t)).withFaceLandmarks().withFaceDescriptors()}var Sa=un;function xo(o,t){if(o.length!==t.length)throw new Error("euclideanDistance: arr1.length !== arr2.length");let e=Array.from(o),r=Array.from(t);return Math.sqrt(e.map((n,s)=>n-r[s]).reduce((n,s)=>n+s*s,0))}var vo=class o{constructor(t,e=.6){this._distanceThreshold=e;let r=Array.isArray(t)?t:[t];if(!r.length)throw new Error("FaceRecognizer.constructor - expected atleast one input");let n=1,s=()=>`person ${n++}`;this._labeledDescriptors=r.map(a=>{if(a instanceof Et)return a;if(a instanceof Float32Array)return new Et(s(),[a]);if(a.descriptor&&a.descriptor instanceof Float32Array)return new Et(s(),[a.descriptor]);throw new Error("FaceRecognizer.constructor - expected inputs to be of type LabeledFaceDescriptors | WithFaceDescriptor<any> | Float32Array | Array<LabeledFaceDescriptors | WithFaceDescriptor<any> | Float32Array>")})}get labeledDescriptors(){return this._labeledDescriptors}get distanceThreshold(){return this._distanceThreshold}computeMeanDistance(t,e){return e.map(r=>xo(r,t)).reduce((r,n)=>r+n,0)/(e.length||1)}matchDescriptor(t){return this.labeledDescriptors.map(({descriptors:e,label:r})=>new me(r,this.computeMeanDistance(t,e))).reduce((e,r)=>e.distance<r.distance?e:r)}findBestMatch(t){let e=this.matchDescriptor(t);return e.distance<this._distanceThreshold?e:new me("unknown",e.distance)}toJSON(){return{distanceThreshold:this._distanceThreshold,labeledDescriptors:this._labeledDescriptors.map(t=>t.toJSON())}}static fromJSON(t){let e=t.labeledDescriptors.map(r=>Et.fromJSON(r));return new o(e,t.distanceThreshold)}};function Aa(o){let t=new re;return t.extractWeights(o),t}function fn(o,t){let{width:e,height:r}=new R(t.width,t.height);if(e<=0||r<=0)throw new Error(`resizeResults - invalid dimensions: ${JSON.stringify({width:e,height:r})}`);if(Array.isArray(o))return o.map(n=>fn(n,{width:e,height:r}));if(qt(o)){let n=o.detection.forSize(e,r),s=o.unshiftedLandmarks.forSize(n.box.width,n.box.height);return Pe(Vt(o,n),s)}return pt(o)?Vt(o,o.detection.forSize(e,r)):o instanceof H||o instanceof M?o.forSize(e,r):o}var ka=No;0&&(module.exports={AgeGenderNet,BoundingBox,Box,ComposableTask,ComputeAllFaceDescriptorsTask,ComputeFaceDescriptorsTaskBase,ComputeSingleFaceDescriptorTask,DetectAllFaceLandmarksTask,DetectAllFacesTask,DetectFaceLandmarksTaskBase,DetectFacesTaskBase,DetectSingleFaceLandmarksTask,DetectSingleFaceTask,Dimensions,FACE_EXPRESSION_LABELS,FaceDetection,FaceDetectionNet,FaceExpressionNet,FaceExpressions,FaceLandmark68Net,FaceLandmark68TinyNet,FaceLandmarkNet,FaceLandmarks,FaceLandmarks5,FaceLandmarks68,FaceMatch,FaceMatcher,FaceRecognitionNet,Gender,LabeledBox,LabeledFaceDescriptors,NetInput,NeuralNetwork,ObjectDetection,Point,PredictedBox,Rect,SsdMobilenetv1,SsdMobilenetv1Options,TinyFaceDetector,TinyFaceDetectorOptions,TinyYolov2,TinyYolov2Options,allFaces,allFacesSsdMobilenetv1,allFacesTinyYolov2,awaitMediaLoaded,bufferToImage,computeFaceDescriptor,createCanvas,createCanvasFromMedia,createFaceDetectionNet,createFaceRecognitionNet,createSsdMobilenetv1,createTinyFaceDetector,createTinyYolov2,detectAllFaces,detectFaceLandmarks,detectFaceLandmarksTiny,detectLandmarks,detectSingleFace,draw,env,euclideanDistance,extendWithAge,extendWithFaceDescriptor,extendWithFaceDetection,extendWithFaceExpressions,extendWithFaceLandmarks,extendWithGender,extractFaceTensors,extractFaces,fetchImage,fetchJson,fetchNetWeights,fetchOrThrow,fetchVideo,getContext2dOrThrow,getMediaDimensions,imageTensorToCanvas,imageToSquare,inverseSigmoid,iou,isMediaElement,isMediaLoaded,isWithAge,isWithFaceDetection,isWithFaceExpressions,isWithFaceLandmarks,isWithGender,loadAgeGenderModel,loadFaceDetectionModel,loadFaceExpressionModel,loadFaceLandmarkModel,loadFaceLandmarkTinyModel,loadFaceRecognitionModel,loadSsdMobilenetv1Model,loadTinyFaceDetectorModel,loadTinyYolov2Model,loadWeightMap,locateFaces,matchDimensions,minBbox,nets,nonMaxSuppression,normalize,padToSquare,predictAgeAndGender,recognizeFaceExpressions,resizeResults,resolveInput,shuffleArray,sigmoid,ssdMobilenetv1,tf,tinyFaceDetector,tinyYolov2,toNetInput,utils,validateConfig,version});
|