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