face-api/dist/face-api.esm-nobundle.js

10 lines
80 KiB
JavaScript

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