UNPKG

@nsfw-filter/nsfwjs

Version:

Detect NSFW content client side

1 lines 1.97 MB
!function(f){"object"==typeof exports&&"undefined"!=typeof module?module.exports=f():"function"==typeof define&&define.amd?define([],f):("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).nsfwjs=f()}(function(){return function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){return o(e[i][1][r]||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}({1:[function(require,module,exports){(function(Buffer){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){void 0===k2&&(k2=k),Object.defineProperty(o,k2,{enumerable:!0,get:function(){return m[k]}})}:function(o,m,k,k2){void 0===k2&&(k2=k),o[k2]=m[k]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}:function(o,v){o.default=v}),__importStar=this&&this.__importStar||function(mod){if(mod&&mod.__esModule)return mod;var result={};if(null!=mod)for(var k in mod)"default"!==k&&Object.hasOwnProperty.call(mod,k)&&__createBinding(result,mod,k);return __setModuleDefault(result,mod),result},__awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){return new(P=P||Promise)(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){var value;result.done?resolve(result.value):((value=result.value)instanceof P?value:new P(function(resolve){resolve(value)})).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})},__generator=this&&this.__generator||function(thisArg,body){var f,y,t,_={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]},g={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return function(op){if(f)throw new TypeError("Generator is already executing.");for(;_;)try{if(f=1,y&&(t=2&op[0]?y.return:op[0]?y.throw||((t=y.return)&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;switch(y=0,t&&(op=[2&op[0],t.value]),op[0]){case 0:case 1:t=op;break;case 4:return _.label++,{value:op[1],done:!1};case 5:_.label++,y=op[1],op=[0];continue;case 7:op=_.ops.pop(),_.trys.pop();continue;default:if(!(t=0<(t=_.trys).length&&t[t.length-1])&&(6===op[0]||2===op[0])){_=0;continue}if(3===op[0]&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(6===op[0]&&_.label<t[1]){_.label=t[1],t=op;break}if(t&&_.label<t[2]){_.label=t[2],_.ops.push(op);break}t[2]&&_.ops.pop(),_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e],y=0}finally{f=t=0}if(5&op[0])throw op[1];return{value:op[0]?op[1]:void 0,done:!0}}([n,v])}}},__importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.NSFWJS=exports.load=void 0;var tf=__importStar(require("@tensorflow/tfjs")),nsfw_classes_1=require("./nsfw_classes"),gif_frames_1=__importDefault(require("@nsfw-filter/gif-frames")),BASE_PATH="https://s3.amazonaws.com/ir_public/nsfwjscdn/TFJS_nsfw_mobilenet/tfjs_quant_nsfw_mobilenet/",IMAGE_SIZE=224;exports.load=function(base,options){return void 0===base&&(base=BASE_PATH),void 0===options&&(options={size:IMAGE_SIZE}),__awaiter(this,void 0,void 0,function(){var nsfwnet;return __generator(this,function(_a){switch(_a.label){case 0:if(null==tf)throw new Error("Cannot find TensorFlow.js. If you are using a <script> tag, please also include @tensorflow/tfjs on the page before using this model.");return options.size=options.size||IMAGE_SIZE,[4,(nsfwnet=new NSFWJS(base,options)).load()];case 1:return _a.sent(),[2,nsfwnet]}})})};var NSFWJS=function(){function NSFWJS(modelPathBaseOrIOHandler,options){this.intermediateModels={},this.options=options,this.normalizationOffset=tf.scalar(255),this.pathOrIOHandler="string"==typeof modelPathBaseOrIOHandler?modelPathBaseOrIOHandler+"model.json":modelPathBaseOrIOHandler}return NSFWJS.prototype.load=function(){return __awaiter(this,void 0,void 0,function(){var _a,size,_b,_c,result,_this=this;return __generator(this,function(_d){switch(_d.label){case 0:return(_a=this.options,size=_a.size,"graph"!==_a.type)?[3,2]:(_b=this,[4,tf.loadGraphModel(this.pathOrIOHandler)]);case 1:return _b.model=_d.sent(),[3,4];case 2:return _c=this,[4,tf.loadLayersModel(this.pathOrIOHandler)];case 3:_c.model=_d.sent(),this.endpoints=this.model.layers.map(function(l){return l.name}),_d.label=4;case 4:return[4,(result=tf.tidy(function(){return _this.model.predict(tf.zeros([1,size,size,3]))})).data()];case 5:return _d.sent(),result.dispose(),[2]}})})},NSFWJS.prototype.infer=function(img,endpoint){var _this=this;if(null!=endpoint&&-1===this.endpoints.indexOf(endpoint))throw new Error("Unknown endpoint "+endpoint+". Available endpoints: "+this.endpoints+".");return tf.tidy(function(){img instanceof tf.Tensor||(img=tf.browser.fromPixels(img));var normalized=img.toFloat().div(_this.normalizationOffset),resized=normalized,size=_this.options.size;img.shape[0]===size&&img.shape[1]===size||(resized=tf.image.resizeBilinear(normalized,[size,size],!0));var layer,batched=resized.reshape([1,size,size,3]),model=null==endpoint?_this.model:(_this.model.hasOwnProperty("layers")&&null==_this.intermediateModels[endpoint]&&(layer=_this.model.layers.find(function(l){return l.name===endpoint}),_this.intermediateModels[endpoint]=tf.model({inputs:_this.model.inputs,outputs:layer.output})),_this.intermediateModels[endpoint]);return model.predict(batched)})},NSFWJS.prototype.classify=function(img,topk){return void 0===topk&&(topk=5),__awaiter(this,void 0,void 0,function(){var logits,classes;return __generator(this,function(_a){switch(_a.label){case 0:return[4,function(logits,topK){return __awaiter(this,void 0,void 0,function(){var values,valuesAndIndices,topkValues,topkIndices,topClassesAndProbs,i;return __generator(this,function(_a){switch(_a.label){case 0:return[4,logits.data()];case 1:for(values=_a.sent(),valuesAndIndices=[],i=0;i<values.length;i++)valuesAndIndices.push({value:values[i],index:i});for(valuesAndIndices.sort(function(a,b){return b.value-a.value}),topkValues=new Float32Array(topK),topkIndices=new Int32Array(topK),i=0;i<topK;i++)topkValues[i]=valuesAndIndices[i].value,topkIndices[i]=valuesAndIndices[i].index;for(topClassesAndProbs=[],i=0;i<topkIndices.length;i++)topClassesAndProbs.push({className:nsfw_classes_1.NSFW_CLASSES[topkIndices[i]],probability:topkValues[i]});return[2,topClassesAndProbs]}})})}(logits=this.infer(img),topk)];case 1:return classes=_a.sent(),logits.dispose(),[2,classes]}})})},NSFWJS.prototype.classifyGif=function(gif,config){return void 0===config&&(config={topk:5}),__awaiter(this,void 0,void 0,function(){var frameData,acceptedFrames,totalTimeInMs,totalFrames,interval,arrayOfPredictions,i,image,predictions;return __generator(this,function(_a){switch(_a.label){case 0:return frameData=[],Buffer.isBuffer(gif)?[4,gif_frames_1.default({url:gif,frames:"all",outputType:"jpg"})]:[3,2];case 1:return frameData=_a.sent(),[3,4];case 2:return[4,gif_frames_1.default({url:gif.src,frames:"all",outputType:"canvas"})];case 3:frameData=_a.sent(),_a.label=4;case 4:if(acceptedFrames=[],"number"!=typeof config.fps)acceptedFrames=frameData.map(function(_element,index){return index});else{for(i=totalTimeInMs=0;i<frameData.length;i++)totalTimeInMs+=10*frameData[i].frameInfo.delay;if((totalFrames=Math.floor(totalTimeInMs/1e3*config.fps))<=1)acceptedFrames=[Math.floor(frameData.length/2)];else if(totalFrames>=frameData.length)acceptedFrames=frameData.map(function(_element,index){return index});else for(interval=Math.floor(frameData.length/(totalFrames+1)),i=1;i<=totalFrames;i++)acceptedFrames.push(i*interval)}arrayOfPredictions=[],i=0,_a.label=5;case 5:return i<acceptedFrames.length?(image=frameData[acceptedFrames[i]].getImage(),[4,this.classify(image,config.topk)]):[3,8];case 6:predictions=_a.sent(),"function"==typeof config.onFrame&&config.onFrame({index:acceptedFrames[i],totalFrames:frameData.length,predictions:predictions,image:image}),arrayOfPredictions.push(predictions),_a.label=7;case 7:return i++,[3,5];case 8:return[2,arrayOfPredictions]}})})},NSFWJS}();exports.NSFWJS=NSFWJS}).call(this,{isBuffer:require("../node_modules/is-buffer/index.js")})},{"../node_modules/is-buffer/index.js":443,"./nsfw_classes":2,"@nsfw-filter/gif-frames":4,"@tensorflow/tfjs":411}],2:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.NSFW_CLASSES=void 0,exports.NSFW_CLASSES={0:"Drawing",1:"Hentai",2:"Neutral",3:"Porn",4:"Sexy"}},{}],3:[function(require,module,exports){"use strict";module.exports=require("./index")},{"./index":1}],4:[function(require,module,exports){var MultiRange=require("multi-integer-range").MultiRange,getPixels=require("get-pixels-frame-info-update"),savePixels=require("@nsfw-filter/save-pixels");function nopromises(){throw new Error("Promises not supported in your environment. Use the callback argument or a Promise polyfill.")}var brokenPromise={then:nopromises,catch:nopromises};module.exports=function(options,callback){var promise,resolve,reject;options=options||{},callback=callback||function(){},"function"==typeof Promise?promise=new Promise(function(_resolve,_reject){resolve=function(res){callback(null,res),_resolve(res)},reject=function(err){callback(err),_reject(err)}}):(promise=brokenPromise,resolve=function(res){callback(null,res)},reject=callback);var url=options.url;if(!url)return reject(new Error('"url" option is required.')),promise;var frames=options.frames;if(!frames&&0!==frames)return reject(new Error('"frames" option is required.')),promise;var outputType=options.outputType||"jpg",quality=options.quality,cumulative=options.cumulative,acceptedFrames="all"===frames?"all":new MultiRange(frames),inputType="undefined"==typeof window?"image/gif":".GIF";return getPixels(url,inputType,function(err,pixels,framesInfo){if(err)reject(err);else if(pixels.shape.length<4)reject(new Error('"url" input should be multi-frame GIF.'));else{for(var frameData=[],maxAccumulatedFrame=0,i=0;i<pixels.shape[0];i++)"all"!==acceptedFrames&&!acceptedFrames.has(i)||function(frameIndex){frameData.push({getImage:function(){if(cumulative&&maxAccumulatedFrame<frameIndex){for(var lastFrame=pixels.pick(maxAccumulatedFrame),f=maxAccumulatedFrame+1;f<=frameIndex;f++){for(var frame=pixels.pick(f),x=0;x<frame.shape[0];x++)for(var y=0;y<frame.shape[1];y++)0===frame.get(x,y,3)&&(frame.set(x,y,0,lastFrame.get(x,y,0)),frame.set(x,y,1,lastFrame.get(x,y,1)),frame.set(x,y,2,lastFrame.get(x,y,2)),frame.set(x,y,3,lastFrame.get(x,y,3)));lastFrame=frame}maxAccumulatedFrame=frameIndex}return savePixels(pixels.pick(frameIndex),outputType,{quality:quality})},frameIndex:frameIndex,frameInfo:framesInfo&&framesInfo[frameIndex]})}(i);resolve(frameData)}}),promise}},{"@nsfw-filter/save-pixels":7,"get-pixels-frame-info-update":428,"multi-integer-range":445}],5:[function(require,module,exports){var iota=require("iota-array"),isBuffer=require("is-buffer"),hasTypedArrays="undefined"!=typeof Float64Array;function compare1st(a,b){return a[0]-b[0]}function order(){for(var stride=this.stride,terms=new Array(stride.length),i=0;i<terms.length;++i)terms[i]=[Math.abs(stride[i]),i];terms.sort(compare1st);var result=new Array(terms.length);for(i=0;i<result.length;++i)result[i]=terms[i][1];return result}function compileConstructor(dtype,dimension){var className=["View",dimension,"d",dtype].join("");dimension<0&&(className="View_Nil"+dtype);var useGetters="generic"===dtype;if(-1===dimension){var code="function "+className+"(a){this.data=a;};var proto="+className+".prototype;proto.dtype='"+dtype+"';proto.index=function(){return -1};proto.size=0;proto.dimension=-1;proto.shape=proto.stride=proto.order=[];proto.lo=proto.hi=proto.transpose=proto.step=function(){return new "+className+"(this.data);};proto.get=proto.set=function(){};proto.pick=function(){return null};return function construct_"+className+"(a){return new "+className+"(a);}";return new Function(code)()}if(0===dimension){code="function "+className+"(a,d) {this.data = a;this.offset = d};var proto="+className+".prototype;proto.dtype='"+dtype+"';proto.index=function(){return this.offset};proto.dimension=0;proto.size=1;proto.shape=proto.stride=proto.order=[];proto.lo=proto.hi=proto.transpose=proto.step=function "+className+"_copy() {return new "+className+"(this.data,this.offset)};proto.pick=function "+className+"_pick(){return TrivialArray(this.data);};proto.valueOf=proto.get=function "+className+"_get(){return "+(useGetters?"this.data.get(this.offset)":"this.data[this.offset]")+"};proto.set=function "+className+"_set(v){return "+(useGetters?"this.data.set(this.offset,v)":"this.data[this.offset]=v")+"};return function construct_"+className+"(a,b,c,d){return new "+className+"(a,d)}";return new Function("TrivialArray",code)(CACHED_CONSTRUCTORS[dtype][0])}var code=["'use strict'"],indices=iota(dimension),args=indices.map(function(i){return"i"+i}),index_str="this.offset+"+indices.map(function(i){return"this.stride["+i+"]*i"+i}).join("+"),shapeArg=indices.map(function(i){return"b"+i}).join(","),strideArg=indices.map(function(i){return"c"+i}).join(",");code.push("function "+className+"(a,"+shapeArg+","+strideArg+",d){this.data=a","this.shape=["+shapeArg+"]","this.stride=["+strideArg+"]","this.offset=d|0}","var proto="+className+".prototype","proto.dtype='"+dtype+"'","proto.dimension="+dimension),code.push("Object.defineProperty(proto,'size',{get:function "+className+"_size(){return "+indices.map(function(i){return"this.shape["+i+"]"}).join("*"),"}})"),1===dimension?code.push("proto.order=[0]"):(code.push("Object.defineProperty(proto,'order',{get:"),dimension<4?(code.push("function "+className+"_order(){"),2===dimension?code.push("return (Math.abs(this.stride[0])>Math.abs(this.stride[1]))?[1,0]:[0,1]}})"):3===dimension&&code.push("var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);if(s0>s1){if(s1>s2){return [2,1,0];}else if(s0>s2){return [1,2,0];}else{return [1,0,2];}}else if(s0>s2){return [2,0,1];}else if(s2>s1){return [0,1,2];}else{return [0,2,1];}}})")):code.push("ORDER})")),code.push("proto.set=function "+className+"_set("+args.join(",")+",v){"),useGetters?code.push("return this.data.set("+index_str+",v)}"):code.push("return this.data["+index_str+"]=v}"),code.push("proto.get=function "+className+"_get("+args.join(",")+"){"),useGetters?code.push("return this.data.get("+index_str+")}"):code.push("return this.data["+index_str+"]}"),code.push("proto.index=function "+className+"_index(",args.join(),"){return "+index_str+"}"),code.push("proto.hi=function "+className+"_hi("+args.join(",")+"){return new "+className+"(this.data,"+indices.map(function(i){return["(typeof i",i,"!=='number'||i",i,"<0)?this.shape[",i,"]:i",i,"|0"].join("")}).join(",")+","+indices.map(function(i){return"this.stride["+i+"]"}).join(",")+",this.offset)}");var a_vars=indices.map(function(i){return"a"+i+"=this.shape["+i+"]"}),c_vars=indices.map(function(i){return"c"+i+"=this.stride["+i+"]"});code.push("proto.lo=function "+className+"_lo("+args.join(",")+"){var b=this.offset,d=0,"+a_vars.join(",")+","+c_vars.join(","));for(var i=0;i<dimension;++i)code.push("if(typeof i"+i+"==='number'&&i"+i+">=0){d=i"+i+"|0;b+=c"+i+"*d;a"+i+"-=d}");code.push("return new "+className+"(this.data,"+indices.map(function(i){return"a"+i}).join(",")+","+indices.map(function(i){return"c"+i}).join(",")+",b)}"),code.push("proto.step=function "+className+"_step("+args.join(",")+"){var "+indices.map(function(i){return"a"+i+"=this.shape["+i+"]"}).join(",")+","+indices.map(function(i){return"b"+i+"=this.stride["+i+"]"}).join(",")+",c=this.offset,d=0,ceil=Math.ceil");for(i=0;i<dimension;++i)code.push("if(typeof i"+i+"==='number'){d=i"+i+"|0;if(d<0){c+=b"+i+"*(a"+i+"-1);a"+i+"=ceil(-a"+i+"/d)}else{a"+i+"=ceil(a"+i+"/d)}b"+i+"*=d}");code.push("return new "+className+"(this.data,"+indices.map(function(i){return"a"+i}).join(",")+","+indices.map(function(i){return"b"+i}).join(",")+",c)}");for(var tShape=new Array(dimension),tStride=new Array(dimension),i=0;i<dimension;++i)tShape[i]="a[i"+i+"]",tStride[i]="b[i"+i+"]";code.push("proto.transpose=function "+className+"_transpose("+args+"){"+args.map(function(n,idx){return n+"=("+n+"===undefined?"+idx+":"+n+"|0)"}).join(";"),"var a=this.shape,b=this.stride;return new "+className+"(this.data,"+tShape.join(",")+","+tStride.join(",")+",this.offset)}"),code.push("proto.pick=function "+className+"_pick("+args+"){var a=[],b=[],c=this.offset");for(i=0;i<dimension;++i)code.push("if(typeof i"+i+"==='number'&&i"+i+">=0){c=(c+this.stride["+i+"]*i"+i+")|0}else{a.push(this.shape["+i+"]);b.push(this.stride["+i+"])}");return code.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}"),code.push("return function construct_"+className+"(data,shape,stride,offset){return new "+className+"(data,"+indices.map(function(i){return"shape["+i+"]"}).join(",")+","+indices.map(function(i){return"stride["+i+"]"}).join(",")+",offset)}"),new Function("CTOR_LIST","ORDER",code.join("\n"))(CACHED_CONSTRUCTORS[dtype],order)}var CACHED_CONSTRUCTORS={float32:[],float64:[],int8:[],int16:[],int32:[],uint8:[],uint16:[],uint32:[],array:[],uint8_clamped:[],buffer:[],generic:[]};module.exports=function(data,shape,stride,offset){if(void 0===data)return(0,CACHED_CONSTRUCTORS.array[0])([]);"number"==typeof data&&(data=[data]),void 0===shape&&(shape=[data.length]);var d=shape.length;if(void 0===stride){stride=new Array(d);for(var i=d-1,sz=1;0<=i;--i)stride[i]=sz,sz*=shape[i]}if(void 0===offset)for(i=offset=0;i<d;++i)stride[i]<0&&(offset-=(shape[i]-1)*stride[i]);for(var dtype=function(data){if(isBuffer(data))return"buffer";if(hasTypedArrays)switch(Object.prototype.toString.call(data)){case"[object Float64Array]":return"float64";case"[object Float32Array]":return"float32";case"[object Int8Array]":return"int8";case"[object Int16Array]":return"int16";case"[object Int32Array]":return"int32";case"[object Uint8Array]":return"uint8";case"[object Uint16Array]":return"uint16";case"[object Uint32Array]":return"uint32";case"[object Uint8ClampedArray]":return"uint8_clamped"}return Array.isArray(data)?"array":"generic"}(data),ctor_list=CACHED_CONSTRUCTORS[dtype];ctor_list.length<=d+1;)ctor_list.push(compileConstructor(dtype,ctor_list.length-1));return(0,ctor_list[d+1])(data,shape,stride,offset)}},{"iota-array":442,"is-buffer":443}],6:[function(require,module,exports){(function(process){var Stream=require("stream");function through(write,end,opts){write=write||function(data){this.queue(data)},end=end||function(){this.queue(null)};var ended=!1,destroyed=!1,buffer=[],_ended=!1,stream=new Stream;function drain(){for(;buffer.length&&!stream.paused;){var data=buffer.shift();if(null===data)return stream.emit("end");stream.emit("data",data)}}return stream.readable=stream.writable=!0,stream.paused=!1,stream.autoDestroy=!(opts&&!1===opts.autoDestroy),stream.write=function(data){return write.call(this,data),!stream.paused},stream.queue=stream.push=function(data){return _ended||(null==data&&(_ended=!0),buffer.push(data),drain()),stream},stream.on("end",function(){stream.readable=!1,!stream.writable&&stream.autoDestroy&&process.nextTick(function(){stream.destroy()})}),stream.end=function(data){if(!ended)return ended=!0,arguments.length&&stream.write(data),stream.writable=!1,end.call(stream),!stream.readable&&stream.autoDestroy&&stream.destroy(),stream},stream.destroy=function(){if(!destroyed)return ended=destroyed=!0,buffer.length=0,stream.writable=stream.readable=!1,stream.emit("close"),stream},stream.pause=function(){if(!stream.paused)return stream.paused=!0,stream},stream.resume=function(){return stream.paused&&(stream.paused=!1,stream.emit("resume")),drain(),stream.paused||stream.emit("drain"),stream},stream}(module.exports=through).through=through}).call(this,require("_process"))},{_process:486,stream:510}],7:[function(require,module,exports){(function(Buffer){"use strict";var GifEncoder=require("gif-encoder"),PNG=require("pngjs-nozlib").PNG,ndarray=require("ndarray"),ops=require("ndarray-ops"),through=require("through");function handleData(array,data,frame){if(4===array.shape.length)return handleData(array.pick(frame),data,0);if(3===array.shape.length)if(3===array.shape[2])ops.assign(ndarray(data,[array.shape[0],array.shape[1],3],[4,4*array.shape[0],1]),array),ops.assigns(ndarray(data,[array.shape[0]*array.shape[1]],[4],3),255);else if(4===array.shape[2])ops.assign(ndarray(data,[array.shape[0],array.shape[1],4],[4,4*array.shape[0],1]),array);else{if(1!==array.shape[2])return new Error("Incompatible array shape");ops.assign(ndarray(data,[array.shape[0],array.shape[1],3],[4,4*array.shape[0],1]),ndarray(array.data,[array.shape[0],array.shape[1],3],[array.stride[0],array.stride[1],0],array.offset)),ops.assigns(ndarray(data,[array.shape[0]*array.shape[1]],[4],3),255)}else{if(2!==array.shape.length)return new Error("Incompatible array shape");ops.assign(ndarray(data,[array.shape[0],array.shape[1],3],[4,4*array.shape[0],1]),ndarray(array.data,[array.shape[0],array.shape[1],3],[array.stride[0],array.stride[1],0],array.offset)),ops.assigns(ndarray(data,[array.shape[0]*array.shape[1]],[4],3),255)}return data}function haderror(err){var result=through();return result.emit("error",err),result}module.exports=function(array,type){switch(type.toUpperCase()){case"JPG":case".JPG":case"JPEG":case".JPEG":case"JPE":case".JPE":var width=array.shape[0],height=array.shape[1];return{data:data=handleData(array,data=new Buffer(width*height*4)),width:width,height:height};case"GIF":case".GIF":var frames=4===array.shape.length?array.shape[0]:1,width=4===array.shape.length?array.shape[1]:array.shape[0],height=4===array.shape.length?array.shape[2]:array.shape[1],data=new Buffer(width*height*4),gif=new GifEncoder(width,height);gif.writeHeader();for(var i=0;i<frames;i++)data=handleData(array,data,i),gif.addFrame(data);return gif.finish(),gif;case"PNG":case".PNG":var png=new PNG({width:array.shape[0],height:array.shape[1]});return"Error"==typeof(data=handleData(array,png.data))?haderror(data):(png.data=data,png.pack());case"CANVAS":var canvas=document.createElement("canvas"),context=canvas.getContext("2d");canvas.width=array.shape[0],canvas.height=array.shape[1];var imageData=context.getImageData(0,0,canvas.width,canvas.height);return"Error"==typeof(data=handleData(array,data=imageData.data))?haderror(data):(context.putImageData(imageData,0,0),canvas);default:return haderror(new Error("Unsupported file type: "+type))}}}).call(this,require("buffer").Buffer)},{buffer:421,"gif-encoder":429,ndarray:5,"ndarray-ops":446,"pngjs-nozlib":483,through:6}],8:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),function(DataType){DataType[DataType.DT_INVALID=0]="DT_INVALID",DataType[DataType.DT_FLOAT=1]="DT_FLOAT",DataType[DataType.DT_DOUBLE=2]="DT_DOUBLE",DataType[DataType.DT_INT32=3]="DT_INT32",DataType[DataType.DT_UINT8=4]="DT_UINT8",DataType[DataType.DT_INT16=5]="DT_INT16",DataType[DataType.DT_INT8=6]="DT_INT8",DataType[DataType.DT_STRING=7]="DT_STRING",DataType[DataType.DT_COMPLEX64=8]="DT_COMPLEX64",DataType[DataType.DT_INT64=9]="DT_INT64",DataType[DataType.DT_BOOL=10]="DT_BOOL",DataType[DataType.DT_QINT8=11]="DT_QINT8",DataType[DataType.DT_QUINT8=12]="DT_QUINT8",DataType[DataType.DT_QINT32=13]="DT_QINT32",DataType[DataType.DT_BFLOAT16=14]="DT_BFLOAT16",DataType[DataType.DT_FLOAT_REF=101]="DT_FLOAT_REF",DataType[DataType.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",DataType[DataType.DT_INT32_REF=103]="DT_INT32_REF",DataType[DataType.DT_UINT8_REF=104]="DT_UINT8_REF",DataType[DataType.DT_INT16_REF=105]="DT_INT16_REF",DataType[DataType.DT_INT8_REF=106]="DT_INT8_REF",DataType[DataType.DT_STRING_REF=107]="DT_STRING_REF",DataType[DataType.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",DataType[DataType.DT_INT64_REF=109]="DT_INT64_REF",DataType[DataType.DT_BOOL_REF=110]="DT_BOOL_REF",DataType[DataType.DT_QINT8_REF=111]="DT_QINT8_REF",DataType[DataType.DT_QUINT8_REF=112]="DT_QUINT8_REF",DataType[DataType.DT_QINT32_REF=113]="DT_QINT32_REF",DataType[DataType.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF"}(exports.DataType||(exports.DataType={})),function(SaverDef){!function(CheckpointFormatVersion){CheckpointFormatVersion[CheckpointFormatVersion.LEGACY=0]="LEGACY",CheckpointFormatVersion[CheckpointFormatVersion.V1=1]="V1",CheckpointFormatVersion[CheckpointFormatVersion.V2=2]="V2"}(SaverDef.CheckpointFormatVersion||(SaverDef.CheckpointFormatVersion={}))}(exports.SaverDef||(exports.SaverDef={}))},{}],9:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var ExecutionContext=function(){function ExecutionContext(weightMap,tensorArrayMap){this.weightMap=weightMap,this.tensorArrayMap=tensorArrayMap,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds()}return ExecutionContext.prototype.newFrame=function(id,frameName){return{id:id,frameName:frameName,iterationId:0}},Object.defineProperty(ExecutionContext.prototype,"currentContext",{get:function(){return this.contexts},set:function(contexts){this.contexts!==contexts&&(this.contexts=contexts,this.generateCurrentContextIds())},enumerable:!0,configurable:!0}),Object.defineProperty(ExecutionContext.prototype,"currentContextId",{get:function(){return this._currentContextIds[0]},enumerable:!0,configurable:!0}),Object.defineProperty(ExecutionContext.prototype,"currentContextIds",{get:function(){return this._currentContextIds},enumerable:!0,configurable:!0}),ExecutionContext.prototype.generateCurrentContextIds=function(){for(var names=[],i=0;i<this.contexts.length-1;i++){var contexts=this.contexts.slice(0,this.contexts.length-i);names.push(this.contextIdforContexts(contexts))}names.push(""),this._currentContextIds=names},ExecutionContext.prototype.contextIdforContexts=function(contexts){return contexts?contexts.map(function(context){return 0===context.id&&0===context.iterationId?"":context.frameName+"-"+context.iterationId}).join("/"):""},ExecutionContext.prototype.enterFrame=function(frameId){this.contexts&&(this.lastId++,this.contexts=this.contexts.slice(),this.contexts.push(this.newFrame(this.lastId,frameId)),this._currentContextIds.unshift(this.contextIdforContexts(this.contexts)))},ExecutionContext.prototype.exitFrame=function(){if(!(this.contexts&&1<this.contexts.length))throw new Error("Cannot exit frame, the context is empty");this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift()},ExecutionContext.prototype.nextIteration=function(){if(!(this.contexts&&0<this.contexts.length))throw new Error("Cannot increase frame iteration, the context is empty");this.contexts=this.contexts.slice(),this.lastId++;var context=Object.assign({},this.contexts[this.contexts.length-1]);context.iterationId+=1,context.id=this.lastId,this.contexts.splice(-1,1,context),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))},ExecutionContext.prototype.getWeight=function(name){return this.weightMap[name]},ExecutionContext.prototype.addTensorArray=function(tensorArray){this.tensorArrayMap[tensorArray.id]=tensorArray},ExecutionContext.prototype.getTensorArray=function(id){return this.tensorArrayMap[id]},ExecutionContext}();exports.ExecutionContext=ExecutionContext},{}],10:[function(require,module,exports){"use strict";var __assign=this&&this.__assign||function(){return(__assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i<n;i++)for(var p in s=arguments[i])Object.prototype.hasOwnProperty.call(s,p)&&(t[p]=s[p]);return t}).apply(this,arguments)},__awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){return new(P=P||Promise)(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):new P(function(resolve){resolve(result.value)}).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})},__generator=this&&this.__generator||function(thisArg,body){var f,y,t,_={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]},g={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return function(op){if(f)throw new TypeError("Generator is already executing.");for(;_;)try{if(f=1,y&&(t=2&op[0]?y.return:op[0]?y.throw||((t=y.return)&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;switch(y=0,t&&(op=[2&op[0],t.value]),op[0]){case 0:case 1:t=op;break;case 4:return _.label++,{value:op[1],done:!1};case 5:_.label++,y=op[1],op=[0];continue;case 7:op=_.ops.pop(),_.trys.pop();continue;default:if(!(t=0<(t=_.trys).length&&t[t.length-1])&&(6===op[0]||2===op[0])){_=0;continue}if(3===op[0]&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(6===op[0]&&_.label<t[1]){_.label=t[1],t=op;break}if(t&&_.label<t[2]){_.label=t[2],_.ops.push(op);break}t[2]&&_.ops.pop(),_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e],y=0}finally{f=t=0}if(5&op[0])throw op[1];return{value:op[0]?op[1]:void 0,done:!0}}([n,v])}}};Object.defineProperty(exports,"__esModule",{value:!0});var tfjs_core_1=require("@tensorflow/tfjs-core"),utils_1=require("../operations/executors/utils"),operation_executor_1=require("../operations/operation_executor"),execution_context_1=require("./execution_context"),model_analysis_1=require("./model_analysis"),GraphExecutor=function(){function GraphExecutor(graph){this.graph=graph,this.compiledMap=new Map,this._weightMap={},this.SEPERATOR=",",this._outputs=graph.outputs,this._inputs=graph.inputs,this._signature=graph.signature}return Object.defineProperty(GraphExecutor.prototype,"weightMap",{get:function(){return this._weightMap},set:function(weightMap){var weightIds=Object.keys(weightMap).map(function(key){return weightMap[key].map(function(tensor){return tensor.id})});this.weightIds=[].concat.apply([],weightIds),this._weightMap=weightMap},enumerable:!0,configurable:!0}),Object.defineProperty(GraphExecutor.prototype,"inputs",{get:function(){return this._inputs.map(function(node){return{name:node.name,shape:node.attrParams.shape?node.attrParams.shape.value:void 0,dtype:node.attrParams.dtype?node.attrParams.dtype.value:void 0}})},enumerable:!0,configurable:!0}),Object.defineProperty(GraphExecutor.prototype,"outputs",{get:function(){return this._outputs.map(function(node){return{name:node.name,shape:node.attrParams.shape?node.attrParams.shape.value:void 0,dtype:node.attrParams.dtype?node.attrParams.dtype.value:void 0}})},enumerable:!0,configurable:!0}),Object.defineProperty(GraphExecutor.prototype,"inputNodes",{get:function(){return this._inputs.map(function(node){return node.signatureKey||node.name})},enumerable:!0,configurable:!0}),Object.defineProperty(GraphExecutor.prototype,"outputNodes",{get:function(){return this._outputs.map(function(node){return node.signatureKey||node.name})},enumerable:!0,configurable:!0}),GraphExecutor.prototype.getCompilationKey=function(inputs,outputs){var sortedInputs=inputs.map(function(node){return node.name}).sort(),sortedOutputs=outputs.map(function(node){return node.name}).sort();return sortedInputs.join(this.SEPERATOR)+"--"+sortedOutputs.join(this.SEPERATOR)},GraphExecutor.prototype.compile=function(inputs,outputs){var executionInfo=model_analysis_1.getExecutionSubgraph(inputs,outputs,this.weightMap),missingInputs=executionInfo.missingInputs,dynamicNode=executionInfo.dynamicNode,syncInputs=executionInfo.syncInputs;if(null!=dynamicNode)throw new Error("This execution contains the node '"+dynamicNode.name+"', which has the dynamic op '"+dynamicNode.op+"'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs ["+syncInputs+"]");if(0<missingInputs.length){var outNames=outputs.map(function(n){return n.name}),inNames=Object.keys(inputs);throw new Error("Cannot compute the outputs ["+outNames+"] from the provided inputs ["+inNames+"]. Missing the following inputs: ["+missingInputs+"]")}return model_analysis_1.getNodesInTopologicalOrder(this.graph,this.weightMap,executionInfo)},GraphExecutor.prototype.execute=function(inputs,outputs){var _this=this;inputs=this.mapInputs(inputs);var names=Object.keys(inputs).sort();this.checkInputs(inputs),this.checkInputShapeAndType(inputs),outputs=this.mapOutputs(outputs),this.checkOutputs(outputs);var inputNodes=names.map(function(name){return _this.graph.nodes[utils_1.parseNodeName(name)[0]]}),outputNodes=outputs.map(function(name){return _this.graph.nodes[utils_1.parseNodeName(name)[0]]}),compilationKey=this.getCompilationKey(inputNodes,outputNodes),orderedNodes=this.compiledMap.get(compilationKey);null==orderedNodes&&(orderedNodes=this.compile(inputs,outputNodes),this.compiledMap.set(compilationKey,orderedNodes));var tensorArrayMap={};return tfjs_core_1.tidy(function(){var context=new execution_context_1.ExecutionContext(_this._weightMap,tensorArrayMap),tensorsMap=__assign({},_this.weightMap);Object.keys(inputs).forEach(function(name){var _a=utils_1.parseNodeName(name),nodeName=_a[0],tensors=[];tensors[_a[1]]=inputs[name],tensorsMap[nodeName]=tensors});for(var tensorsToKeep=_this.getFrozenTensorIds(tensorsMap),intermediateTensorConsumerCount={},i=0;i<orderedNodes.length;i++){var node=orderedNodes[i];if(!tensorsMap[node.name]){var tensors=operation_executor_1.executeOp(node,tensorsMap,context);if(tensors instanceof Promise)throw new Error("The execution of the op '"+node.op+"' returned a promise. Please use model.executeAsync() instead.");tensorsMap[node.name]=tensors,_this.checkTensorForDisposal(node.name,node,tensorsMap,context,tensorsToKeep,outputs,intermediateTensorConsumerCount)}}return outputs.map(function(name){return utils_1.getTensor(name,tensorsMap,context)})})},GraphExecutor.prototype.getFrozenTensorIds=function(tensorMap){var ids=[].concat.apply([],Object.keys(tensorMap).map(function(key){return tensorMap[key]}).map(function(tensors){return tensors.map(function(tensor){return tensor.id})}));return new Set(ids)},GraphExecutor.prototype.checkTensorForDisposal=function(nodeName,node,tensorMap,context,tensorsToKeep,outputNames,intermediateTensorConsumerCount){"control"!==node.category&&-1===outputNames.indexOf(nodeName)&&(tensorMap[nodeName].forEach(function(tensor){null!=tensor&&(intermediateTensorConsumerCount[tensor.id]=(intermediateTensorConsumerCount[tensor.id]||0)+node.children.length)}),node.inputs.forEach(function(input){var tensors;"control"===input.category||null!=(tensors=utils_1.getTensorsForCurrentContenxt(input.name,tensorMap,context))&&tensors.forEach(function(tensor){var count;tensor&&!tensorsToKeep.has(tensor.id)&&(1===(count=intermediateTensorConsumerCount[tensor.id])?(tensor.dispose(),delete intermediateTensorConsumerCount[tensor.id]):null!=count&&intermediateTensorConsumerCount[tensor.id]--)})}))},GraphExecutor.prototype.executeAsync=function(inputs,outputs){return __awaiter(this,void 0,void 0,function(){var tensorArrayMap,context,tensorMap,results,outputIds,inputIds,_this=this;return __generator(this,function(_a){switch(_a.label){case 0:return inputs=this.mapInputs(inputs),this.checkInputs(inputs),this.checkInputShapeAndType(inputs),outputs=this.mapOutputs(outputs),this.checkOutputs(outputs),tensorArrayMap={},context=new execution_context_1.ExecutionContext(this._weightMap,tensorArrayMap),[4,this.executeWithControlFlow(inputs,context,outputs)];case 1:return tensorMap=_a.sent(),results=outputs.map(function(name){return utils_1.getTensor(name,tensorMap,context)}),outputIds=new Set(results.map(function(t){return t.id})),inputIds=new Set(Object.keys(inputs).map(function(name){return inputs[name].id})),Object.keys(tensorMap).forEach(function(key){tensorMap[key].forEach(function(tensor){!tensor||tensor.isDisposed||outputIds.has(tensor.id)||inputIds.has(tensor.id)||-1!==_this.weightIds.indexOf(tensor.id)||tensor.dispose()})}),[2,results]}})})},GraphExecutor.prototype.executeWithControlFlow=function(inputs,context,outputNames){return __awaiter(this,void 0,void 0,function(){var names,inputNodes,outputNodes,_a,usedNodes,missingInputs,dynamicNode,syncInputs,stack,tensorsMap,intermediateTensorConsumerCount,tensorsToKeep,added,promises,missingOutputs,_this=this;return __generator(this,function(_b){switch(_b.label){case 0:names=Object.keys(inputs),inputNodes=names.map(function(name){return _this.graph.nodes[utils_1.parseNodeName(name)[0]]}),outputNodes=outputNames.map(function(name){return _this.graph.nodes[utils_1.parseNodeName(name)[0]]}),_a=model_analysis_1.getExecutionSubgraph(inputs,outputNodes,this.weightMap),usedNodes=_a.usedNodes,missingInputs=_a.missingInputs,dynamicNode=_a.dynamicNode,syncInputs=_a.syncInputs,stack=inputNodes.concat(this.graph.weights).map(function(node){return{node:node,contexts:context.currentContext}}),tensorsMap=__assign({},this.weightMap),Object.keys(inputs).forEach(function(name){var _a=utils_1.parseNodeName(name),nodeName=_a[0],tensors=[];tensors[_a[1]]=inputs[name],tensorsMap[nodeName]=tensors}),intermediateTensorConsumerCount={},tensorsToKeep=this.getFrozenTensorIds(tensorsMap),added={},_b.label=1;case 1:return 0<stack.length?(promises=this.processStack(inputNodes,stack,context,tensorsMap,added,tensorsToKeep,outputNames,intermediateTensorConsumerCount,usedNodes),[4,Promise.all(promises)]):[3,3];case 2:return _b.sent(),[3,1];case 3:if(null==dynamicNode&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead."),0<(missingOutputs=outputNodes.filter(function(node){return!model_analysis_1.isControlFlow(node)&&!utils_1.getTensor(node.name,tensorsMap,context)}).map(function(node){return node.name})).length)throw new Error("Cannot compute the outputs ["+missingOutputs+"] from the provided inputs ["+names+"]. Consider providing the following inputs: ["+missingInputs+"]. "+(null!=dynamicNode?"Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs ["+syncInputs+"]":""));return[2,tensorsMap]}})})},GraphExecutor.prototype.processStack=function(inputNodes,stack,context,tensorMap,added,tensorsToKeep,outputNames,intermediateTensorConsumerCount,usedNodes){for(var _this=this,promises=[],this_1=this;0<stack.length;)!function(){var item=stack.pop();context.currentContext=item.contexts;var tensors,currentContext_1,nodeName="";"Enter"===item.node.op&&utils_1.getParamValue("isConstant",item.node,tensorMap,context)&&(nodeName=utils_1.getNodeNameAndIndex(item.node.name,context)[0]),-1===inputNodes.indexOf(item.node)?(tensors=operation_executor_1.executeOp(item.node,tensorMap,context),nodeName=nodeName||utils_1.getNodeNameAndIndex(item.node.name,context)[0],currentContext_1=context.currentContext,tensors instanceof Promise?promises.push(tensors.then(function(t){return tensorMap[nodeName]=t,context.currentContext=currentContext_1,_this.checkTensorForDisposal(nodeName,item.node,tensorMap,context,tensorsToKeep,outputNames,intermediateTensorConsumerCount),_this.processChildNodes(item.node,stack,context,tensorMap,added,usedNodes),t})):(tensorMap[nodeName]=tensors,this_1.checkTensorForDisposal(nodeName,item.node,tensorMap,context,tensorsToKeep,outputNames,intermediateTensorConsumerCount),this_1.processChildNodes(item.node,stack,context,tensorMap,added,usedNodes))):this_1.processChildNodes(item.node,stack,context,tensorMap,added,usedNodes)}();return promises},GraphExecutor.prototype.processChildNodes=function(node,stack,context,tensorMap,added,usedNodes){node.children.forEach(function(childNode){var nodeName=utils_1.getNodeNameAndIndex(childNode.name,context)[0];!added[nodeName]&&usedNodes.has(childNode.name)&&("Merge"===childNode.op?childNode.inputNames.some(function(name){return!!utils_1.getTensor(name,tensorMap,context)})&&(added[nodeName]=!0,stack.push({contexts:context.currentContext,node:childNode})):childNode.inputNames.every(function(name){return!!utils_1.getTensor(name,tensorMap,context)})&&(added[nodeName]=!0,stack.push({contexts:context.currentContext,node:childNode})))})},GraphExecutor.prototype.dispose=function(){var _this=this;Object.keys(this.weightMap).forEach(function(key){return _this.weightMap[key].forEach(function(tensor){return tensor.dispose()})})},GraphExecutor.prototype.checkInputShapeAndType=function(inputs){var _this=this;Object.keys(inputs).forEach(function(name){var shape_1,match,input=inputs[name],nodeName=utils_1.parseNodeName(name)[0],node=_this.graph.nodes[nodeName];node.attrParams.shape&&node.attrParams.shape.value&&(match=(shape_1=node.attrParams.shape.value).length===input.shape.length&&input.shape.every(function(dim,index){return-1===shape_1[index]||shape_1[index]===dim}),tfjs_core_1.util.assert(match,function(){return"The shape of dict['"+node.name+"'] provided in model.execute(dict) must be ["+shape_1+"], but was ["+input.shape+"]"})),node.attrParams.dtype&&node.attrParams.dtype.value&&tfjs_core_1.util.assert(input.dtype===node.attrParams.dtype.value,function(){return"The dtype of dict['"+node.name+"'] provided in model.execute(dict) must be "+node.attrParams.dtype.value+", but was "+input.dtype})})},GraphExecutor.prototype.mapInputs=function(inputs){var result={};for(var inputName in inputs){null!=this._signature&&null!=this._signature.inputs&&null!=this._signature.inputs[inputName]?result[this._signature.inputs[inputName].name]=inputs[inputName]:result[inputName]=inputs[inputName]}return result},GraphExecutor.prototype.checkInputs=function(inputs){var _this=this,notInGraph=Object.keys(inputs).filter(function(name){var nodeName=utils_1.parseNodeName(name)[0];return null==_this.graph.nodes[nodeName]});if(0<notInGraph.length)throw new Error("The dict provided in model.execute(dict) has keys: ["+notInGraph+"] that are not part of graph")},GraphExecutor.prototype.mapOutputs=function(outputs){var _this=this;return outputs.map(function(name){return null==_this._signature||null==_this._signature.outputs||null==_this._signature.outputs[name]?name:_this._signature.outputs[name].name},{})},GraphExecutor.prototype.checkOutputs=function(outputs){var _this=this;outputs.forEach(function(name){var normalizedName=utils_1.parseNodeName(name)[0];if(!_this.graph.nodes[normalizedName])throw new Error("The output '"+name+"' is not found in the graph")})},GraphExecutor}();exports.GraphExecutor=GraphExecutor},{"../operations/executors/utils":33,"../operations/operation_executor":50,"./execution_context":9,"./model_analysis":12,"@tensorflow/tfjs-core":188}],11:[function(require,module,exports){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){return new(P=P||Promise)(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):new P(function(resolve){resolve(result.value)}).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})},__generator=this&&this.__generator||function(thisArg,body){var f,y,t,_={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]},g={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return function(op){if(f)throw new TypeError("Generator is already executing.");for(;_;)try{if(f=1,y&&(t=2&op[0]?y.return:op[0]?y.throw||((t=y.return)&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;switch(y=0,t&&(op=[2&op[0],t.value]),op[0]){case 0:case 1:t=op;break;case 4:return _.label++,{value:op[1],done:!1};case 5:_.label++,y=op[1],op=[0];continue;case 7:op=_.ops.pop(),_.trys.pop();continue;default:if(!(t=0<(t=_.trys).length&&t[t.length-1])&&(6===op[0]||2===op[0])){_=0;continue}if(3===op[0]&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(6===op[0]&&_.label<t[1]){_.label=t[1],t=op;break}if(t&&_.label<t[2]){_.label=t[2],_.ops.push(op);break}t[2]&&_.ops.pop(),_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e],y=0}finally{f=t=0}if(5&op[0])throw op[1];return{value:op[0]?op[1]:void 0,done:!0}}([n,v])}}};Object.defineProperty(exports,"__esModule",{value:!0});var tfjs_core_1=require("@tensorflow/tfjs-core"),operation_mapper_1=require("../operations/operation_mapper"),graph_executor_1=require("./graph_executor");exports.TFHUB_SEARCH_PARAM="?tfjs-format=file",exports.DEFAULT_MODEL_NAME="model.json";var GraphModel=function(){function GraphModel(modelUrl,loadOptions){void 0===loadOptions&&(loadOptions={}),this.modelUrl=modelUrl,this.loadOptions=loadOptions,this.version="n/a",null==loadOptions&&(this.loadOptions={})}return Object.defineProperty(GraphModel.prototype,"modelVersion",{get:function(){return this.version},enumerable:!0,configurable:!0}),Object.defineProperty(GraphModel.prototype,"inputNodes",{get:function(){return this.executor.inputNodes},enumerable:!0,configurable:!0}),Object.defineProperty(GraphModel.prototype,"outputNodes",{get:function(){return this.executor.outputNodes},enumerable:!0,configurable:!0}),Object.defineProperty(GraphModel.prototype,"inputs",{get:function(){return this.executor.inputs},enumerable:!0,configurable:!0}),Object.defineProperty(GraphModel.prototype,"outputs",{get:function(){return this.executor.outputs},enumerable:!0,configurable:!0}),Object.defineProperty(GraphModel.prototype,"weights",{get:function(){return this.executor.weightMap},enumerable:!0,configurable:!0}),GraphModel.prototype.findIOHandler=function(){var path=this.modelUrl;if(null!=path.load)this.handler=path;else if(null!=this.loadOptions.requestInit)this.handler=tfjs_core_1.io.browserHTTPRequest(path,this.loadOptions);else{var handlers=tfjs_core_1.io.getLoadHandlers(path,this.loadOptions.onProgress);if(0===handlers.length)handlers.push(tfjs_core_1.io.browserHTTPRequest(path,this.loadOptions));else if(1<handlers.length)throw new Error("Found more than one ("+handlers.length+") load handlers for URL '"+[path]+"'");this.handler=handlers[0]}},GraphModel.prototype.load=function(){return __awaiter(this,void 0,void 0,function(){var _a,graph,signature,weightMap;return __generator(this,function(_b){switch(_b.label){case 0:if(this.findIOHandler(),null==this.handler.load)throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");return[4,(_a=this).handler.load()];case 1:return _a.artifacts=_b.sent(),graph=this.artifacts.modelTopology,signature={},null!=this.artifacts.userDefinedMetadata&&(signature=this.artifacts.userDefinedMetadata.signature),this.version=graph.versions.producer+"."+graph.versions.minConsumer,weightMap=tfjs_core_1.io.decodeWeights(this.artifacts.weightData,this.artifacts.weightSpecs),this.executor=new graph_executor_1.GraphExecutor(operation_mapper_1.OperationMapper.Instance.transformGraph(graph,signature)),this.executor.weightMap=this.convertTensorMapToTensorsMap(weightMap),[2,!0]}})})},GraphModel.prototype.save=function(handlerOrURL,config){return __awaiter(this,void 0,void 0,function(){var handlers;return __generator(this,function(_a){if("string"==typeof handlerOrURL){if(0===(handlers=tfjs_core_1.io.getSaveHandlers(handlerOrURL)).length)throw new Error("Cannot find any save handlers for URL '"+handlerOrURL+"'");if(1<handlers.length)throw new Error("Found more than one ("+handlers.length+") save handlers for URL '"+handlerOrURL+"'");handlerOrURL=handlers[0]}if(null==handlerOrURL.save)throw new Error("GraphModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return[2,handlerOrURL.save(this.artifacts)]})})},GraphModel.prototype.predict=function(inputs,config){return this.execute(inputs,this.outputNodes)},GraphModel.prototype.normalizeInputs=function(inputs){if(!(inputs instanceof tfjs_core_1.Tensor||Array.isArray(inputs)))return inputs;if((inputs=Array.isArray(inputs)?inputs:[inputs]).length!==this.inputNodes.length)throw new Error("Input tensor count mismatch,the graph model has "+this.inputNodes.length+" placeholders, while there are "+inputs.length+" input tensors.");return this.inputNodes.reduce(function(map,inputName,i){return map[inputName]=inputs[i],map},{})},GraphModel.prototype.normalizeOutputs=function(outputs){return outputs=outputs||this.outputNodes,Array.isArray(outputs)?outputs:[outputs]},GraphModel.prototype.execute=function(inputs,outputs){inputs=this.normalizeInputs(inputs),outputs=this.normalizeOutputs(outputs);var result=this.executor.execute(inputs,outputs);return 1<result.length?result:result[0]},GraphModel.prototype.executeAsync=function(inputs,outputs){return __awaiter(this,void 0,void 0,function(){var result;return __generator(this,function(_a){switch(_a.label){case 0:return inputs=this.normalizeInputs(inputs),outputs=this.normalizeOutputs(outputs),[4,this.executor.executeAsync(inputs,outputs)];case 1:return[2,1<(result=_a.sent()).length?result:result[0]]}})})},GraphModel.prototype.convertTensorMapToTensorsMap=function(map){return Object.keys(map).reduce(function(newMap,key){return newMap[key]=[map[key]],newMap},{})},GraphModel.prototype.dispose=function(){this.executor.dispose()},GraphModel}();exports.GraphModel=GraphModel,exports.loadGraphModel=function(modelUrl,options){return void 0===options&&(options={}),__awaiter(th