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

3 lines
83 KiB
JavaScript

var fe=Object.defineProperty,pn=Object.prototype.hasOwnProperty,fn=(t,e)=>()=>(e||(e={exports:{}},t(e.exports,e)),e.exports),jr=t=>fe(t,"__esModule",{value:!0}),He=(t,e)=>{jr(t);for(var r in e)fe(t,r,{get:e[r],enumerable:!0})},ln=(t,e)=>{if(jr(t),typeof e=="object"||typeof e=="function")for(let r in e)!pn.call(t,r)&&r!=="default"&&fe(t,r,{get:()=>e[r],enumerable:!0});return t},un=t=>t&&t.__esModule?t:ln(fe({},"default",{value:t,enumerable:!0}),t);var Hr=fn((dn,$r)=>{He(dn,{isNodejs:()=>hn});function hn(){return typeof global=="object"&&!0&&typeof $r!="undefined"&&typeof process!="undefined"&&!!process.version}});function Z(t,e,r=!1){if(t.beginPath(),e.slice(1).forEach(({x:o,y:n},a)=>{const i=e[a];t.moveTo(i.x,i.y),t.lineTo(o,n)}),r){const o=e[e.length-1],n=e[0];if(!o||!n)return;t.moveTo(o.x,o.y),t.lineTo(n.x,n.y)}t.stroke()}class S{constructor(t,e){if(!H(t)||!H(e))throw new Error(`Dimensions.constructor - expected width and height to be valid numbers, instead have ${JSON.stringify({width:t,height:e})}`);this._width=t,this._height=e}get width(){return this._width}get height(){return this._height}reverse(){return new S(1/this.width,1/this.height)}}const Ge={};He(Ge,{computeReshapedDimensions:()=>Ve,getCenterPoint:()=>ut,isDimensions:()=>ue,isEven:()=>le,isFloat:()=>Ye,isTensor:()=>ft,isTensor1D:()=>bn,isTensor2D:()=>ze,isTensor3D:()=>K,isTensor4D:()=>W,isValidNumber:()=>H,isValidProbablitiy:()=>Mt,range:()=>X,round:()=>lt});import{Tensor as gn}from"@tensorflow/tfjs/dist/tf.es2017.js";function ft(t,e){return t instanceof gn&&t.shape.length===e}function bn(t){return ft(t,1)}function ze(t){return ft(t,2)}function K(t){return ft(t,3)}function W(t){return ft(t,4)}function Ye(t){return t%1!==0}function le(t){return t%2===0}function lt(t,e=2){const r=Math.pow(10,e);return Math.floor(t*r)/r}function ue(t){return t&&t.width&&t.height}function Ve({width:t,height:e},r){const o=r/Math.max(e,t);return new S(Math.round(t*o),Math.round(e*o))}function ut(t){return t.reduce((e,r)=>e.add(r),new g(0,0)).div(new g(t.length,t.length))}function X(t,e,r){return Array(t).fill(0).map((o,n)=>e+n*r)}function H(t){return!!t&&t!==Infinity&&t!==-Infinity&&!isNaN(t)||t===0}function Mt(t){return H(t)&&0<=t&&t<=1}class g{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(Math.pow(this.x,2)+Math.pow(this.y,2))}floor(){return new g(Math.floor(this.x),Math.floor(this.y))}}class F{static isRect(t){return!!t&&[t.x,t.y,t.width,t.height].every(H)}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){const r=t||{},o=[r.left,r.top,r.right,r.bottom].every(H),n=[r.x,r.y,r.width,r.height].every(H);if(!n&&!o)throw new Error(`Box.constructor - expected box to be IBoundingBox | IRect, instead have ${JSON.stringify(r)}`);const[a,i,s,c]=n?[r.x,r.y,r.width,r.height]:[r.left,r.top,r.right-r.left,r.bottom-r.top];F.assertIsValidBox({x:a,y:i,width:s,height:c},"Box.constructor",e),this._x=a,this._y=i,this._width=s,this._height=c}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(){const[t,e,r,o]=[this.x,this.y,this.width,this.height].map(n=>Math.round(n));return new F({x:t,y:e,width:r,height:o})}floor(){const[t,e,r,o]=[this.x,this.y,this.width,this.height].map(n=>Math.floor(n));return new F({x:t,y:e,width:r,height:o})}toSquare(){let{x:t,y:e,width:r,height:o}=this;const n=Math.abs(r-o);return r<o&&(t-=n/2,r+=n),o<r&&(e-=n/2,o+=n),new F({x:t,y:e,width:r,height:o})}rescale(t){const 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,o,n,a]=[this.x-t/2,this.y-e/2,this.width+t,this.height+e];return new F({x:r,y:o,width:n,height:a})}clipAtImageBorders(t,e){const{x:r,y:o,right:n,bottom:a}=this,i=Math.max(r,0),s=Math.max(o,0),c=n-i,m=a-s,p=Math.min(c,t-i),f=Math.min(m,e-s);return new F({x:i,y:s,width:p,height:f}).floor()}shift(t,e){const{width:r,height:o}=this,n=this.x+t,a=this.y+e;return new F({x:n,y:a,width:r,height:o})}padAtBorders(t,e){const r=this.width+1,o=this.height+1;let n=1,a=1,i=r,s=o,c=this.left,m=this.top,p=this.right,f=this.bottom;return p>e&&(i=-p+e+r,p=e),f>t&&(s=-f+t+o,f=t),c<1&&(s=2-c,c=1),m<1&&(s=2-m,m=1),{dy:a,edy:s,dx:n,edx:i,y:m,ey:f,x:c,ex:p,w:r,h:o}}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()}}class Ut extends F{constructor(t,e,r,o,n=!1){super({left:t,top:e,right:r,bottom:o},n)}}class Ct{constructor(t,e,r,o,n){this._imageDims=new S(n.width,n.height),this._score=t,this._classScore=e,this._className=r,this._box=new F(o).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})}}class _ extends Ct{constructor(t,e,r){super(t,t,"",e,r)}forSize(t,e){const{score:r,relativeBox:o,imageDims:n}=super.forSize(t,e);return new _(r,o,n)}}function Ue(t,e,r=!0){const o=Math.max(0,Math.min(t.right,e.right)-Math.max(t.left,e.left)),n=Math.max(0,Math.min(t.bottom,e.bottom)-Math.max(t.top,e.top)),a=o*n;return r?a/(t.area+e.area-a):a/Math.min(t.area,e.area)}function Xe(t){const e=t.map(s=>s.x),r=t.map(s=>s.y),o=e.reduce((s,c)=>c<s?c:s,Infinity),n=r.reduce((s,c)=>c<s?c:s,Infinity),a=e.reduce((s,c)=>s<c?c:s,0),i=r.reduce((s,c)=>s<c?c:s,0);return new Ut(o,n,a,i)}function Je(t,e,r,o=!0){let n=e.map((i,s)=>({score:i,boxIndex:s})).sort((i,s)=>i.score-s.score).map(i=>i.boxIndex);const a=[];for(;n.length>0;){const i=n.pop();a.push(i);const s=n,c=[];for(let m=0;m<s.length;m++){const p=s[m],f=t[i],l=t[p];c.push(Ue(f,l,o))}n=n.filter((m,p)=>c[p]<=r)}return a}import{concat as xn,fill as qe,sub as vn,tidy as yn}from"@tensorflow/tfjs/dist/tf.es2017.js";function G(t,e){return yn(()=>{const[r,o,n]=e,a=qe([...t.shape.slice(0,3),1],r),i=qe([...t.shape.slice(0,3),1],o),s=qe([...t.shape.slice(0,3),1],n),c=xn([a,i,s],3);return vn(t,c)})}import{cast as Tn,concat as Fn,fill as wn,tidy as Pn}from"@tensorflow/tfjs/dist/tf.es2017.js";function Ze(t,e=!1){return Pn(()=>{const[r,o]=t.shape.slice(1);if(r===o)return t;const n=Math.abs(r-o),a=Math.round(n*(e?.5:1)),i=r>o?2:1,s=l=>{const u=t.shape.slice();return u[i]=l,wn(u,0)},c=s(a),m=n-c.shape[i],p=e&&m?s(m):null,f=[p,t,c].filter(l=>!!l).map(l=>Tn(l,"float32"));return Fn(f,i)})}function _n(t){const e=t.slice();for(let r=e.length-1;r>0;r--){const o=Math.floor(Math.random()*(r+1)),n=e[r];e[r]=e[o],e[o]=n}return e}function Xt(t){return 1/(1+Math.exp(-t))}function Dn(t){return Math.log(t/(1-t))}class Jt extends F{constructor(t,e,r,o,n=!1){super({x:t,y:e,width:r,height:o},n)}}const En=.5,Mn=.43,Cn=.45;class O{constructor(t,e,r=new g(0,0)){const{width:o,height:n}=e;this._imgDims=new S(o,n),this._shift=r,this._positions=t.map(a=>a.mul(new g(o,n)).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){const n=t instanceof _?t.box.floor():new F(t);return this.shiftBy(n.x,n.y).align(null,e)}const{useDlibAlignment:r,minBoxPadding:o}=Object.assign({},{useDlibAlignment:!1,minBoxPadding:.2},e);return r?this.alignDlib():this.alignMinBbox(o)}alignDlib(){const t=this.getRefPointsForAlignment(),[e,r,o]=t,n=p=>o.sub(p).magnitude(),a=(n(e)+n(r))/2,i=Math.floor(a/Cn),s=ut(t),c=Math.floor(Math.max(0,s.x-En*i)),m=Math.floor(Math.max(0,s.y-Mn*i));return new Jt(c,m,Math.min(i,this.imageWidth+c),Math.min(i,this.imageHeight+m))}alignMinBbox(t){const e=Xe(this.positions);return e.pad(e.width*t,e.height*t)}getRefPointsForAlignment(){throw new Error("getRefPointsForAlignment not implemented by base class")}}class kn extends O{getRefPointsForAlignment(){const t=this.positions;return[t[0],t[1],ut([t[3],t[4]])]}}class qt extends O{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(ut)}}class de{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?` (${lt(this.distance)})`:""}`}}class he extends F{static assertIsValidLabeledBox(t,e){if(F.assertIsValidBox(t,e),!H(t.label))throw new Error(`${e} - expected property label (${t.label}) to be a number`)}constructor(t,e){super(t);this._label=e}get label(){return this._label}}class dt{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){const e=t.descriptors.map(r=>new Float32Array(r));return new dt(t.label,e)}}class Nn extends he{static assertIsValidPredictedBox(t,e){if(he.assertIsValidLabeledBox(t,e),!Mt(t.score)||!Mt(t.classScore))throw new Error(`${e} - expected properties score (${t.score}) and (${t.classScore}) to be a number between [0, 1]`)}constructor(t,e,r,o){super(t,e);this._score=r,this._classScore=o}get score(){return this._score}get classScore(){return this._classScore}}function J(t){return t.detection instanceof _}function ht(t,e){const r={detection:e};return Object.assign({},t,r)}function Ke(){const t=window.fetch||function(){throw new Error("fetch - missing fetch implementation for browser environment")},e=function(){throw new Error("readFile - filesystem not available for browser environment")};return{Canvas:HTMLCanvasElement,CanvasRenderingContext2D,Image:HTMLImageElement,ImageData,Video:HTMLVideoElement,createCanvasElement:()=>document.createElement("canvas"),createImageElement:()=>document.createElement("img"),fetch:t,readFile:e}}function ge(t){let e="";if(!t)try{t=require("fs")}catch(o){e=o.toString()}const r=t?function(o){return new Promise((n,a)=>{t.readFile(o,function(i,s){return i?a(i):n(s)})})}:function(){throw new Error(`readFile - failed to require fs in nodejs environment with error: ${e}`)};return{readFile:r}}function Qe(){const t=global.Canvas||global.HTMLCanvasElement,e=global.Image||global.HTMLImageElement,r=function(){if(t)return new t;throw new Error("createCanvasElement - missing Canvas implementation for nodejs environment")},o=function(){if(e)return new e;throw new Error("createImageElement - missing Image implementation for nodejs environment")},n=global.fetch||function(){throw new Error("fetch - missing fetch implementation for nodejs environment")},a=ge();return{Canvas:t||class{},CanvasRenderingContext2D:global.CanvasRenderingContext2D||class{},Image:e||class{},ImageData:global.ImageData||class{},Video:global.HTMLVideoElement||class{},createCanvasElement:r,createImageElement:o,fetch:n,...a}}function tr(){return typeof window=="object"&&typeof document!="undefined"&&typeof HTMLImageElement!="undefined"&&typeof HTMLCanvasElement!="undefined"&&typeof HTMLVideoElement!="undefined"&&typeof ImageData!="undefined"&&typeof CanvasRenderingContext2D!="undefined"}const er=un(Hr());let D;function Ln(){if(!D)throw new Error("getEnv - environment is not defined, check isNodejs() and isBrowser()");return D}function rr(t){D=t}function or(){if(tr())return rr(Ke());if(er.isNodejs())return rr(Qe())}function In(t){if(D||or(),!D)throw new Error("monkeyPatch - environment is not defined, check isNodejs() and isBrowser()");const{Canvas:e=D.Canvas,Image:r=D.Image}=t;D.Canvas=e,D.Image=r,D.createCanvasElement=t.createCanvasElement||(()=>new e),D.createImageElement=t.createImageElement||(()=>new r),D.ImageData=t.ImageData||D.ImageData,D.Video=t.Video||D.Video,D.fetch=t.fetch||D.fetch,D.readFile=t.readFile||D.readFile}const T={getEnv:Ln,setEnv:rr,initialize:or,createBrowserEnv:Ke,createFileSystem:ge,createNodejsEnv:Qe,monkeyPatch:In,isBrowser:tr,isNodejs:er.isNodejs};or();function gt(t){return!T.isNodejs()&&typeof t=="string"?document.getElementById(t):t}function N(t){const{Canvas:e,CanvasRenderingContext2D:r}=T.getEnv();if(t instanceof r)return t;const o=gt(t);if(!(o instanceof e))throw new Error("resolveContext2d - expected canvas to be of instance of Canvas");const n=o.getContext("2d");if(!n)throw new Error("resolveContext2d - canvas 2d context is null");return n}var q;(function(t){t.TOP_LEFT="TOP_LEFT",t.TOP_RIGHT="TOP_RIGHT",t.BOTTOM_LEFT="BOTTOM_LEFT",t.BOTTOM_RIGHT="BOTTOM_RIGHT"})(q||(q={}));class be{constructor(t={}){const{anchorPosition:e,backgroundColor:r,fontColor:o,fontSize:n,fontStyle:a,padding:i}=t;this.anchorPosition=e||q.TOP_LEFT,this.backgroundColor=r||"rgba(0, 0, 0, 0.5)",this.fontColor=o||"rgba(255, 255, 255, 1)",this.fontSize=n||14,this.fontStyle=a||"Georgia",this.padding=i||4}}class kt{constructor(t,e,r={}){this.text=typeof t=="string"?[t]:t instanceof kt?t.text:t,this.anchor=e,this.options=new be(r)}measureWidth(t){const{padding:e}=this.options;return this.text.map(r=>t.measureText(r).width).reduce((r,o)=>r<o?o:r,0)+2*e}measureHeight(){const{fontSize:t,padding:e}=this.options;return this.text.length*t+2*e}getUpperLeft(t,e){const{anchorPosition:r}=this.options,o=r===q.BOTTOM_RIGHT||r===q.TOP_RIGHT,n=r===q.BOTTOM_LEFT||r===q.BOTTOM_RIGHT,a=this.measureWidth(t),i=this.measureHeight(),s=o?this.anchor.x-a:this.anchor.x,c=n?this.anchor.y-i:this.anchor.y;if(e){const{width:m,height:p}=e,f=Math.max(Math.min(s,m-a),0),l=Math.max(Math.min(c,p-i),0);return{x:f,y:l}}return{x:s,y:c}}draw(t){const e=gt(t),r=N(e),{backgroundColor:o,fontColor:n,fontSize:a,fontStyle:i,padding:s}=this.options;r.font=`${a}px ${i}`;const c=this.measureWidth(r),m=this.measureHeight();r.fillStyle=o;const p=this.getUpperLeft(r,e);r.fillRect(p.x,p.y,c,m),r.fillStyle=n,this.text.forEach((f,l)=>{const u=s+p.x,v=s+p.y+(l+1)*a;r.fillText(f,u,v)})}}class Gr{constructor(t={}){const{boxColor:e,lineWidth:r,label:o,drawLabelOptions:n}=t;this.boxColor=e||"rgba(0, 0, 255, 1)",this.lineWidth=r||2,this.label=o;const a={anchorPosition:q.BOTTOM_LEFT,backgroundColor:this.boxColor};this.drawLabelOptions=new be(Object.assign({},a,n))}}class nr{constructor(t,e={}){this.box=new F(t),this.options=new Gr(e)}draw(t){const e=N(t),{boxColor:r,lineWidth:o}=this.options,{x:n,y:a,width:i,height:s}=this.box;e.strokeStyle=r,e.lineWidth=o,e.strokeRect(n,a,i,s);const{label:c}=this.options;c&&new kt([c],{x:n-o/2,y:a},this.options.drawLabelOptions).draw(t)}}function Sn(t,e){const r=Array.isArray(e)?e:[e];r.forEach(o=>{const n=o instanceof _?o.score:J(o)?o.detection.score:void 0,a=o instanceof _?o.box:J(o)?o.detection.box:new F(o),i=n?`${lt(n)}`:void 0;new nr(a,{label:i}).draw(t)})}function Zt(t){const{Image:e,Video:r}=T.getEnv();return t instanceof e&&t.complete||t instanceof r&&t.readyState>=3}function ar(t){return new Promise((e,r)=>{if(t instanceof T.getEnv().Canvas||Zt(t))return e(null);function o(a){if(!a.currentTarget)return;a.currentTarget.removeEventListener("load",o),a.currentTarget.removeEventListener("error",n),e(a)}function n(a){if(!a.currentTarget)return;a.currentTarget.removeEventListener("load",o),a.currentTarget.removeEventListener("error",n),r(a)}t.addEventListener("load",o),t.addEventListener("error",n)})}function sr(t){return new Promise((e,r)=>{if(!(t instanceof Blob))return r("bufferToImage - expected buf to be of type: Blob");const o=new FileReader;o.onload=()=>{if(typeof o.result!="string")return r("bufferToImage - expected reader.result to be a string, in onload");const n=T.getEnv().createImageElement();n.onload=()=>e(n),n.onerror=r,n.src=o.result},o.onerror=r,o.readAsDataURL(t)})}function bt(t){const{Image:e,Video:r}=T.getEnv();return t instanceof e?new S(t.naturalWidth,t.naturalHeight):t instanceof r?new S(t.videoWidth,t.videoHeight):new S(t.width,t.height)}function Nt({width:t,height:e}){const{createCanvasElement:r}=T.getEnv(),o=r();return o.width=t,o.height=e,o}function Kt(t,e){const{ImageData:r}=T.getEnv();if(!(t instanceof r)&&!Zt(t))throw new Error("createCanvasFromMedia - media has not finished loading yet");const{width:o,height:n}=e||bt(t),a=Nt({width:o,height:n});return t instanceof r?N(a).putImageData(t,0,0):N(a).drawImage(t,0,0,o,n),a}import{browser as An,tidy as Wn}from"@tensorflow/tfjs/dist/tf.es2017.js";async function ir(t,e){const r=e||T.getEnv().createCanvasElement(),[o,n,a]=t.shape.slice(W(t)?1:0),i=Wn(()=>t.as3D(o,n,a).toInt());return await An.toPixels(i,r),i.dispose(),r}function xe(t){const{Image:e,Canvas:r,Video:o}=T.getEnv();return t instanceof e||t instanceof r||t instanceof o}function cr(t,e,r=!1){const{Image:o,Canvas:n}=T.getEnv();if(!(t instanceof o||t instanceof n))throw new Error("imageToSquare - expected arg0 to be HTMLImageElement | HTMLCanvasElement");const a=bt(t),i=e/Math.max(a.height,a.width),s=i*a.width,c=i*a.height,m=Nt({width:e,height:e}),p=t instanceof n?t:Kt(t),f=Math.abs(s-c)/2,l=r&&s<c?f:0,u=r&&c<s?f:0;return N(m).drawImage(p,l,u,s,c),m}import{Tensor as Bn,browser as Rn,cast as On,image as jn,stack as $n,tidy as Hn}from"@tensorflow/tfjs-core";class st{constructor(t,e=!1){this._imageTensors=[];this._canvases=[];this._treatAsBatchInput=!1;this._inputDimensions=[];if(!Array.isArray(t))throw new Error(`NetInput.constructor - expected inputs to be an Array of TResolvedNetInput or to be instanceof tf.Tensor4D, instead have ${t}`);this._treatAsBatchInput=e,this._batchSize=t.length,t.forEach((r,o)=>{if(K(r)){this._imageTensors[o]=r,this._inputDimensions[o]=r.shape;return}if(W(r)){const a=r.shape[0];if(a!==1)throw new Error(`NetInput - tf.Tensor4D with batchSize ${a} passed, but not supported in input array`);this._imageTensors[o]=r,this._inputDimensions[o]=r.shape.slice(1);return}const n=r instanceof T.getEnv().Canvas?r:Kt(r);this._canvases[o]=n,this._inputDimensions[o]=[n.height,n.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 X(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");const e=this.getInputWidth(t),r=this.getInputHeight(t);return Ve({width:e,height:r},this.inputSize)}toBatchTensor(t,e=!0){return this._inputSize=t,Hn(()=>{const r=X(this.batchSize,0,1).map(n=>{const a=this.getInput(n);if(a instanceof Bn){let i=W(a)?a:a.expandDims();return i=Ze(i,e),(i.shape[1]!==t||i.shape[2]!==t)&&(i=jn.resizeBilinear(i,[t,t])),i.as3D(t,t,3)}if(a instanceof T.getEnv().Canvas)return Rn.fromPixels(cr(a,t,e));throw new Error(`toBatchTensor - at batchIdx ${n}, expected input to be instanceof tf.Tensor or instanceof HTMLCanvasElement, instead have ${a}`)}),o=$n(r.map(n=>On(n,"float32"))).as4D(this.batchSize,t,t,3);return o})}}async function w(t){if(t instanceof st)return t;let e=Array.isArray(t)?t:[t];if(!e.length)throw new Error("toNetInput - empty array passed as input");const r=n=>Array.isArray(t)?` at input index ${n}:`:"",o=e.map(gt);return o.forEach((n,a)=>{if(!xe(n)&&!K(n)&&!W(n))throw typeof e[a]=="string"?new Error(`toNetInput -${r(a)} string passed, but could not resolve HTMLElement for element id ${e[a]}`):new Error(`toNetInput -${r(a)} expected media to be of type HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | tf.Tensor3D, or to be an element id`);if(W(n)){const i=n.shape[0];if(i!==1)throw new Error(`toNetInput -${r(a)} tf.Tensor4D with batchSize ${i} passed, but not supported in input array`)}}),await Promise.all(o.map(n=>xe(n)&&ar(n))),new st(o,Array.isArray(t))}async function Lt(t,e){const{Canvas:r}=T.getEnv();let o=t;if(!(t instanceof r)){const i=await w(t);if(i.batchSize>1)throw new Error("extractFaces - batchSize > 1 not supported");const s=i.getInput(0);o=s instanceof r?s:await ir(s)}const n=N(o),a=e.map(i=>i instanceof _?i.forSize(o.width,o.height).box.floor():i).map(i=>i.clipAtImageBorders(o.width,o.height));return a.map(({x:i,y:s,width:c,height:m})=>{const p=Nt({width:c,height:m});return N(p).putImageData(n.getImageData(i,s,c,m),0,0),p})}import{slice3d as Gn,tidy as zn}from"@tensorflow/tfjs/dist/tf.es2017.js";async function It(t,e){if(!K(t)&&!W(t))throw new Error("extractFaceTensors - expected image tensor to be 3D or 4D");if(W(t)&&t.shape[0]>1)throw new Error("extractFaceTensors - batchSize > 1 not supported");return zn(()=>{const[r,o,n]=t.shape.slice(W(t)?1:0),a=e.map(s=>s instanceof _?s.forSize(o,r).box:s).map(s=>s.clipAtImageBorders(o,r)),i=a.map(({x:s,y:c,width:m,height:p})=>Gn(t.as3D(r,o,n),[c,s,0],[p,m,n]));return i})}async function xt(t,e){const r=T.getEnv().fetch,o=await r(t,e);if(!(o.status<400))throw new Error(`failed to fetch: (${o.status}) ${o.statusText}, from url: ${o.url}`);return o}async function Yn(t){const e=await xt(t),r=await e.blob();if(!r.type.startsWith("image/"))throw new Error(`fetchImage - expected blob type to be of type image/*, instead have: ${r.type}, for url: ${e.url}`);return sr(r)}async function mr(t){return(await xt(t)).json()}async function Vn(t){return new Float32Array(await(await xt(t)).arrayBuffer())}function ve(t,e){const r=`${e}-weights_manifest.json`;if(!t)return{modelBaseUri:"",manifestUri:r};if(t==="/")return{modelBaseUri:"/",manifestUri:`/${r}`};const o=t.startsWith("http://")?"http://":t.startsWith("https://")?"https://":"";t=t.replace(o,"");const n=t.split("/").filter(s=>s),a=t.endsWith(".json")?n[n.length-1]:r;let i=o+(t.endsWith(".json")?n.slice(0,n.length-1):n).join("/");return i=t.startsWith("/")?`/${i}`:i,{modelBaseUri:i,manifestUri:i==="/"?`/${a}`:`${i}/${a}`}}import{io as Un}from"@tensorflow/tfjs/dist/tf.es2017.js";async function pr(t,e){const{manifestUri:r,modelBaseUri:o}=ve(t,e);let n=await mr(r);return Un.loadWeights(n,o)}function Xn(t,e,r=!1){const{width:o,height:n}=r?bt(e):e;return t.width=o,t.height=n,{width:o,height:n}}import{Tensor as Jn,Variable as zr,io as qn,tensor as Zn}from"@tensorflow/tfjs/dist/tf.es2017.js";class E{constructor(t){this._name=t;this._params=void 0;this._paramMappings=[]}get params(){return this._params}get paramMappings(){return this._paramMappings}get isLoaded(){return!!this.params}getParamFromPath(t){const{obj:e,objProp:r}=this.traversePropertyPath(t);return e[r]}reassignParamFromPath(t,e){const{obj:r,objProp:o}=this.traversePropertyPath(t);r[o].dispose(),r[o]=e}getParamList(){return this._paramMappings.map(({paramPath:t})=>({path:t,tensor:this.getParamFromPath(t)}))}getTrainableParams(){return this.getParamList().filter(t=>t.tensor instanceof zr)}getFrozenParams(){return this.getParamList().filter(t=>!(t.tensor instanceof zr))}variable(){this.getFrozenParams().forEach(({path:t,tensor:e})=>{this.reassignParamFromPath(t,e.variable())})}freeze(){this.getTrainableParams().forEach(({path:t,tensor:e})=>{const r=Zn(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`);const e=await pr(t,this.getDefaultModelName());this.loadFromWeightMap(e)}async loadFromDisk(t){if(t&&typeof t!="string")throw new Error(`${this._name}.loadFromDisk - expected model file path`);const{readFile:e}=T.getEnv(),{manifestUri:r,modelBaseUri:o}=ve(t,this.getDefaultModelName()),n=c=>Promise.all(c.map(m=>e(m).then(p=>p.buffer))),a=qn.weightsLoaderFactory(n),i=JSON.parse((await e(r)).toString()),s=await a(i,o);this.loadFromWeightMap(s)}loadFromWeightMap(t){const{paramMappings:e,params:r}=this.extractParamsFromWeigthMap(t);this._paramMappings=e,this._params=r}extractWeights(t){const{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");const e=t.split("/").reduce((n,a)=>{if(!n.nextObj.hasOwnProperty(a))throw new Error(`traversePropertyPath - object does not have property ${a}, for path ${t}`);return{obj:n.nextObj,objProp:a,nextObj:n.nextObj[a]}},{nextObj:this.params}),{obj:r,objProp:o}=e;if(!r||!o||!(r[o]instanceof Jn))throw new Error(`traversePropertyPath - parameter is not a tensor, for path ${t}`);return{obj:r,objProp:o}}}import{add as Kn,separableConv2d as Qn,tidy as ta}from"@tensorflow/tfjs/dist/tf.es2017.js";function L(t,e,r){return ta(()=>{let o=Qn(t,e.depthwise_filter,e.pointwise_filter,r,"same");return o=Kn(o,e.bias),o})}import{add as z,conv2d as Yr,relu as vt,tidy as Vr}from"@tensorflow/tfjs/dist/tf.es2017.js";function ye(t,e,r=!1){return Vr(()=>{const o=vt(r?z(Yr(t,e.conv0.filters,[2,2],"same"),e.conv0.bias):L(t,e.conv0,[2,2])),n=L(o,e.conv1,[1,1]),a=vt(z(o,n)),i=L(a,e.conv2,[1,1]);return vt(z(o,z(n,i)))})}function Qt(t,e,r=!1,o=!0){return Vr(()=>{const n=vt(r?z(Yr(t,e.conv0.filters,o?[2,2]:[1,1],"same"),e.conv0.bias):L(t,e.conv0,o?[2,2]:[1,1])),a=L(n,e.conv1,[1,1]),i=vt(z(n,a)),s=L(i,e.conv2,[1,1]),c=vt(z(n,z(a,s))),m=L(c,e.conv3,[1,1]);return vt(z(n,z(a,z(s,m))))})}import{add as ea,conv2d as ra,relu as oa,tidy as na}from"@tensorflow/tfjs/dist/tf.es2017.js";function yt(t,e,r="same",o=!1){return na(()=>{const n=ea(ra(t,e.filters,[1,1],r),e.bias);return o?oa(n):n})}function M(t,e){Object.keys(t).forEach(r=>{e.some(o=>o.originalPath===r)||t[r].dispose()})}import{tensor1d as aa,tensor4d as sa}from"@tensorflow/tfjs/dist/tf.es2017.js";function St(t,e){return function(r,o,n,a){const i=sa(t(r*o*n*n),[n,n,r,o]),s=aa(t(o));return e.push({paramPath:`${a}/filters`},{paramPath:`${a}/bias`}),{filters:i,bias:s}}}import{tensor1d as ia,tensor2d as ca}from"@tensorflow/tfjs/dist/tf.es2017.js";function Te(t,e){return function(r,o,n){const a=ca(t(r*o),[r,o]),i=ia(t(o));return e.push({paramPath:`${n}/weights`},{paramPath:`${n}/bias`}),{weights:a,bias:i}}}class fr{constructor(t,e,r){this.depthwise_filter=t;this.pointwise_filter=e;this.bias=r}}import{tensor1d as ma,tensor4d as Ur}from"@tensorflow/tfjs/dist/tf.es2017.js";function At(t,e){return function(r,o,n){const a=Ur(t(3*3*r),[3,3,r,1]),i=Ur(t(r*o),[1,1,r,o]),s=ma(t(o));return e.push({paramPath:`${n}/depthwise_filter`},{paramPath:`${n}/pointwise_filter`},{paramPath:`${n}/bias`}),new fr(a,i,s)}}function Wt(t){return function(e){const r=t(`${e}/depthwise_filter`,4),o=t(`${e}/pointwise_filter`,4),n=t(`${e}/bias`,1);return new fr(r,o,n)}}function A(t,e){return function(r,o,n){const a=t[r];if(!ft(a,o))throw new Error(`expected weightMap[${r}] to be a Tensor${o}D, instead have ${a}`);return e.push({originalPath:r,paramPath:n||r}),a}}function C(t){let e=t;function r(n){const a=e.slice(0,n);return e=e.slice(n),a}function o(){return e}return{extractWeights:r,getRemainingWeights:o}}function Fe(t,e){const r=St(t,e),o=At(t,e);function n(i,s,c,m=!1){const p=m?r(i,s,3,`${c}/conv0`):o(i,s,`${c}/conv0`),f=o(s,s,`${c}/conv1`),l=o(s,s,`${c}/conv2`);return{conv0:p,conv1:f,conv2:l}}function a(i,s,c,m=!1){const{conv0:p,conv1:f,conv2:l}=n(i,s,c,m),u=o(s,s,`${c}/conv3`);return{conv0:p,conv1:f,conv2:l,conv3:u}}return{extractDenseBlock3Params:n,extractDenseBlock4Params:a}}function Xr(t){const e=[],{extractWeights:r,getRemainingWeights:o}=C(t),{extractDenseBlock4Params:n}=Fe(r,e),a=n(3,32,"dense0",!0),i=n(32,64,"dense1"),s=n(64,128,"dense2"),c=n(128,256,"dense3");if(o().length!==0)throw new Error(`weights remaing after extract: ${o().length}`);return{paramMappings:e,params:{dense0:a,dense1:i,dense2:s,dense3:c}}}function we(t){return function(e){const r=t(`${e}/filters`,4),o=t(`${e}/bias`,1);return{filters:r,bias:o}}}function Pe(t,e){const r=A(t,e),o=we(r),n=Wt(r);function a(s,c=!1){const m=c?o(`${s}/conv0`):n(`${s}/conv0`),p=n(`${s}/conv1`),f=n(`${s}/conv2`);return{conv0:m,conv1:p,conv2:f}}function i(s,c=!1){const m=c?o(`${s}/conv0`):n(`${s}/conv0`),p=n(`${s}/conv1`),f=n(`${s}/conv2`),l=n(`${s}/conv3`);return{conv0:m,conv1:p,conv2:f,conv3:l}}return{extractDenseBlock3Params:a,extractDenseBlock4Params:i}}function Jr(t){const e=[],{extractDenseBlock4Params:r}=Pe(t,e),o={dense0:r("dense0",!0),dense1:r("dense1"),dense2:r("dense2"),dense3:r("dense3")};return M(t,e),{params:o,paramMappings:e}}import{avgPool as pa,scalar as fa,tidy as la}from"@tensorflow/tfjs/dist/tf.es2017.js";class _e extends E{constructor(){super("FaceFeatureExtractor")}forwardInput(t){const{params:e}=this;if(!e)throw new Error("FaceFeatureExtractor - load model before inference");return la(()=>{const r=t.toBatchTensor(112,!0),o=[122.782,117.001,104.298],n=G(r,o).div(fa(255));let a=Qt(n,e.dense0,!0);return a=Qt(a,e.dense1),a=Qt(a,e.dense2),a=Qt(a,e.dense3),a=pa(a,[7,7],[2,2],"valid"),a})}async forward(t){return this.forwardInput(await w(t))}getDefaultModelName(){return"face_feature_extractor_model"}extractParamsFromWeigthMap(t){return Jr(t)}extractParams(t){return Xr(t)}}import{add as ua,matMul as da,tidy as ha}from"@tensorflow/tfjs/dist/tf.es2017.js";function te(t,e){return ha(()=>ua(da(t,e.weights),e.bias))}function qr(t,e,r){const o=[],{extractWeights:n,getRemainingWeights:a}=C(t),i=Te(n,o),s=i(e,r,"fc");if(a().length!==0)throw new Error(`weights remaing after extract: ${a().length}`);return{paramMappings:o,params:{fc:s}}}function Zr(t){const e=[],r=A(t,e);function o(a){const i=r(`${a}/weights`,2),s=r(`${a}/bias`,1);return{weights:i,bias:s}}const n={fc:o("fc")};return M(t,e),{params:n,paramMappings:e}}function De(t){const e={},r={};return Object.keys(t).forEach(o=>{const n=o.startsWith("fc")?r:e;n[o]=t[o]}),{featureExtractorMap:e,classifierMap:r}}import{tidy as ga}from"@tensorflow/tfjs/dist/tf.es2017.js";class Ee extends E{constructor(t,e){super(t);this._faceFeatureExtractor=e}get faceFeatureExtractor(){return this._faceFeatureExtractor}runNet(t){const{params:e}=this;if(!e)throw new Error(`${this._name} - load model before inference`);return ga(()=>{const r=t instanceof st?this.faceFeatureExtractor.forwardInput(t):t;return te(r.as2D(r.shape[0],-1),e.fc)})}dispose(t=!0){this.faceFeatureExtractor.dispose(t),super.dispose(t)}loadClassifierParams(t){const{params:e,paramMappings:r}=this.extractClassifierParams(t);this._params=e,this._paramMappings=r}extractClassifierParams(t){return qr(t,this.getClassifierChannelsIn(),this.getClassifierChannelsOut())}extractParamsFromWeigthMap(t){const{featureExtractorMap:e,classifierMap:r}=De(t);return this.faceFeatureExtractor.loadFromWeightMap(e),Zr(r)}extractParams(t){const e=this.getClassifierChannelsIn(),r=this.getClassifierChannelsOut(),o=r*e+r,n=t.slice(0,t.length-o),a=t.slice(t.length-o);return this.faceFeatureExtractor.extractWeights(n),this.extractClassifierParams(a)}}const lr=["neutral","happy","sad","angry","fearful","disgusted","surprised"];class Tt{constructor(t){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)}}import{softmax as ba,tidy as xa,unstack as va}from"@tensorflow/tfjs/dist/tf.es2017.js";class ur extends Ee{constructor(t=new _e){super("FaceExpressionNet",t)}forwardInput(t){return xa(()=>ba(this.runNet(t)))}async forward(t){return this.forwardInput(await w(t))}async predictExpressions(t){const e=await w(t),r=await this.forwardInput(e),o=await Promise.all(va(r).map(async a=>{const i=await a.data();return a.dispose(),i}));r.dispose();const n=o.map(a=>new Tt(a));return e.isBatchInput?n:n[0]}getDefaultModelName(){return"face_expression_model"}getClassifierChannelsIn(){return 256}getClassifierChannelsOut(){return 7}}function dr(t){return t.expressions instanceof Tt}function Me(t,e){const r={expressions:e};return Object.assign({},t,r)}function ya(t,e,r=.1,o){const n=Array.isArray(e)?e:[e];n.forEach(a=>{const i=a instanceof Tt?a:dr(a)?a.expressions:void 0;if(!i)throw new Error("drawFaceExpressions - expected faceExpressions to be FaceExpressions | WithFaceExpressions<{}> or array thereof");const s=i.asSortedArray(),c=s.filter(f=>f.probability>r),m=J(a)?a.detection.box.bottomLeft:o||new g(0,0),p=new kt(c.map(f=>`${f.expression} (${lt(f.probability)})`),m);p.draw(t)})}function Ft(t){return J(t)&&t.landmarks instanceof O&&t.unshiftedLandmarks instanceof O&&t.alignedRect instanceof _}function Bt(t,e){const{box:r}=t.detection,o=e.shiftBy(r.x,r.y),n=o.align(),{imageDims:a}=t.detection,i=new _(t.detection.score,n.rescale(a.reverse()),a),s={landmarks:o,unshiftedLandmarks:e,alignedRect:i};return Object.assign({},t,s)}class Kr{constructor(t={}){const{drawLines:e=!0,drawPoints:r=!0,lineWidth:o,lineColor:n,pointSize:a,pointColor:i}=t;this.drawLines=e,this.drawPoints=r,this.lineWidth=o||1,this.pointSize=a||2,this.lineColor=n||"rgba(0, 255, 255, 1)",this.pointColor=i||"rgba(255, 0, 255, 1)"}}class Qr{constructor(t,e={}){this.faceLandmarks=t,this.options=new Kr(e)}draw(t){const e=N(t),{drawLines:r,drawPoints:o,lineWidth:n,lineColor:a,pointSize:i,pointColor:s}=this.options;if(r&&this.faceLandmarks instanceof qt&&(e.strokeStyle=a,e.lineWidth=n,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)),o){e.strokeStyle=s,e.fillStyle=s;const c=m=>{e.beginPath(),e.arc(m.x,m.y,i,0,2*Math.PI),e.fill()};this.faceLandmarks.positions.forEach(c)}}}function Ta(t,e){const r=Array.isArray(e)?e:[e];r.forEach(o=>{const n=o instanceof O?o:Ft(o)?o.landmarks:void 0;if(!n)throw new Error("drawFaceLandmarks - expected faceExpressions to be FaceLandmarks | WithFaceLandmarks<WithFaceDetection<{}>> or array thereof");new Qr(n).draw(t)})}const hr={};He(hr,{AnchorPosition:()=>q,DrawBox:()=>nr,DrawBoxOptions:()=>Gr,DrawFaceLandmarks:()=>Qr,DrawFaceLandmarksOptions:()=>Kr,DrawTextField:()=>kt,DrawTextFieldOptions:()=>be,drawContour:()=>Z,drawDetections:()=>Sn,drawFaceExpressions:()=>ya,drawFaceLandmarks:()=>Ta});function Fa(t,e){const r=St(t,e),o=At(t,e);function n(i,s,c){const m=o(i,s,`${c}/separable_conv0`),p=o(s,s,`${c}/separable_conv1`),f=r(i,s,1,`${c}/expansion_conv`);return{separable_conv0:m,separable_conv1:p,expansion_conv:f}}function a(i,s){const c=o(i,i,`${s}/separable_conv0`),m=o(i,i,`${s}/separable_conv1`),p=o(i,i,`${s}/separable_conv2`);return{separable_conv0:c,separable_conv1:m,separable_conv2:p}}return{extractConvParams:r,extractSeparableConvParams:o,extractReductionBlockParams:n,extractMainBlockParams:a}}function to(t,e){const r=[],{extractWeights:o,getRemainingWeights:n}=C(t),{extractConvParams:a,extractSeparableConvParams:i,extractReductionBlockParams:s,extractMainBlockParams:c}=Fa(o,r),m=a(3,32,3,"entry_flow/conv_in"),p=s(32,64,"entry_flow/reduction_block_0"),f=s(64,128,"entry_flow/reduction_block_1"),l={conv_in:m,reduction_block_0:p,reduction_block_1:f},u={};X(e,0,1).forEach(x=>{u[`main_block_${x}`]=c(128,`middle_flow/main_block_${x}`)});const v=s(128,256,"exit_flow/reduction_block"),d=i(256,512,"exit_flow/separable_conv"),b={reduction_block:v,separable_conv:d};if(n().length!==0)throw new Error(`weights remaing after extract: ${n().length}`);return{paramMappings:r,params:{entry_flow:l,middle_flow:u,exit_flow:b}}}function wa(t,e){const r=A(t,e),o=we(r),n=Wt(r);function a(s){const c=n(`${s}/separable_conv0`),m=n(`${s}/separable_conv1`),p=o(`${s}/expansion_conv`);return{separable_conv0:c,separable_conv1:m,expansion_conv:p}}function i(s){const c=n(`${s}/separable_conv0`),m=n(`${s}/separable_conv1`),p=n(`${s}/separable_conv2`);return{separable_conv0:c,separable_conv1:m,separable_conv2:p}}return{extractConvParams:o,extractSeparableConvParams:n,extractReductionBlockParams:a,extractMainBlockParams:i}}function eo(t,e){const r=[],{extractConvParams:o,extractSeparableConvParams:n,extractReductionBlockParams:a,extractMainBlockParams:i}=wa(t,r),s=o("entry_flow/conv_in"),c=a("entry_flow/reduction_block_0"),m=a("entry_flow/reduction_block_1"),p={conv_in:s,reduction_block_0:c,reduction_block_1:m},f={};X(e,0,1).forEach(d=>{f[`main_block_${d}`]=i(`middle_flow/main_block_${d}`)});const l=a("exit_flow/reduction_block"),u=n("exit_flow/separable_conv"),v={reduction_block:l,separable_conv:u};return M(t,r),{params:{entry_flow:p,middle_flow:f,exit_flow:v},paramMappings:r}}import{add as gr,conv2d as Pa,maxPool as _a,relu as wt,scalar as Da,tidy as Ea}from"@tensorflow/tfjs/dist/tf.es2017.js";function ro(t,e,r){return gr(Pa(t,e.filters,r,"same"),e.bias)}function br(t,e,r=!0){let o=r?wt(t):t;return o=L(o,e.separable_conv0,[1,1]),o=L(wt(o),e.separable_conv1,[1,1]),o=_a(o,[3,3],[2,2],"same"),o=gr(o,ro(t,e.expansion_conv,[2,2])),o}function Ma(t,e){let r=L(wt(t),e.separable_conv0,[1,1]);return r=L(wt(r),e.separable_conv1,[1,1]),r=L(wt(r),e.separable_conv2,[1,1]),r=gr(r,t),r}class oo extends E{constructor(t){super("TinyXception");this._numMainBlocks=t}forwardInput(t){const{params:e}=this;if(!e)throw new Error("TinyXception - load model before inference");return Ea(()=>{const r=t.toBatchTensor(112,!0),o=[122.782,117.001,104.298],n=G(r,o).div(Da(256));let a=wt(ro(n,e.entry_flow.conv_in,[2,2]));return a=br(a,e.entry_flow.reduction_block_0,!1),a=br(a,e.entry_flow.reduction_block_1),X(this._numMainBlocks,0,1).forEach(i=>{a=Ma(a,e.middle_flow[`main_block_${i}`])}),a=br(a,e.exit_flow.reduction_block),a=wt(L(a,e.exit_flow.separable_conv,[1,1])),a})}async forward(t){return this.forwardInput(await w(t))}getDefaultModelName(){return"tiny_xception_model"}extractParamsFromWeigthMap(t){return eo(t,this._numMainBlocks)}extractParams(t){return to(t,this._numMainBlocks)}}function no(t){const e=[],{extractWeights:r,getRemainingWeights:o}=C(t),n=Te(r,e),a=n(512,1,"fc/age"),i=n(512,2,"fc/gender");if(o().length!==0)throw new Error(`weights remaing after extract: ${o().length}`);return{paramMappings:e,params:{fc:{age:a,gender:i}}}}function ao(t){const e=[],r=A(t,e);function o(a){const i=r(`${a}/weights`,2),s=r(`${a}/bias`,1);return{weights:i,bias:s}}const n={fc:{age:o("fc/age"),gender:o("fc/gender")}};return M(t,e),{params:n,paramMappings:e}}var Q;(function(t){t.FEMALE="female",t.MALE="male"})(Q||(Q={}));import{avgPool as Ca,softmax as ka,tidy as so,unstack as io}from"@tensorflow/tfjs/dist/tf.es2017.js";class xr extends E{constructor(t=new oo(2)){super("AgeGenderNet");this._faceFeatureExtractor=t}get faceFeatureExtractor(){return this._faceFeatureExtractor}runNet(t){const{params:e}=this;if(!e)throw new Error(`${this._name} - load model before inference`);return so(()=>{const r=t instanceof st?this.faceFeatureExtractor.forwardInput(t):t,o=Ca(r,[7,7],[2,2],"valid").as2D(r.shape[0],-1),n=te(o,e.fc.age).as1D(),a=te(o,e.fc.gender);return{age:n,gender:a}})}forwardInput(t){return so(()=>{const{age:e,gender:r}=this.runNet(t);return{age:e,gender:ka(r)}})}async forward(t){return this.forwardInput(await w(t))}async predictAgeAndGender(t){const e=await w(t),r=await this.forwardInput(e),o=io(r.age),n=io(r.gender),a=o.map((s,c)=>({ageTensor:s,genderTensor:n[c]})),i=await Promise.all(a.map(async({ageTensor:s,genderTensor:c})=>{const m=(await s.data())[0],p=(await c.data())[0],f=p>.5,l=f?Q.MALE:Q.FEMALE,u=f?p:1-p;return s.dispose(),c.dispose(),{age:m,gender:l,genderProbability:u}}));return r.age.dispose(),r.gender.dispose(),e.isBatchInput?i:i[0]}getDefaultModelName(){return"age_gender_model"}dispose(t=!0){this.faceFeatureExtractor.dispose(t),super.dispose(t)}loadClassifierParams(t){const{params:e,paramMappings:r}=this.extractClassifierParams(t);this._params=e,this._paramMappings=r}extractClassifierParams(t){return no(t)}extractParamsFromWeigthMap(t){const{featureExtractorMap:e,classifierMap:r}=De(t);return this.faceFeatureExtractor.loadFromWeightMap(e),ao(r)}extractParams(t){const e=512*1+1+(512*2+2),r=t.slice(0,t.length-e),o=t.slice(t.length-e);return this.faceFeatureExtractor.extractWeights(r),this.extractClassifierParams(o)}}import{fill as vr,stack as yr,tidy as Tr,unstack as Na}from"@tensorflow/tfjs/dist/tf.es2017.js";class Ce extends Ee{postProcess(t,e,r){const o=r.map(({width:a,height:i})=>{const s=e/Math.max(i,a);return{width:a*s,height:i*s}}),n=o.length;return Tr(()=>{const a=(p,f)=>yr([vr([68],p),vr([68],f)],1).as2D(1,136).as1D(),i=(p,f)=>{const{width:l,height:u}=o[p];return f(l,u)?Math.abs(l-u)/2:0},s=p=>i(p,(f,l)=>f<l),c=p=>i(p,(f,l)=>l<f),m=t.mul(vr([n,136],e)).sub(yr(Array.from(Array(n),(p,f)=>a(s(f),c(f))))).div(yr(Array.from(Array(n),(p,f)=>a(o[f].width,o[f].height))));return m})}forwardInput(t){return Tr(()=>{const e=this.runNet(t);return this.postProcess(e,t.inputSize,t.inputDimensions.map(([r,o])=>({height:r,width:o})))})}async forward(t){return this.forwardInput(await w(t))}async detectLandmarks(t){const e=await w(t),r=Tr(()=>Na(this.forwardInput(e))),o=await Promise.all(r.map(async(n,a)=>{const i=Array.from(await n.data()),s=i.filter((m,p)=>le(p)),c=i.filter((m,p)=>!le(p));return new qt(Array(68).fill(0).map((m,p)=>new g(s[p],c[p])),{height:e.getInputHeight(a),width:e.getInputWidth(a)})}));return r.forEach(n=>n.dispose()),e.isBatchInput?o:o[0]}getClassifierChannelsOut(){return 136}}class ee extends Ce{constructor(t=new _e){super("FaceLandmark68Net",t)}getDefaultModelName(){return"face_landmark_68_model"}getClassifierChannelsIn(){return 256}}function co(t){const e=[],{extractDenseBlock3Params:r}=Pe(t,e),o={dense0:r("dense0",!0),dense1:r("dense1"),dense2:r("dense2")};return M(t,e),{params:o,paramMappings:e}}function mo(t){const e=[],{extractWeights:r,getRemainingWeights:o}=C(t),{extractDenseBlock3Params:n}=Fe(r,e),a=n(3,32,"dense0",!0),i=n(32,64,"dense1"),s=n(64,128,"dense2");if(o().length!==0)throw new Error(`weights remaing after extract: ${o().length}`);return{paramMappings:e,params:{dense0:a,dense1:i,dense2:s}}}import{avgPool as La,scalar as Ia,tidy as Sa}from"@tensorflow/tfjs/dist/tf.es2017.js";class po extends E{constructor(){super("TinyFaceFeatureExtractor")}forwardInput(t){const{params:e}=this;if(!e)throw new Error("TinyFaceFeatureExtractor - load model before inference");return Sa(()=>{const r=t.toBatchTensor(112,!0),o=[122.782,117.001,104.298],n=G(r,o).div(Ia(255));let a=ye(n,e.dense0,!0);return a=ye(a,e.dense1),a=ye(a,e.dense2),a=La(a,[14,14],[2,2],"valid"),a})}async forward(t){return this.forwardInput(await w(t))}getDefaultModelName(){return"face_feature_extractor_tiny_model"}extractParamsFromWeigthMap(t){return co(t)}extractParams(t){return mo(t)}}class Fr extends Ce{constructor(t=new po){super("FaceLandmark68TinyNet",t)}getDefaultModelName(){return"face_landmark_68_tiny_model"}getClassifierChannelsIn(){return 128}}class Aa extends ee{}import{add as Wa,mul as Ba}from"@tensorflow/tfjs/dist/tf.es2017.js";function fo(t,e){return Wa(Ba(t,e.weights),e.biases)}import{add as Ra,conv2d as Oa,relu as ja}from"@tensorflow/tfjs/dist/tf.es2017.js";function wr(t,e,r,o,n="same"){const{filters:a,bias:i}=e.conv;let s=Oa(t,a,r,n);return s=Ra(s,i),s=fo(s,e.scale),o?ja(s):s}function lo(t,e){return wr(t,e,[1,1],!0)}function Pr(t,e){return wr(t,e,[1,1],!1)}function ke(t,e){return wr(t,e,[2,2],!0,"valid")}import{tensor1d as _r,tensor2d as $a,tensor4d as Ha,tidy as uo,transpose as ho}from"@tensorflow/tfjs/dist/tf.es2017.js";function Ga(t,e){function r(s,c,m){const p=t(s),f=p.length/(c*m*m);if(Ye(f))throw new Error(`depth has to be an integer: ${f}, weights.length: ${p.length}, numFilters: ${c}, filterSize: ${m}`);return uo(()=>ho(Ha(p,[c,f,m,m]),[2,3,1,0]))}function o(s,c,m,p){const f=r(s,c,m),l=_r(t(c));return e.push({paramPath:`${p}/filters`},{paramPath:`${p}/bias`}),{filters:f,bias:l}}function n(s,c){const m=_r(t(s)),p=_r(t(s));return e.push({paramPath:`${c}/weights`},{paramPath:`${c}/biases`}),{weights:m,biases:p}}function a(s,c,m,p){const f=o(s,c,m,`${p}/conv`),l=n(c,`${p}/scale`);return{conv:f,scale:l}}function i(s,c,m,p,f=!1){const l=a((f?.5:1)*s,c,m,`${p}/conv1`),u=a(s,c,m,`${p}/conv2`);return{conv1:l,conv2:u}}return{extractConvLayerParams:a,extractResidualLayerParams:i}}function go(t){const{extractWeights:e,getRemainingWeights:r}=C(t),o=[],{extractConvLayerParams:n,extractResidualLayerParams:a}=Ga(e,o),i=n(4704,32,7,"conv32_down"),s=a(9216,32,3,"conv32_1"),c=a(9216,32,3,"conv32_2"),m=a(9216,32,3,"conv32_3"),p=a(36864,64,3,"conv64_down",!0),f=a(36864,64,3,"conv64_1"),l=a(36864,64,3,"conv64_2"),u=a(36864,64,3,"conv64_3"),v=a(147456,128,3,"conv128_down",!0),d=a(147456,128,3,"conv128_1"),b=a(147456,128,3,"conv128_2"),x=a(589824,256,3,"conv256_down",!0),h=a(589824,256,3,"conv256_1"),P=a(589824,256,3,"conv256_2"),k=a(589824,256,3,"conv256_down_out"),I=uo(()=>ho($a(e(256*128),[128,256]),[1,0]));if(o.push({paramPath:"fc"}),r().length!==0)throw new Error(`weights remaing after extract: ${r().length}`);const B={conv32_down:i,conv32_1:s,conv32_2:c,conv32_3:m,conv64_down:p,conv64_1:f,conv64_2:l,conv64_3:u,conv128_down:v,conv128_1:d,conv128_2:b,conv256_down:x,conv256_1:h,conv256_2:P,conv256_down_out:k,fc:I};return{params:B,paramMappings:o}}function za(t,e){const r=A(t,e);function o(i){const s=r(`${i}/scale/weights`,1),c=r(`${i}/scale/biases`,1);return{weights:s,biases:c}}function n(i){const s=r(`${i}/conv/filters`,4),c=r(`${i}/conv/bias`,1),m=o(i);return{conv:{filters:s,bias:c},scale:m}}function a(i){return{conv1:n(`${i}/conv1`),conv2:n(`${i}/conv2`)}}return{extractConvLayerParams:n,extractResidualLayerParams:a}}function bo(t){const e=[],{extractConvLayerParams:r,extractResidualLayerParams:o}=za(t,e),n=r("conv32_down"),a=o("conv32_1"),i=o("conv32_2"),s=o("conv32_3"),c=o("conv64_down"),m=o("conv64_1"),p=o("conv64_2"),f=o("conv64_3"),l=o("conv128_down"),u=o("conv128_1"),v=o("conv128_2"),d=o("conv256_down"),b=o("conv256_1"),x=o("conv256_2"),h=o("conv256_down_out"),P=t.fc;if(e.push({originalPath:"fc",paramPath:"fc"}),!ze(P))throw new Error(`expected weightMap[fc] to be a Tensor2D, instead have ${P}`);const k={conv32_down:n,conv32_1:a,conv32_2:i,conv32_3:s,conv64_down:c,conv64_1:m,conv64_2:p,conv64_3:f,conv128_down:l,conv128_1:u,conv128_2:v,conv256_down:d,conv256_1:b,conv256_2:x,conv256_down_out:h,fc:P};return M(t,e),{params:k,paramMappings:e}}import{add as xo,avgPool as Ya,concat as Dr,relu as vo,zeros as Er}from"@tensorflow/tfjs/dist/tf.es2017.js";function Y(t,e){let r=lo(t,e.conv1);return r=Pr(r,e.conv2),r=xo(r,t),r=vo(r),r}function re(t,e){let r=ke(t,e.conv1);r=Pr(r,e.conv2);let o=Ya(t,2,2,"valid");const n=Er(o.shape),a=o.shape[3]!==r.shape[3],i=o.shape[1]!==r.shape[1]||o.shape[2]!==r.shape[2];if(i){const s=[...r.shape];s[1]=1;const c=Er(s);r=Dr([r,c],1);const m=[...r.shape];m[2]=1;const p=Er(m);r=Dr([r,p],2)}return o=a?Dr([o,n],3):o,r=xo(o,r),r=vo(r),r}import{cast as Va,matMul as Ua,maxPool as Xa,scalar as Ja,tidy as yo,unstack as qa}from"@tensorflow/tfjs/dist/tf.es2017.js";class oe extends E{constructor(){super("FaceRecognitionNet")}forwardInput(t){const{params:e}=this;if(!e)throw new Error("FaceRecognitionNet - load model before inference");return yo(()=>{const r=Va(t.toBatchTensor(150,!0),"float32"),o=[122.782,117.001,104.298],n=G(r,o).div(Ja(256));let a=ke(n,e.conv32_down);a=Xa(a,3,2,"valid"),a=Y(a,e.conv32_1),a=Y(a,e.conv32_2),a=Y(a,e.conv32_3),a=re(a,e.conv64_down),a=Y(a,e.conv64_1),a=Y(a,e.conv64_2),a=Y(a,e.conv64_3),a=re(a,e.conv128_down),a=Y(a,e.conv128_1),a=Y(a,e.conv128_2),a=re(a,e.conv256_down),a=Y(a,e.conv256_1),a=Y(a,e.conv256_2),a=re(a,e.conv256_down_out);const i=a.mean([1,2]),s=Ua(i,e.fc);return s})}async forward(t){return this.forwardInput(await w(t))}async computeFaceDescriptor(t){const e=await w(t),r=yo(()=>qa(this.forwardInput(e))),o=await Promise.all(r.map(n=>n.data()));return r.forEach(n=>n.dispose()),e.isBatchInput?o:o[0]}getDefaultModelName(){return"face_recognition_model"}extractParamsFromWeigthMap(t){return bo(t)}extractParams(t){return go(t)}}function Za(t){const e=new oe;return e.extractWeights(t),e}function Ne(t,e){const r={descriptor:e};return Object.assign({},t,r)}function Ka(t){return typeof t.age=="number"}function Le(t,e){const r={age:e};return Object.assign({},t,r)}function Qa(t){return(t.gender===Q.MALE||t.gender===Q.FEMALE)&&Mt(t.genderProbability)}function Ie(t,e,r){const o={gender:e,genderProbability:r};return Object.assign({},t,o)}import{tensor1d as ne,tensor3d as ts,tensor4d as To}from"@tensorflow/tfjs/dist/tf.es2017.js";function es(t,e){function r(c,m){const p=To(t(3*3*c),[3,3,c,1]),f=ne(t(c)),l=ne(t(c)),u=ne(t(c)),v=ne(t(c));return e.push({paramPath:`${m}/filters`},{paramPath:`${m}/batch_norm_scale`},{paramPath:`${m}/batch_norm_offset`},{paramPath:`${m}/batch_norm_mean`},{paramPath:`${m}/batch_norm_variance`}),{filters:p,batch_norm_scale:f,batch_norm_offset:l,batch_norm_mean:u,batch_norm_variance:v}}function o(c,m,p,f,l){const u=To(t(c*m*p*p),[p,p,c,m]),v=ne(t(m));return e.push({paramPath:`${f}/filters`},{paramPath:`${f}/${l?"batch_norm_offset":"bias"}`}),{filters:u,bias:v}}function n(c,m,p,f){const{filters:l,bias:u}=o(c,m,p,f,!0);return{filters:l,batch_norm_offset:u}}function a(c,m,p){const f=r(c,`${p}/depthwise_conv`),l=n(c,m,1,`${p}/pointwise_conv`);return{depthwise_conv:f,pointwise_conv:l}}function i(){const c=n(3,32,3,"mobilenetv1/conv_0"),m=a(32,64,"mobilenetv1/conv_1"),p=a(64,128,"mobilenetv1/conv_2"),f=a(128,128,"mobilenetv1/conv_3"),l=a(128,256,"mobilenetv1/conv_4"),u=a(256,256,"mobilenetv1/conv_5"),v=a(256,512,"mobilenetv1/conv_6"),d=a(512,512,"mobilenetv1/conv_7"),b=a(512,512,"mobilenetv1/conv_8"),x=a(512,512,"mobilenetv1/conv_9"),h=a(512,512,"mobilenetv1/conv_10"),P=a(512,512,"mobilenetv1/conv_11"),k=a(512,1024,"mobilenetv1/conv_12"),I=a(1024,1024,"mobilenetv1/conv_13");return{conv_0:c,conv_1:m,conv_2:p,conv_3:f,conv_4:l,conv_5:u,conv_6:v,conv_7:d,conv_8:b,conv_9:x,conv_10:h,conv_11:P,conv_12:k,conv_13:I}}function s(){const c=n(1024,256,1,"prediction_layer/conv_0"),m=n(256,512,3,"prediction_layer/conv_1"),p=n(512,128,1,"prediction_layer/conv_2"),f=n(128,256,3,"prediction_layer/conv_3"),l=n(256,128,1,"prediction_layer/conv_4"),u=n(128,256,3,"prediction_layer/conv_5"),v=n(256,64,1,"prediction_layer/conv_6"),d=n(64,128,3,"prediction_layer/conv_7"),b=o(512,12,1,"prediction_layer/box_predictor_0/box_encoding_predictor"),x=o(512,9,1,"prediction_layer/box_predictor_0/class_predictor"),h=o(1024,24,1,"prediction_layer/box_predictor_1/box_encoding_predictor"),P=o(1024,18,1,"prediction_layer/box_predictor_1/class_predictor"),k=o(512,24,1,"prediction_layer/box_predictor_2/box_encoding_predictor"),I=o(512,18,1,"prediction_layer/box_predictor_2/class_predictor"),B=o(256,24,1,"prediction_layer/box_predictor_3/box_encoding_predictor"),R=o(256,18,1,"prediction_layer/box_predictor_3/class_predictor"),ot=o(256,24,1,"prediction_layer/box_predictor_4/box_encoding_predictor"),nt=o(256,18,1,"prediction_layer/box_predictor_4/class_predictor"),at=o(128,24,1,"prediction_layer/box_predictor_5/box_encoding_predictor"),mt=o(128,18,1,"prediction_layer/box_predictor_5/class_predictor"),pt={box_encoding_predictor:b,class_predictor:x},nn={box_encoding_predictor:h,class_predictor:P},an={box_encoding_predictor:k,class_predictor:I},sn={box_encoding_predictor:B,class_predictor:R},cn={box_encoding_predictor:ot,class_predictor:nt},mn={box_encoding_predictor:at,class_predictor:mt};return{conv_0:c,conv_1:m,conv_2:p,conv_3:f,conv_4:l,conv_5:u,conv_6:v,conv_7:d,box_predictor_0:pt,box_predictor_1:nn,box_predictor_2:an,box_predictor_3:sn,box_predictor_4:cn,box_predictor_5:mn}}return{extractMobilenetV1Params:i,extractPredictionLayerParams:s}}function Fo(t){const e=[],{extractWeights:r,getRemainingWeights:o}=C(t),{extractMobilenetV1Params:n,extractPredictionLayerParams:a}=es(r,e),i=n(),s=a(),c=ts(r(5118*4),[1,5118,4]),m={extra_dim:c};if(e.push({paramPath:"output_layer/extra_dim"}),o().length!==0)throw new Error(`weights remaing after extract: ${o().length}`);return{params:{mobilenetv1:i,prediction_layer:s,output_layer:m},paramMappings:e}}function rs(t,e){const r=A(t,e);function o(m,p,f){const l=r(`${m}/Conv2d_${p}_pointwise/weights`,4,`${f}/filters`),u=r(`${m}/Conv2d_${p}_pointwise/convolution_bn_offset`,1,`${f}/batch_norm_offset`);return{filters:l,batch_norm_offset:u}}function n(m){const p=`mobilenetv1/conv_${m}`,f=`MobilenetV1/Conv2d_${m}_depthwise`,l=`${p}/depthwise_conv`,u=`${p}/pointwise_conv`,v=r(`${f}/depthwise_weights`,4,`${l}/filters`),d=r(`${f}/BatchNorm/gamma`,1,`${l}/batch_norm_scale`),b=r(`${f}/BatchNorm/beta`,1,`${l}/batch_norm_offset`),x=r(`${f}/BatchNorm/moving_mean`,1,`${l}/batch_norm_mean`),h=r(`${f}/BatchNorm/moving_variance`,1,`${l}/batch_norm_variance`);return{depthwise_conv:{filters:v,batch_norm_scale:d,batch_norm_offset:b,batch_norm_mean:x,batch_norm_variance:h},pointwise_conv:o("MobilenetV1",m,u)}}function a(){return{conv_0:o("MobilenetV1",0,"mobilenetv1/conv_0"),conv_1:n(1),conv_2:n(2),conv_3:n(3),conv_4:n(4),conv_5:n(5),conv_6:n(6),conv_7:n(7),conv_8:n(8),conv_9:n(9),conv_10:n(10),conv_11:n(11),conv_12:n(12),conv_13:n(13)}}function i(m,p){const f=r(`${m}/weights`,4,`${p}/filters`),l=r(`${m}/biases`,1,`${p}/bias`);return{filters:f,bias:l}}function s(m){const p=i(`Prediction/BoxPredictor_${m}/BoxEncodingPredictor`,`prediction_layer/box_predictor_${m}/box_encoding_predictor`),f=i(`Prediction/BoxPredictor_${m}/ClassPredictor`,`prediction_layer/box_predictor_${m}/class_predictor`);return{box_encoding_predictor:p,class_predictor:f}}function c(){return{conv_0:o("Prediction",0,"prediction_layer/conv_0"),conv_1:o("Prediction",1,"prediction_layer/conv_1"),conv_2:o("Prediction",2,"prediction_layer/conv_2"),conv_3:o("Prediction",3,"prediction_layer/conv_3"),conv_4:o("Prediction",4,"prediction_layer/conv_4"),conv_5:o("Prediction",5,"prediction_layer/conv_5"),conv_6:o("Prediction",6,"prediction_layer/conv_6"),conv_7:o("Prediction",7,"prediction_layer/conv_7"),box_predictor_0:s(0),box_predictor_1:s(1),box_predictor_2:s(2),box_predictor_3:s(3),box_predictor_4:s(4),box_predictor_5:s(5)}}return{extractMobilenetV1Params:a,extractPredictionLayerParams:c}}function wo(t){const e=[],{extractMobilenetV1Params:r,extractPredictionLayerParams:o}=rs(t,e),n=t["Output/extra_dim"];if(e.push({originalPath:"Output/extra_dim",paramPath:"output_layer/extra_dim"}),!K(n))throw new Error(`expected weightMap['Output/extra_dim'] to be a Tensor3D, instead have ${n}`);const a={mobilenetv1:r(),prediction_layer:o(),output_layer:{extra_dim:n}};return M(t,e),{params:a,paramMappings:e}}import{add as os,clipByValue as ns,conv2d as as,tidy as ss}from"@tensorflow/tfjs/dist/tf.es2017.js";function j(t,e,r){return ss(()=>{let o=as(t,e.filters,r,"same");return o=os(o,e.batch_norm_offset),ns(o,0,6)})}import{batchNorm as is,clipByValue as cs,depthwiseConv2d as ms,tidy as Po}from"@tensorflow/tfjs/dist/tf.es2017.js";const ps=.0010000000474974513;function fs(t,e,r){return Po(()=>{let o=ms(t,e.filters,r,"same");return o=is(o,e.batch_norm_mean,e.batch_norm_variance,e.batch_norm_offset,e.batch_norm_scale,ps),cs(o,0,6)})}function ls(t){return[2,4,6,12].some(e=>e===t)?[2,2]:[1,1]}function _o(t,e){return Po(()=>{let r,o=j(t,e.conv_0,[2,2]);const n=[e.conv_1,e.conv_2,e.conv_3,e.conv_4,e.conv_5,e.conv_6,e.conv_7,e.conv_8,e.conv_9,e.conv_10,e.conv_11,e.conv_12,e.conv_13];if(n.forEach((a,i)=>{const s=i+1,c=ls(s);o=fs(o,a.depthwise_conv,c),o=j(o,a.pointwise_conv,[1,1]),s===11&&(r=o)}),r===null)throw new Error("mobileNetV1 - output of conv layer 11 is null");return{out:o,conv11:r}})}function Do(t,e,r,o,n){const a=t.shape[0],i=Math.min(r,a),s=e.map((p,f)=>({score:p,boxIndex:f})).filter(p=>p.score>n).sort((p,f)=>f.score-p.score),c=p=>p<=o?1:0,m=[];return s.forEach(p=>{if(m.length>=i)return;const f=p.score;for(let l=m.length-1;l>=0;--l){const u=us(t,p.boxIndex,m[l]);if(u===0)continue;if(p.score*=c(u),p.score<=n)break}f===p.score&&m.push(p.boxIndex)}),m}function us(t,e,r){const o=t.arraySync(),n=Math.min(o[e][0],o[e][2]),a=Math.min(o[e][1],o[e][3]),i=Math.max(o[e][0],o[e][2]),s=Math.max(o[e][1],o[e][3]),c=Math.min(o[r][0],o[r][2]),m=Math.min(o[r][1],o[r][3]),p=Math.max(o[r][0],o[r][2]),f=Math.max(o[r][1],o[r][3]),l=(i-n)*(s-a),u=(p-c)*(f-m);if(l<=0||u<=0)return 0;const v=Math.max(n,c),d=Math.max(a,m),b=Math.min(i,p),x=Math.min(s,f),h=Math.max(b-v,0)*Math.max(x-d,0);return h/(l+u-h)}import{add as Rt,div as it,exp as Eo,mul as Se,reshape as Ae,scalar as ct,sigmoid as ds,slice as Mo,stack as hs,sub as We,tidy as gs,tile as bs,transpose as Mr,unstack as Be}from"@tensorflow/tfjs/dist/tf.es2017.js";function xs(t){const e=Be(Mr(t,[1,0])),r=[We(e[2],e[0]),We(e[3],e[1])],o=[Rt(e[0],it(r[0],ct(2))),Rt(e[1],it(r[1],ct(2)))];return{sizes:r,centers:o}}function vs(t,e){const{sizes:r,centers:o}=xs(t),n=Be(Mr(e,[1,0])),a=it(Se(Eo(it(n[2],ct(5))),r[0]),ct(2)),i=Rt(Se(it(n[0],ct(10)),r[0]),o[0]),s=it(Se(Eo(it(n[3],ct(5))),r[1]),ct(2)),c=Rt(Se(it(n[1],ct(10)),r[1]),o[1]);return Mr(hs([We(i,a),We(c,s),Rt(i,a),Rt(c,s)]),[1,0])}function Co(t,e,r){return gs(()=>{const o=t.shape[0];let n=vs(Ae(bs(r.extra_dim,[o,1,1]),[-1,4]),Ae(t,[-1,4]));n=Ae(n,[o,n.shape[0]/o,4]);const a=ds(Mo(e,[0,0,1],[-1,-1,-1]));let i=Mo(a,[0,0,0],[-1,-1,1]);i=Ae(i,[o,i.shape[1]]);const s=Be(n),c=Be(i);return{boxes:s,scores:c}})}import{reshape as ko,tidy as ys}from"@tensorflow/tfjs/dist/tf.es2017.js";function Pt(t,e){return ys(()=>{const r=t.shape[0],o=ko(yt(t,e.box_encoding_predictor),[r,-1,1,4]),n=ko(yt(t,e.class_predictor),[r,-1,3]);return{boxPredictionEncoding:o,classPrediction:n}})}import{concat as No,tidy as Ts}from"@tensorflow/tfjs/dist/tf.es2017.js";function Lo(t,e,r){return Ts(()=>{const o=j(t,r.conv_0,[1,1]),n=j(o,r.conv_1,[2,2]),a=j(n,r.conv_2,[1,1]),i=j(a,r.conv_3,[2,2]),s=j(i,r.conv_4,[1,1]),c=j(s,r.conv_5,[2,2]),m=j(c,r.conv_6,[1,1]),p=j(m,r.conv_7,[2,2]),f=Pt(e,r.box_predictor_0),l=Pt(t,r.box_predictor_1),u=Pt(n,r.box_predictor_2),v=Pt(i,r.box_predictor_3),d=Pt(c,r.box_predictor_4),b=Pt(p,r.box_predictor_5),x=No([f.boxPredictionEncoding,l.boxPredictionEncoding,u.boxPredictionEncoding,v.boxPredictionEncoding,d.boxPredictionEncoding,b.boxPredictionEncoding],1),h=No([f.classPrediction,l.classPrediction,u.classPrediction,v.classPrediction,d.classPrediction,b.classPrediction],1);return{boxPredictions:x,classPredictions:h}})}class V{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}}import{cast as Fs,mul as ws,scalar as Io,sub as Ps,tidy as _s}from"@tensorflow/tfjs/dist/tf.es2017.js";class Ot extends E{constructor(){super("SsdMobilenetv1")}forwardInput(t){const{params:e}=this;if(!e)throw new Error("SsdMobilenetv1 - load model before inference");return _s(()=>{const r=Fs(t.toBatchTensor(512,!1),"float32"),o=Ps(ws(r,Io(.007843137718737125)),Io(1)),n=_o(o,e.mobilenetv1),{boxPredictions:a,classPredictions:i}=Lo(n.out,n.conv11,e.prediction_layer);return Co(a,i,e.output_layer)})}async forward(t){return this.forwardInput(await w(t))}async locateFaces(t,e={}){const{maxResults:r,minConfidence:o}=new V(e),n=await w(t),{boxes:a,scores:i}=this.forwardInput(n),s=a[0],c=i[0];for(let h=1;h<a.length;h++)a[h].dispose(),i[h].dispose();const m=Array.from(await c.data()),p=.5,f=Do(s,m,r,p,o),l=n.getReshapedInputDimensions(0),u=n.inputSize,v=u/l.width,d=u/l.height,b=s.arraySync(),x=f.map(h=>{const[P,k]=[Math.max(0,b[h][0]),Math.min(1,b[h][2])].map(R=>R*d),[I,B]=[Math.max(0,b[h][1]),Math.min(1,b[h][3])].map(R=>R*v);return new _(m[h],new Jt(I,P,B-I,k-P),{height:n.getInputHeight(0),width:n.getInputWidth(0)})});return s.dispose(),c.dispose(),x}getDefaultModelName(){return"ssd_mobilenetv1_model"}extractParamsFromWeigthMap(t){return wo(t)}extractParams(t){return Fo(t)}}function So(t){const e=new Ot;return e.extractWeights(t),e}function Ds(t){return So(t)}class Es extends Ot{}const Ao=.4,Wo=[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)],Bo=[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)],Ro=[117.001,114.697,97.404],Oo="tiny_yolov2_model",jo="tiny_yolov2_separable_conv_model";const Re=t=>typeof t=="number";function Cr(t){if(!t)throw new Error(`invalid config: ${t}`);if(typeof t.withSeparableConvs!="boolean")throw new Error(`config.withSeparableConvs has to be a boolean, have: ${t.withSeparableConvs}`);if(!Re(t.iouThreshold)||t.iouThreshold<0||t.iouThreshold>1)throw new Error(`config.iouThreshold has to be a number between [0, 1], have: ${t.iouThreshold}`);if(!Array.isArray(t.classes)||!t.classes.length||!t.classes.every(e=>typeof e=="string"))throw new Error(`config.classes has to be an array class names: string[], have: ${JSON.stringify(t.classes)}`);if(!Array.isArray(t.anchors)||!t.anchors.length||!t.anchors.map(e=>e||{}).every(e=>Re(e.x)&&Re(e.y)))throw new Error(`config.anchors has to be an array of { x: number, y: number }, have: ${JSON.stringify(t.anchors)}`);if(t.meanRgb&&(!Array.isArray(t.meanRgb)||t.meanRgb.length!==3||!t.meanRgb.every(Re)))throw new Error(`config.meanRgb has to be an array of shape [number, number, number], have: ${JSON.stringify(t.meanRgb)}`)}import{add as Ms,mul as Cs,relu as ks,scalar as Ns,sub as Ls,tidy as Is}from"@tensorflow/tfjs/dist/tf.es2017.js";function jt(t){return Is(()=>{const e=Cs(t,Ns(.10000000149011612));return Ms(ks(Ls(t,e)),e)})}import{add as Ss,conv2d as As,mul as Ws,pad as Bs,sub as Rs,tidy as Os}from"@tensorflow/tfjs/dist/tf.es2017.js";function tt(t,e){return Os(()=>{let r=Bs(t,[[0,0],[1,1],[1,1],[0,0]]);return r=As(r,e.conv.filters,[1,1],"valid"),r=Rs(r,e.bn.sub),r=Ws(r,e.bn.truediv),r=Ss(r,e.conv.bias),jt(r)})}import{add as js,pad as $s,separableConv2d as Hs,tidy as Gs}from"@tensorflow/tfjs/dist/tf.es2017.js";function et(t,e){return Gs(()=>{let r=$s(t,[[0,0],[1,1],[1,1],[0,0]]);return r=Hs(r,e.depthwise_filter,e.pointwise_filter,[1,1],"valid"),r=js(r,e.bias),jt(r)})}import{tensor1d as $o}from"@tensorflow/tfjs/dist/tf.es2017.js";function zs(t,e){const r=St(t,e);function o(i,s){const c=$o(t(i)),m=$o(t(i));return e.push({paramPath:`${s}/sub`},{paramPath:`${s}/truediv`}),{sub:c,truediv:m}}function n(i,s,c){const m=r(i,s,3,`${c}/conv`),p=o(s,`${c}/bn`);return{conv:m,bn:p}}const a=At(t,e);return{extractConvParams:r,extractConvWithBatchNormParams:n,extractSeparableConvParams:a}}function Ho(t,e,r,o){const{extractWeights:n,getRemainingWeights:a}=C(t),i=[],{extractConvParams:s,extractConvWithBatchNormParams:c,extractSeparableConvParams:m}=zs(n,i);let p;if(e.withSeparableConvs){const[f,l,u,v,d,b,x,h,P]=o,k=e.isFirstLayerConv2d?s(f,l,3,"conv0"):m(f,l,"conv0"),I=m(l,u,"conv1"),B=m(u,v,"conv2"),R=m(v,d,"conv3"),ot=m(d,b,"conv4"),nt=m(b,x,"conv5"),at=h?m(x,h,"conv6"):void 0,mt=P?m(h,P,"conv7"):void 0,pt=s(P||h||x,5*r,1,"conv8");p={conv0:k,conv1:I,conv2:B,conv3:R,conv4:ot,conv5:nt,conv6:at,conv7:mt,conv8:pt}}else{const[f,l,u,v,d,b,x,h,P]=o,k=c(f,l,"conv0"),I=c(l,u,"conv1"),B=c(u,v,"conv2"),R=c(v,d,"conv3"),ot=c(d,b,"conv4"),nt=c(b,x,"conv5"),at=c(x,h,"conv6"),mt=c(h,P,"conv7"),pt=s(P,5*r,1,"conv8");p={conv0:k,conv1:I,conv2:B,conv3:R,conv4:ot,conv5:nt,conv6:at,conv7:mt,conv8:pt}}if(a().length!==0)throw new Error(`weights remaing after extract: ${a().length}`);return{params:p,paramMappings:i}}function Ys(t,e){const r=A(t,e);function o(s){const c=r(`${s}/sub`,1),m=r(`${s}/truediv`,1);return{sub:c,truediv:m}}function n(s){const c=r(`${s}/filters`,4),m=r(`${s}/bias`,1);return{filters:c,bias:m}}function a(s){const c=n(`${s}/conv`),m=o(`${s}/bn`);return{conv:c,bn:m}}const i=Wt(r);return{extractConvParams:n,extractConvWithBatchNormParams:a,extractSeparableConvParams:i}}function Go(t,e){const r=[],{extractConvParams:o,extractConvWithBatchNormParams:n,extractSeparableConvParams:a}=Ys(t,r);let i;if(e.withSeparableConvs){const s=e.filterSizes&&e.filterSizes.length||9;i={conv0:e.isFirstLayerConv2d?o("conv0"):a("conv0"),conv1:a("conv1"),conv2:a("conv2"),conv3:a("conv3"),conv4:a("conv4"),conv5:a("conv5"),conv6:s>7?a("conv6"):void 0,conv7:s>8?a("conv7"):void 0,conv8:o("conv8")}}else i={conv0:n("conv0"),conv1:n("conv1"),conv2:n("conv2"),conv3:n("conv3"),conv4:n("conv4"),conv5:n("conv5"),conv6:n("conv6"),conv7:n("conv7"),conv8:o("conv8")};return M(t,r),{params:i,paramMappings:r}}var kr;(function(t){t[t.XS=224]="XS",t[t.SM=320]="SM",t[t.MD=416]="MD",t[t.LG=608]="LG"})(kr||(kr={}));class rt{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}}import{cast as Vs,maxPool as $,scalar as zo,softmax as Us,tidy as Nr,unstack as Xs}from"@tensorflow/tfjs/dist/tf.es2017.js";class $t extends E{constructor(t){super("TinyYolov2");Cr(t),this._config=t}get config(){return this._config}get withClassScores(){return this.config.withClassScores||this.config.classes.length>1}get boxEncodingSize(){return 5+(this.withClassScores?this.config.classes.length:0)}runTinyYolov2(t,e){let r=tt(t,e.conv0);return r=$(r,[2,2],[2,2],"same"),r=tt(r,e.conv1),r=$(r,[2,2],[2,2],"same"),r=tt(r,e.conv2),r=$(r,[2,2],[2,2],"same"),r=tt(r,e.conv3),r=$(r,[2,2],[2,2],"same"),r=tt(r,e.conv4),r=$(r,[2,2],[2,2],"same"),r=tt(r,e.conv5),r=$(r,[2,2],[1,1],"same"),r=tt(r,e.conv6),r=tt(r,e.conv7),yt(r,e.conv8,"valid",!1)}runMobilenet(t,e){let r=this.config.isFirstLayerConv2d?jt(yt(t,e.conv0,"valid",!1)):et(t,e.conv0);return r=$(r,[2,2],[2,2],"same"),r=et(r,e.conv1),r=$(r,[2,2],[2,2],"same"),r=et(r,e.conv2),r=$(r,[2,2],[2,2],"same"),r=et(r,e.conv3),r=$(r,[2,2],[2,2],"same"),r=et(r,e.conv4),r=$(r,[2,2],[2,2],"same"),r=et(r,e.conv5),r=$(r,[2,2],[1,1],"same"),r=e.conv6?et(r,e.conv6):r,r=e.conv7?et(r,e.conv7):r,yt(r,e.conv8,"valid",!1)}forwardInput(t,e){const{params:r}=this;if(!r)throw new Error("TinyYolov2 - load model before inference");return Nr(()=>{let o=Vs(t.toBatchTensor(e,!1),"float32");return o=this.config.meanRgb?G(o,this.config.meanRgb):o,o=o.div(zo(256)),this.config.withSeparableConvs?this.runMobilenet(o,r):this.runTinyYolov2(o,r)})}async forward(t,e){return await this.forwardInput(await w(t),e)}async detect(t,e={}){const{inputSize:r,scoreThreshold:o}=new rt(e),n=await w(t),a=await this.forwardInput(n,r),i=Nr(()=>Xs(a)[0].expandDims()),s={width:n.getInputWidth(0),height:n.getInputHeight(0)},c=await this.extractBoxes(i,n.getReshapedInputDimensions(0),o);a.dispose(),i.dispose();const m=c.map(d=>d.box),p=c.map(d=>d.score),f=c.map(d=>d.classScore),l=c.map(d=>this.config.classes[d.label]),u=Je(m.map(d=>d.rescale(r)),p,this.config.iouThreshold,!0),v=u.map(d=>new Ct(p[d],f[d],l[d],m[d],s));return v}getDefaultModelName(){return""}extractParamsFromWeigthMap(t){return Go(t,this.config)}extractParams(t){const e=this.config.filterSizes||$t.DEFAULT_FILTER_SIZES,r=e?e.length:void 0;if(r!==7&&r!==8&&r!==9)throw new Error(`TinyYolov2 - expected 7 | 8 | 9 convolutional filters, but found ${r} filterSizes in config`);return Ho(t,this.config,this.boxEncodingSize,e)}async extractBoxes(t,e,r){const{width:o,height:n}=e,a=Math.max(o,n),i=a/o,s=a/n,c=t.shape[1],m=this.config.anchors.length,[p,f,l]=Nr(()=>{const b=t.reshape([c,c,m,this.boxEncodingSize]),x=b.slice([0,0,0,0],[c,c,m,4]),h=b.slice([0,0,0,4],[c,c,m,1]),P=this.withClassScores?Us(b.slice([0,0,0,5],[c,c,m,this.config.classes.length]),3):zo(0);return[x,h,P]}),u=[],v=await f.array(),d=await p.array();for(let b=0;b<c;b++)for(let x=0;x<c;x++)for(let h=0;h<m;h++){const P=Xt(v[b][x][h][0]);if(!r||P>r){const k=(x+Xt(d[b][x][h][0]))/c*i,I=(b+Xt(d[b][x][h][1]))/c*s,B=Math.exp(d[b][x][h][2])*this.config.anchors[h].x/c*i,R=Math.exp(d[b][x][h][3])*this.config.anchors[h].y/c*s,ot=k-B/2,nt=I-R/2,at={row:b,col:x,anchor:h},{classScore:mt,label:pt}=this.withClassScores?await this.extractPredictedClass(l,at):{classScore:1,label:0};u.push({box:new Ut(ot,nt,ot+B,nt+R),score:P,classScore:P*mt,label:pt,...at})}}return p.dispose(),f.dispose(),l.dispose(),u}async extractPredictedClass(t,e){const{row:r,col:o,anchor:n}=e,a=await t.array();return Array(this.config.classes.length).fill(0).map((i,s)=>a[r][o][n][s]).map((i,s)=>({classScore:i,label:s})).reduce((i,s)=>i.classScore>s.classScore?i:s)}}$t.DEFAULT_FILTER_SIZES=[3,16,32,64,128,256,512,1024,1024];class ae extends $t{constructor(t=!0){const e=Object.assign({},{withSeparableConvs:t,iouThreshold:Ao,classes:["face"]},t?{anchors:Bo,meanRgb:Ro}:{anchors:Wo,withClassScores:!0});super(e)}get withSeparableConvs(){return this.config.withSeparableConvs}get anchors(){return this.config.anchors}async locateFaces(t,e){const r=await this.detect(t,e);return r.map(o=>new _(o.score,o.relativeBox,{width:o.imageWidth,height:o.imageHeight}))}getDefaultModelName(){return this.withSeparableConvs?jo:Oo}extractParamsFromWeigthMap(t){return super.extractParamsFromWeigthMap(t)}}function Js(t,e=!0){const r=new ae(e);return r.extractWeights(t),r}class Lr extends rt{constructor(){super(...arguments);this._name="TinyFaceDetectorOptions"}}class U{async then(t){return t(await this.run())}async run(){throw new Error("ComposableTask - run is not implemented")}}import{Tensor as Yo}from"@tensorflow/tfjs/dist/tf.es2017.js";async function _t(t,e,r,o,n=({alignedRect:a})=>a){const a=t.map(c=>Ft(c)?n(c):c.detection),i=o||(e instanceof Yo?await It(e,a):await Lt(e,a)),s=await r(i);return i.forEach(c=>c instanceof Yo&&c.dispose()),s}async function Ht(t,e,r,o,n){return _t([t],e,async a=>r(a[0]),o,n)}const Vo=.4,Uo=[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)],Xo=[117.001,114.697,97.404];class se extends $t{constructor(){const t={withSeparableConvs:!0,iouThreshold:Vo,classes:["face"],anchors:Uo,meanRgb:Xo,isFirstLayerConv2d:!0,filterSizes:[3,16,32,64,128,256,512]};super(t)}get anchors(){return this.config.anchors}async locateFaces(t,e){const r=await this.detect(t,e);return r.map(o=>new _(o.score,o.relativeBox,{width:o.imageWidth,height:o.imageHeight}))}getDefaultModelName(){return"tiny_face_detector_model"}extractParamsFromWeigthMap(t){return super.extractParamsFromWeigthMap(t)}}const y={ssdMobilenetv1:new Ot,tinyFaceDetector:new se,tinyYolov2:new ae,faceLandmark68Net:new ee,faceLandmark68TinyNet:new Fr,faceRecognitionNet:new oe,faceExpressionNet:new ur,ageGenderNet:new xr},Jo=(t,e)=>y.ssdMobilenetv1.locateFaces(t,e),qs=(t,e)=>y.tinyFaceDetector.locateFaces(t,e),Zs=(t,e)=>y.tinyYolov2.locateFaces(t,e),qo=t=>y.faceLandmark68Net.detectLandmarks(t),Ks=t=>y.faceLandmark68TinyNet.detectLandmarks(t),Qs=t=>y.faceRecognitionNet.computeFaceDescriptor(t),ti=t=>y.faceExpressionNet.predictExpressions(t),ei=t=>y.ageGenderNet.predictAgeAndGender(t),Zo=t=>y.ssdMobilenetv1.load(t),ri=t=>y.tinyFaceDetector.load(t),oi=t=>y.tinyYolov2.load(t),ni=t=>y.faceLandmark68Net.load(t),ai=t=>y.faceLandmark68TinyNet.load(t),si=t=>y.faceRecognitionNet.load(t),ii=t=>y.faceExpressionNet.load(t),ci=t=>y.ageGenderNet.load(t),mi=Zo,pi=Jo,fi=qo;class Ko extends U{constructor(t,e,r){super();this.parentTask=t;this.input=e;this.extractedFaces=r}}class me extends Ko{async run(){const t=await this.parentTask,e=await _t(t,this.input,async r=>await Promise.all(r.map(o=>y.faceExpressionNet.predictExpressions(o))),this.extractedFaces);return t.map((r,o)=>Me(r,e[o]))}withAgeAndGender(){return new ie(this,this.input)}}class pe extends Ko{async run(){const t=await this.parentTask;if(!t)return;const e=await Ht(t,this.input,r=>y.faceExpressionNet.predictExpressions(r),this.extractedFaces);return Me(t,e)}withAgeAndGender(){return new ce(this,this.input)}}class Yt extends me{withAgeAndGender(){return new Gt(this,this.input)}withFaceDescriptors(){return new Dt(this,this.input)}}class Vt extends pe{withAgeAndGender(){return new zt(this,this.input)}withFaceDescriptor(){return new Et(this,this.input)}}class Qo extends U{constructor(t,e,r){super();this.parentTask=t;this.input=e;this.extractedFaces=r}}class ie extends Qo{async run(){const t=await this.parentTask,e=await _t(t,this.input,async r=>await Promise.all(r.map(o=>y.ageGenderNet.predictAgeAndGender(o))),this.extractedFaces);return t.map((r,o)=>{const{age:n,gender:a,genderProbability:i}=e[o];return Le(Ie(r,a,i),n)})}withFaceExpressions(){return new me(this,this.input)}}class ce extends Qo{async run(){const t=await this.parentTask;if(!t)return;const{age:e,gender:r,genderProbability:o}=await Ht(t,this.input,n=>y.ageGenderNet.predictAgeAndGender(n),this.extractedFaces);return Le(Ie(t,r,o),e)}withFaceExpressions(){return new pe(this,this.input)}}class Gt extends ie{withFaceExpressions(){return new Yt(this,this.input)}withFaceDescriptors(){return new Dt(this,this.input)}}class zt extends ce{withFaceExpressions(){return new Vt(this,this.input)}withFaceDescriptor(){return new Et(this,this.input)}}class Ir extends U{constructor(t,e){super();this.parentTask=t;this.input=e}}class Dt extends Ir{async run(){const t=await this.parentTask,e=await _t(t,this.input,r=>Promise.all(r.map(o=>y.faceRecognitionNet.computeFaceDescriptor(o))),null,r=>r.landmarks.align(null,{useDlibAlignment:!0}));return e.map((r,o)=>Ne(t[o],r))}withFaceExpressions(){return new Yt(this,this.input)}withAgeAndGender(){return new Gt(this,this.input)}}class Et extends Ir{async run(){const t=await this.parentTask;if(!t)return;const e=await Ht(t,this.input,r=>y.faceRecognitionNet.computeFaceDescriptor(r),null,r=>r.landmarks.align(null,{useDlibAlignment:!0}));return Ne(t,e)}withFaceExpressions(){return new Vt(this,this.input)}withAgeAndGender(){return new zt(this,this.input)}}import{Tensor as Oe}from"@tensorflow/tfjs/dist/tf.es2017.js";class Sr extends U{constructor(t,e,r){super();this.parentTask=t;this.input=e;this.useTinyLandmarkNet=r}get landmarkNet(){return this.useTinyLandmarkNet?y.faceLandmark68TinyNet:y.faceLandmark68Net}}class Ar extends Sr{async run(){const t=await this.parentTask,e=t.map(n=>n.detection),r=this.input instanceof Oe?await It(this.input,e):await Lt(this.input,e),o=await Promise.all(r.map(n=>this.landmarkNet.detectLandmarks(n)));return r.forEach(n=>n instanceof Oe&&n.dispose()),t.map((n,a)=>Bt(n,o[a]))}withFaceExpressions(){return new Yt(this,this.input)}withAgeAndGender(){return new Gt(this,this.input)}withFaceDescriptors(){return new Dt(this,this.input)}}class Wr extends Sr{async run(){const t=await this.parentTask;if(!t)return;const{detection:e}=t,r=this.input instanceof Oe?await It(this.input,[e]):await Lt(this.input,[e]),o=await this.landmarkNet.detectLandmarks(r[0]);return r.forEach(n=>n instanceof Oe&&n.dispose()),Bt(t,o)}withFaceExpressions(){return new Vt(this,this.input)}withAgeAndGender(){return new zt(this,this.input)}withFaceDescriptor(){return new Et(this,this.input)}}class Br extends U{constructor(t,e=new V){super();this.input=t;this.options=e}}class je extends Br{async run(){const{input:t,options:e}=this,r=e instanceof Lr?o=>y.tinyFaceDetector.locateFaces(o,e):e instanceof V?o=>y.ssdMobilenetv1.locateFaces(o,e):e instanceof rt?o=>y.tinyYolov2.locateFaces(o,e):null;if(!r)throw new Error("detectFaces - expected options to be instance of TinyFaceDetectorOptions | SsdMobilenetv1Options | MtcnnOptions | TinyYolov2Options");return r(t)}runAndExtendWithFaceDetections(){return new Promise(async t=>{const e=await this.run();return t(e.map(r=>ht({},r)))})}withFaceLandmarks(t=!1){return new Ar(this.runAndExtendWithFaceDetections(),this.input,t)}withFaceExpressions(){return new me(this.runAndExtendWithFaceDetections(),this.input)}withAgeAndGender(){return new ie(this.runAndExtendWithFaceDetections(),this.input)}}class Rr extends Br{async run(){const t=await new je(this.input,this.options);let e=t[0];return t.forEach(r=>{r.score>e.score&&(e=r)}),e}runAndExtendWithFaceDetection(){return new Promise(async t=>{const e=await this.run();return t(e?ht({},e):void 0)})}withFaceLandmarks(t=!1){return new Wr(this.runAndExtendWithFaceDetection(),this.input,t)}withFaceExpressions(){return new pe(this.runAndExtendWithFaceDetection(),this.input)}withAgeAndGender(){return new ce(this.runAndExtendWithFaceDetection(),this.input)}}function li(t,e=new V){return new Rr(t,e)}function $e(t,e=new V){return new je(t,e)}async function tn(t,e){return console.warn("allFacesSsdMobilenetv1 is deprecated and will be removed soon, use the high level api instead"),await $e(t,new V(e?{minConfidence:e}:{})).withFaceLandmarks().withFaceDescriptors()}async function ui(t,e={}){return console.warn("allFacesTinyYolov2 is deprecated and will be removed soon, use the high level api instead"),await $e(t,new rt(e)).withFaceLandmarks().withFaceDescriptors()}const di=tn;function Or(t,e){if(t.length!==e.length)throw new Error("euclideanDistance: arr1.length !== arr2.length");const r=Array.from(t),o=Array.from(e);return Math.sqrt(r.map((n,a)=>n-o[a]).reduce((n,a)=>n+Math.pow(a,2),0))}class en{constructor(t,e=.6){this._distanceThreshold=e;const r=Array.isArray(t)?t:[t];if(!r.length)throw new Error("FaceRecognizer.constructor - expected atleast one input");let o=1;const n=()=>`person ${o++}`;this._labeledDescriptors=r.map(a=>{if(a instanceof dt)return a;if(a instanceof Float32Array)return new dt(n(),[a]);if(a.descriptor&&a.descriptor instanceof Float32Array)return new dt(n(),[a.descriptor]);throw new Error("FaceRecognizer.constructor - expected inputs to be of type LabeledFaceDescriptors | WithFaceDescriptor<any> | Float32Array | Array<LabeledFaceDescriptors | WithFaceDescriptor<any> | Float32Array>")})}get labeledDescriptors(){return this._labeledDescriptors}get distanceThreshold(){return this._distanceThreshold}computeMeanDistance(t,e){return e.map(r=>Or(r,t)).reduce((r,o)=>r+o,0)/(e.length||1)}matchDescriptor(t){return this.labeledDescriptors.map(({descriptors:e,label:r})=>new de(r,this.computeMeanDistance(t,e))).reduce((e,r)=>e.distance<r.distance?e:r)}findBestMatch(t){const e=this.matchDescriptor(t);return e.distance<this.distanceThreshold?e:new de("unknown",e.distance)}toJSON(){return{distanceThreshold:this.distanceThreshold,labeledDescriptors:this.labeledDescriptors.map(t=>t.toJSON())}}static fromJSON(t){const e=t.labeledDescriptors.map(r=>dt.fromJSON(r));return new en(e,t.distanceThreshold)}}function hi(t){const e=new se;return e.extractWeights(t),e}function rn(t,e){const{width:r,height:o}=new S(e.width,e.height);if(r<=0||o<=0)throw new Error(`resizeResults - invalid dimensions: ${JSON.stringify({width:r,height:o})}`);if(Array.isArray(t))return t.map(n=>rn(n,{width:r,height:o}));if(Ft(t)){const n=t.detection.forSize(r,o),a=t.unshiftedLandmarks.forSize(n.box.width,n.box.height);return Bt(ht(t,n),a)}return J(t)?ht(t,t.detection.forSize(r,o)):t instanceof O||t instanceof _?t.forSize(r,o):t}var on="0.7.3";import*as gi from"@tensorflow/tfjs/dist/tf.es2017.js";const bi=typeof process!="undefined",xi=typeof navigator!="undefined"&&typeof navigator.userAgent!="undefined",vi={faceapi:on,node:bi,browser:xi};export{xr as AgeGenderNet,Ut as BoundingBox,F as Box,U as ComposableTask,Dt as ComputeAllFaceDescriptorsTask,Ir as ComputeFaceDescriptorsTaskBase,Et as ComputeSingleFaceDescriptorTask,Ar as DetectAllFaceLandmarksTask,je as DetectAllFacesTask,Sr as DetectFaceLandmarksTaskBase,Br as DetectFacesTaskBase,Wr as DetectSingleFaceLandmarksTask,Rr as DetectSingleFaceTask,S as Dimensions,lr as FACE_EXPRESSION_LABELS,_ as FaceDetection,Es as FaceDetectionNet,ur as FaceExpressionNet,Tt as FaceExpressions,ee as FaceLandmark68Net,Fr as FaceLandmark68TinyNet,Aa as FaceLandmarkNet,O as FaceLandmarks,kn as FaceLandmarks5,qt as FaceLandmarks68,de as FaceMatch,en as FaceMatcher,oe as FaceRecognitionNet,Q as Gender,he as LabeledBox,dt as LabeledFaceDescriptors,st as NetInput,E as NeuralNetwork,Ct as ObjectDetection,g as Point,Nn as PredictedBox,Jt as Rect,Ot as SsdMobilenetv1,V as SsdMobilenetv1Options,se as TinyFaceDetector,Lr as TinyFaceDetectorOptions,ae as TinyYolov2,rt as TinyYolov2Options,kr as TinyYolov2SizeType,di as allFaces,tn as allFacesSsdMobilenetv1,ui as allFacesTinyYolov2,ar as awaitMediaLoaded,sr as bufferToImage,Qs as computeFaceDescriptor,Nt as createCanvas,Kt as createCanvasFromMedia,Ds as createFaceDetectionNet,Za as createFaceRecognitionNet,So as createSsdMobilenetv1,hi as createTinyFaceDetector,Js as createTinyYolov2,$e as detectAllFaces,qo as detectFaceLandmarks,Ks as detectFaceLandmarksTiny,fi as detectLandmarks,li as detectSingleFace,hr as draw,T as env,Or as euclideanDistance,Le as extendWithAge,Ne as extendWithFaceDescriptor,ht as extendWithFaceDetection,Me as extendWithFaceExpressions,Bt as extendWithFaceLandmarks,Ie as extendWithGender,It as extractFaceTensors,Lt as extractFaces,Yn as fetchImage,mr as fetchJson,Vn as fetchNetWeights,xt as fetchOrThrow,N as getContext2dOrThrow,bt as getMediaDimensions,ir as imageTensorToCanvas,cr as imageToSquare,Dn as inverseSigmoid,Ue as iou,xe as isMediaElement,Zt as isMediaLoaded,Ka as isWithAge,J as isWithFaceDetection,dr as isWithFaceExpressions,Ft as isWithFaceLandmarks,Qa as isWithGender,ci as loadAgeGenderModel,mi as loadFaceDetectionModel,ii as loadFaceExpressionModel,ni as loadFaceLandmarkModel,ai as loadFaceLandmarkTinyModel,si as loadFaceRecognitionModel,Zo as loadSsdMobilenetv1Model,ri as loadTinyFaceDetectorModel,oi as loadTinyYolov2Model,pr as loadWeightMap,pi as locateFaces,Xn as matchDimensions,Xe as minBbox,y as nets,Je as nonMaxSuppression,G as normalize,Ze as padToSquare,ei as predictAgeAndGender,ti as recognizeFaceExpressions,rn as resizeResults,gt as resolveInput,_n as shuffleArray,Xt as sigmoid,Jo as ssdMobilenetv1,gi as tf,qs as tinyFaceDetector,Zs as tinyYolov2,w as toNetInput,Ge as utils,Cr as validateConfig,vi as version};
//# sourceMappingURL=face-api.nobundle.js.map