8 lines
81 KiB
JavaScript
8 lines
81 KiB
JavaScript
/*
|
|
Face-API
|
|
homepage: <https://github.com/vladmandic/face-api>
|
|
author: <https://github.com/vladmandic>'
|
|
*/
|
|
|
|
var lr=Object.defineProperty;var ho=Object.getOwnPropertyDescriptor;var bo=Object.getOwnPropertyNames;var go=Object.prototype.hasOwnProperty;var xo=(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 bo(t))!go.call(o,a)&&a!==e&&lr(o,a,{get:()=>t[a],enumerable:!(r=ho(t,a))||r.enumerable});return o},v=(o,t,e)=>(fr(o,t,"default"),e&&fr(e,t,"default"));var n={};Ve(n,{version:()=>Eo});v(n,fn);v(n,ln);v(n,dn);import*as fn from"@tensorflow/tfjs/dist/index.js";import*as ln from"@tensorflow/tfjs-backend-webgl/dist/index.js";import*as dn from"@tensorflow/tfjs-backend-wasm/dist/index.js";var vo="3.19.0",yo="3.19.0",_o="3.19.0",To="3.19.0",Po="3.19.0",wo="3.19.0",Fo="3.19.0",Do="3.19.0",Eo={tfjs:vo,"tfjs-core":yo,"tfjs-data":_o,"tfjs-layers":To,"tfjs-converter":Po,"tfjs-backend-cpu":wo,"tfjs-backend-webgl":Fo,"tfjs-backend-wasm":Do};var Ar={};Ve(Ar,{AnchorPosition:()=>Ke,DrawBox:()=>ee,DrawBoxOptions:()=>de,DrawFaceLandmarks:()=>De,DrawFaceLandmarksOptions:()=>Fe,DrawTextField:()=>et,DrawTextFieldOptions:()=>kt,drawContour:()=>Z,drawDetections:()=>Ao,drawFaceExpressions:()=>Wo,drawFaceLandmarks:()=>Bo});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 dr={};Ve(dr,{computeReshapedDimensions:()=>je,getCenterPoint:()=>yt,isDimensions:()=>ue,isEven:()=>pe,isFloat:()=>Ge,isTensor:()=>xt,isTensor1D:()=>Mo,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 Mo(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 b(0,0)).div(new b(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 b=class{constructor(t,e){this._x=t,this._y=e}get x(){return this._x}get y(){return this._y}add(t){return new b(this.x+t.x,this.y+t.y)}sub(t){return new b(this.x-t.x,this.y-t.y)}mul(t){return new b(this.x*t.x,this.y*t.y)}div(t){return new b(this.x/t.x,this.y/t.y)}abs(){return new b(Math.abs(this.x),Math.abs(this.y))}magnitude(){return Math.sqrt(this.x**2+this.y**2)}floor(){return new b(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(G)}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(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];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 b(this.left,this.top)}get topRight(){return new b(this.right,this.top)}get bottomLeft(){return new b(this.left,this.bottom)}get bottomRight(){return new b(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=ue(t)?t.width:t,r=ue(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,u=i-m,f=Math.min(p,t-c),l=Math.min(u,e-m);return new w({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 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,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 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 Nt=class extends w{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 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 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 hr(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 br(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 gr(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(hr(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 xr(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 Hn(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 Vn(o){return Math.log(o/(1-o))}var St=class extends w{constructor(t,e,r,a,s=!1){super({x:t,y:e,width:r,height:a},s)}};var Co=.5,Io=.43,No=.45,$=class{constructor(t,e,r=new b(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 b(a,s)).add(r))}get shift(){return new b(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 b(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 b(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 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=f=>a.sub(f).magnitude(),i=(s(e)+s(r))/2,c=Math.floor(i/No),m=yt(t),p=Math.floor(Math.max(0,m.x-Co*c)),u=Math.floor(Math.max(0,m.y-Io*c));return new St(p,u,Math.min(c,this.imageWidth+p),Math.min(c,this.imageHeight+u))}alignMinBbox(t){let e=br(this.positions);return e.pad(e.width*t,e.height*t)}getRefPointsForAlignment(){throw new Error("getRefPointsForAlignment not implemented by base class")}};var vr=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 w{constructor(e,r){super(e);this._label=r}static assertIsValidLabeledBox(e,r){if(w.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 yr=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=xo("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 So(){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 Lo(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 T={getEnv:So,setEnv:qe,initialize:Ze,createBrowserEnv:Ue,createFileSystem:le,createNodejsEnv:Xe,monkeyPatch:Lo,isBrowser:Je,isNodejs:te};Ze();function Wt(o){return!T.isNodejs()&&typeof o=="string"?document.getElementById(o):o}function k(o){let{Canvas:t,CanvasRenderingContext2D:e}=T.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 g=m+f.x,_=m+f.y+(d+1)*i;r.fillText(l,g,_)})}};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 w(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 Ao(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 w(r),i=a?`${vt(a)}`:void 0;new ee(s,{label:i}).draw(o)})}function he(o){let{Image:t,Video:e}=T.getEnv();return o instanceof t&&o.complete||o instanceof e&&o.readyState>=3}function _r(o){return new Promise((t,e)=>{(o instanceof T.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 Tr(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=T.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}=T.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}=T.getEnv(),r=e();return r.width=o,r.height=t,r}function be(o,t){let{ImageData:e}=T.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||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}=T.getEnv();return o instanceof t||o instanceof e||o instanceof r}function wr(o,t,e=!1){let{Image:r,Canvas:a}=T.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 T.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=xr(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 T.getEnv().Canvas)return n.browser.fromPixels(wr(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)&&_r(a))),new rt(r,Array.isArray(o))}async function re(o,t){let{Canvas:e}=T.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}=T.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 Mi(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 Tr(e)}async function Fr(o){return(await mt(o)).json()}async function Li(o){return new Float32Array(await(await mt(o)).arrayBuffer())}function Dr(o){return new Promise((t,e)=>{o instanceof Blob||e(new Error("bufferToVideo - expected buf to be of type: Blob"));let r=T.getEnv().createVideoElement();r.oncanplay=()=>t(r),r.onerror=e,r.playsInline=!0,r.muted=!0,r.src=URL.createObjectURL(o),r.play()})}async function $i(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 Dr(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 Er(o,t){let{manifestUri:e,modelBaseUri:r}=ge(o,t),a=await Fr(e);return n.io.loadWeights(a,r)}function ji(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 Er(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}=T.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 Mr(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 Cr(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 Cr(t)}extractParams(t){return Mr(t)}};function se(o,t){return n.tidy(()=>n.add(n.matMul(o,t.weights),t.bias))}function Ir(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 Nr(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 Pe(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 Ir(e,this.getClassifierChannelsIn(),this.getClassifierChannelsOut())}extractParamsFromWeightMap(e){let{featureExtractorMap:r,classifierMap:a}=Pe(e);return this.faceFeatureExtractor.loadFromWeightMap(r),Nr(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 Sr=["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}`);Sr.forEach((e,r)=>{this[e]=t[r]})}asSortedArray(){return Sr.map(t=>({expression:t,probability:this[t]})).sort((t,e)=>e.probability-t.probability)}};var we=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 Lr(o){return o.expressions instanceof pt}function tr(o,t){return{...o,...{expressions:t}}}function Wo(o,t,e=.1,r){(Array.isArray(t)?t:[t]).forEach(s=>{let i=s instanceof pt?s:Lr(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 b(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 ko(o){let t=(c,m,p,u)=>Math.atan2(u-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,1/0),i=a.reduce((c,m)=>c>m._y?c:m._y,-1/0);return r.yaw=Math.PI*(o._imgDims._height/(i-s)/1.4-1),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=ko(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 Bo(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 Wr="1.7.2";function Oo(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 kr(o,t){let e=[],{extractWeights:r,getRemainingWeights:a}=A(o),{extractConvParams:s,extractSeparableConvParams:i,extractReductionBlockParams:c,extractMainBlockParams:m}=Oo(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 g=c(128,256,"exit_flow/reduction_block"),_=i(256,512,"exit_flow/separable_conv"),F={reduction_block:g,separable_conv:_};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:F}}}function Ho(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 Br(o,t){let e=[],{extractConvParams:r,extractSeparableConvParams:a,extractReductionBlockParams:s,extractMainBlockParams:i}=Ho(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(_=>{f[`main_block_${_}`]=i(`middle_flow/main_block_${_}`)});let l=s("exit_flow/reduction_block"),d=a("exit_flow/separable_conv"),g={reduction_block:l,separable_conv:d};return L(o,e),{params:{entry_flow:u,middle_flow:f,exit_flow:g},paramMappings:e}}function Rr(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,Rr(o,t.expansion_conv,[2,2])),r}function zo(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(Rr(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=zo(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 Br(e,this._numMainBlocks)}extractParams(e){return kr(e,this._numMainBlocks)}};function $r(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 Or(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,g=d?"male":"female",_=d?l:1-l;return p.dispose(),u.dispose(),{age:f,gender:g,genderProbability:_}}));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 $r(e)}extractParamsFromWeightMap(e){let{featureExtractorMap:r,classifierMap:a}=Pe(e);return this.faceFeatureExtractor.loadFromWeightMap(r),Or(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:g}=a[f];return l(d,g)?Math.abs(d-g)/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 b(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 Hr(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 zr(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 Hr(t)}extractParams(t){return zr(t)}};var Ie=class extends Gt{constructor(t=new Ce){super("FaceLandmark68TinyNet",t)}getDefaultModelName(){return"face_landmark_68_tiny_model"}getClassifierChannelsIn(){return 128}};var Vr=class extends jt{};function Yr(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=Yr(c,t.scale),r?n.relu(c):c}function Gr(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 Vo(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 jr(o){let{extractWeights:t,getRemainingWeights:e}=A(o),r=[],{extractConvLayerParams:a,extractResidualLayerParams:s}=Vo(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"),g=s(147456,128,3,"conv128_down",!0),_=s(147456,128,3,"conv128_1"),F=s(147456,128,3,"conv128_2"),h=s(589824,256,3,"conv256_down",!0),y=s(589824,256,3,"conv256_1"),x=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:g,conv128_1:_,conv128_2:F,conv256_down:h,conv256_1:y,conv256_2:x,conv256_down_out:D,fc:N},paramMappings:r}}function Yo(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 Ur(o){let t=[],{extractConvLayerParams:e,extractResidualLayerParams:r}=Yo(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"),g=r("conv128_2"),_=r("conv256_down"),F=r("conv256_1"),h=r("conv256_2"),y=r("conv256_down_out"),{fc:x}=o;if(t.push({originalPath:"fc",paramPath:"fc"}),!Ye(x))throw new Error(`expected weightMap[fc] to be a Tensor2D, instead have ${x}`);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:g,conv256_down:_,conv256_1:F,conv256_2:h,conv256_down_out:y,fc:x};return L(o,t),{params:D,paramMappings:t}}function j(o,t){let e=Gr(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 Ur(t)}extractParams(t){return jr(t)}};function vf(o){let t=new Ut;return t.extractWeights(o),t}function ar(o,t){return{...o,...{descriptor:t}}}function Pf(o){return typeof o.age=="number"}function sr(o,t){return{...o,...{age:t}}}function Ef(o){return(o.gender==="male"||o.gender==="female")&&It(o.genderProbability)}function ir(o,t,e){return{...o,...{gender:t,genderProbability:e}}}function Go(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)),g=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:g}}function r(m,p,u,f,l){let d=n.tensor4d(o(m*p*u*u),[u,u,m,p]),g=n.tensor1d(o(p));return t.push({paramPath:`${f}/filters`},{paramPath:`${f}/${l?"batch_norm_offset":"bias"}`}),{filters:d,bias:g}}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"),g=s(256,512,"mobilenetv1/conv_6"),_=s(512,512,"mobilenetv1/conv_7"),F=s(512,512,"mobilenetv1/conv_8"),h=s(512,512,"mobilenetv1/conv_9"),y=s(512,512,"mobilenetv1/conv_10"),x=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:g,conv_7:_,conv_8:F,conv_9:h,conv_10:y,conv_11:x,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"),g=a(256,64,1,"prediction_layer/conv_6"),_=a(64,128,3,"prediction_layer/conv_7"),F=r(512,12,1,"prediction_layer/box_predictor_0/box_encoding_predictor"),h=r(512,9,1,"prediction_layer/box_predictor_0/class_predictor"),y=r(1024,24,1,"prediction_layer/box_predictor_1/box_encoding_predictor"),x=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:g,conv_7:_,box_predictor_0:{box_encoding_predictor:F,class_predictor:h},box_predictor_1:{box_encoding_predictor:y,class_predictor:x},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 Xr(o){let t=[],{extractWeights:e,getRemainingWeights:r}=A(o),{extractMobilenetV1Params:a,extractPredictionLayerParams:s}=Go(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 jo(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`,g=e(`${f}/depthwise_weights`,4,`${l}/filters`),_=e(`${f}/BatchNorm/gamma`,1,`${l}/batch_norm_scale`),F=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:g,batch_norm_scale:_,batch_norm_offset:F,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 Jr(o){let t=[],{extractMobilenetV1Params:e,extractPredictionLayerParams:r}=jo(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 Uo=.0010000000474974513;function Xo(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,Uo),n.clipByValue(r,0,6)})}function Jo(o){return[2,4,6,12].some(t=>t===o)?[2,2]:[1,1]}function qr(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=Xo(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 qo(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 g=Math.max(a,m),_=Math.max(s,p),F=Math.min(i,u),h=Math.min(c,f),y=Math.max(F-g,0)*Math.max(h-_,0);return y/(l+d-y)}function Zr(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=qo(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 Zo(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 Ko(o,t){let{sizes:e,centers:r}=Zo(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 Kr(o,t,e){return n.tidy(()=>{let r=o.shape[0],a=Ko(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 Qr(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),g=Tt(i,e.box_predictor_3),_=Tt(m,e.box_predictor_4),F=Tt(u,e.box_predictor_5),h=n.concat([f.boxPredictionEncoding,l.boxPredictionEncoding,d.boxPredictionEncoding,g.boxPredictionEncoding,_.boxPredictionEncoding,F.boxPredictionEncoding],1),y=n.concat([f.classPrediction,l.classPrediction,d.classPrediction,g.classPrediction,_.classPrediction,F.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 Pt=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=qr(a,e.mobilenetv1),{boxPredictions:i,classPredictions:c}=Qr(s.out,s.conv11,e.prediction_layer);return Kr(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 x=1;x<i.length;x++)i[x].dispose(),c[x].dispose();let u=Array.from(p.dataSync()),l=Zr(m,u,r,.5,a),d=s.getReshapedInputDimensions(0),g=s.inputSize,_=g/d.width,F=g/d.height,h=m.arraySync(),y=l.map(x=>{let[D,N]=[Math.max(0,h[x][0]),Math.min(1,h[x][2])].map(O=>O*F),[Y,q]=[Math.max(0,h[x][1]),Math.min(1,h[x][3])].map(O=>O*_);return new E(u[x],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 Jr(t)}extractParams(t){return Xr(t)}};function Qo(o){let t=new Pt;return t.extractWeights(o),t}function vl(o){return Qo(o)}var to=class extends Pt{};var eo=.4,ro=[new b(.738768,.874946),new b(2.42204,2.65704),new b(4.30971,7.04493),new b(10.246,4.59428),new b(12.6868,11.8741)],oo=[new b(1.603231,2.094468),new b(6.041143,7.080126),new b(2.882459,3.518061),new b(4.266906,5.178857),new b(9.041765,10.66308)],no=[117.001,114.697,97.404],ao="tiny_yolov2_model",so="tiny_yolov2_separable_conv_model";var Se=o=>typeof o=="number";function io(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 tn(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 co(o,t,e,r){let{extractWeights:a,getRemainingWeights:s}=A(o),i=[],{extractConvParams:c,extractConvWithBatchNormParams:m,extractSeparableConvParams:p}=tn(a,i),u;if(t.withSeparableConvs){let[f,l,d,g,_,F,h,y,x]=r,D=t.isFirstLayerConv2d?c(f,l,3,"conv0"):p(f,l,"conv0"),N=p(l,d,"conv1"),Y=p(d,g,"conv2"),q=p(g,_,"conv3"),O=p(_,F,"conv4"),at=p(F,h,"conv5"),st=y?p(h,y,"conv6"):void 0,it=x?p(y,x,"conv7"):void 0,gt=c(x||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,g,_,F,h,y,x]=r,D=m(f,l,"conv0"),N=m(l,d,"conv1"),Y=m(d,g,"conv2"),q=m(g,_,"conv3"),O=m(_,F,"conv4"),at=m(F,h,"conv5"),st=m(h,y,"conv6"),it=m(y,x,"conv7"),gt=c(x,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 en(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 mo(o,t){let e=[],{extractConvParams:r,extractConvWithBatchNormParams:a,extractSeparableConvParams:s}=en(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");io(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),g=u.map(h=>this.config.classes[h.label]);return gr(f.map(h=>h.rescale(a)),l,this.config.iouThreshold,!0).map(h=>new ct(l[h],d[h],g[h],f[h],p))}getDefaultModelName(){return""}extractParamsFromWeightMap(e){return mo(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 co(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,g]=n.tidy(()=>{let y=e.reshape([u,u,f,this.boxEncodingSize]),x=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[x,D,N]}),_=[],F=await d.array(),h=await l.array();for(let y=0;y<u;y++)for(let x=0;x<u;x++)for(let D=0;D<f;D++){let N=fe(F[y][x][D][0]);if(!a||N>a){let Y=(x+fe(h[y][x][D][0]))/u*m,q=(y+fe(h[y][x][D][1]))/u*p,O=Math.exp(h[y][x][D][2])*this.config.anchors[D].x/u*m,at=Math.exp(h[y][x][D][3])*this.config.anchors[D].y/u*p,st=Y-O/2,it=q-at/2,gt={row:y,col:x,anchor:D},{classScore:pr,label:ur}=this.withClassScores?await this.extractPredictedClass(g,gt):{classScore:1,label:0};_.push({box:new Nt(st,it,st+O,it+at),score:N,classScore:N*pr,label:ur,...gt})}}return l.dispose(),d.dispose(),g.dispose(),_}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)}},wt=cr;wt.DEFAULT_FILTER_SIZES=[3,16,32,64,128,256,512,1024,1024];var Jt=class extends wt{constructor(t=!0){let e={withSeparableConvs:t,iouThreshold:eo,classes:["face"],...t?{anchors:oo,meanRgb:no}:{anchors:ro,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?so:ao}extractParamsFromWeightMap(t){return super.extractParamsFromWeightMap(t)}};function pd(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 po=.4,uo=[new b(1.603231,2.094468),new b(6.041143,7.080126),new b(2.882459,3.518061),new b(4.266906,5.178857),new b(9.041765,10.66308)],fo=[117.001,114.697,97.404];var Zt=class extends wt{constructor(){let t={withSeparableConvs:!0,iouThreshold:po,classes:["face"],anchors:uo,meanRgb:fo,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 P={ssdMobilenetv1:new Pt,tinyFaceDetector:new Zt,tinyYolov2:new Jt,faceLandmark68Net:new jt,faceLandmark68TinyNet:new Ie,faceRecognitionNet:new Ut,faceExpressionNet:new we,ageGenderNet:new Me},rn=(o,t)=>P.ssdMobilenetv1.locateFaces(o,t),Od=(o,t)=>P.tinyFaceDetector.locateFaces(o,t),Hd=(o,t)=>P.tinyYolov2.locateFaces(o,t),on=o=>P.faceLandmark68Net.detectLandmarks(o),zd=o=>P.faceLandmark68TinyNet.detectLandmarks(o),Vd=o=>P.faceRecognitionNet.computeFaceDescriptor(o),Yd=o=>P.faceExpressionNet.predictExpressions(o),Gd=o=>P.ageGenderNet.predictAgeAndGender(o),nn=o=>P.ssdMobilenetv1.load(o),jd=o=>P.tinyFaceDetector.load(o),Ud=o=>P.tinyYolov2.load(o),Xd=o=>P.faceLandmark68Net.load(o),Jd=o=>P.faceLandmark68TinyNet.load(o),qd=o=>P.faceRecognitionNet.load(o),Zd=o=>P.faceExpressionNet.load(o),Kd=o=>P.ageGenderNet.load(o),Qd=nn,th=rn,eh=on;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=>P.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=>P.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=>P.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=>P.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=>P.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=>P.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?P.faceLandmark68TinyNet:P.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=P.tinyFaceDetector.locateFaces(t,e);else if(e instanceof z)r=P.ssdMobilenetv1.locateFaces(t,e);else if(e instanceof J)r=P.tinyYolov2.locateFaces(t,e);else throw new Error("detectFaces - expected options to be instance of TinyFaceDetectorOptions | SsdMobilenetv1Options | TinyYolov2Options");return r}runAndExtendWithFaceDetections(){return new Promise((t,e)=>{this.run().then(r=>t(r.map(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 Kh(o,t=new z){return new He(o,t)}function mr(o,t=new z){return new me(o,t)}async function an(o,t){return mr(o,new z(t?{minConfidence:t}:{})).withFaceLandmarks().withFaceDescriptors()}async function nb(o,t={}){return mr(o,new J(t)).withFaceLandmarks().withFaceDescriptors()}var ab=an;function lo(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 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=>lo(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 Pb(o){let t=new Zt;return t.extractWeights(o),t}function sn(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=>sn(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 Ab=Wr;export{Me as AgeGenderNet,Nt as BoundingBox,w 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,Sr as FACE_EXPRESSION_LABELS,E as FaceDetection,to as FaceDetectionNet,we as FaceExpressionNet,pt as FaceExpressions,jt as FaceLandmark68Net,Ie as FaceLandmark68TinyNet,Vr as FaceLandmarkNet,$ as FaceLandmarks,vr 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,b as Point,yr as PredictedBox,St as Rect,Pt as SsdMobilenetv1,z as SsdMobilenetv1Options,Zt as TinyFaceDetector,Le as TinyFaceDetectorOptions,Jt as TinyYolov2,J as TinyYolov2Options,ab as allFaces,an as allFacesSsdMobilenetv1,nb as allFacesTinyYolov2,_r as awaitMediaLoaded,Tr as bufferToImage,Vd as computeFaceDescriptor,Rt as createCanvas,be as createCanvasFromMedia,vl as createFaceDetectionNet,vf as createFaceRecognitionNet,Qo as createSsdMobilenetv1,Pb as createTinyFaceDetector,pd as createTinyYolov2,mr as detectAllFaces,on as detectFaceLandmarks,zd as detectFaceLandmarksTiny,eh as detectLandmarks,Kh as detectSingleFace,Ar as draw,T as env,lo 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,Mi as fetchImage,Fr as fetchJson,Li as fetchNetWeights,mt as fetchOrThrow,$i as fetchVideo,k as getContext2dOrThrow,Bt as getMediaDimensions,Pr as imageTensorToCanvas,wr as imageToSquare,Vn as inverseSigmoid,hr as iou,Qe as isMediaElement,he as isMediaLoaded,Pf as isWithAge,tt as isWithFaceDetection,Lr as isWithFaceExpressions,Yt as isWithFaceLandmarks,Ef as isWithGender,Kd as loadAgeGenderModel,Qd as loadFaceDetectionModel,Zd as loadFaceExpressionModel,Xd as loadFaceLandmarkModel,Jd as loadFaceLandmarkTinyModel,qd as loadFaceRecognitionModel,nn as loadSsdMobilenetv1Model,jd as loadTinyFaceDetectorModel,Ud as loadTinyYolov2Model,Er as loadWeightMap,th as locateFaces,ji as matchDimensions,br as minBbox,P as nets,gr as nonMaxSuppression,X as normalize,xr as padToSquare,Gd as predictAgeAndGender,Yd as recognizeFaceExpressions,sn as resizeResults,Wt as resolveInput,Hn as shuffleArray,fe as sigmoid,rn as ssdMobilenetv1,n as tf,Od as tinyFaceDetector,Hd as tinyYolov2,M as toNetInput,dr as utils,io as validateConfig,Ab as version};
|