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