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

8 lines
81 KiB
JavaScript

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