UNPKG

@magenta/music

Version:

Make music with machine learning, in the browser.

311 lines 1.35 MB
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e(require("@tensorflow/tfjs"),require("tone")):"function"==typeof define&&define.amd?define(["tf","Tone"],e):"object"==typeof exports?exports.lib=e(require("@tensorflow/tfjs"),require("tone")):t.lib=e(t.tf,t.Tone)}(self,(function(__WEBPACK_EXTERNAL_MODULE__2__,__WEBPACK_EXTERNAL_MODULE__9__){return function(t){var e={};function n(r){if(e[r])return e[r].exports;var o=e[r]={i:r,l:!1,exports:{}};return t[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=t,n.c=e,n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:r})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var o in t)n.d(r,o,function(e){return t[e]}.bind(null,o));return r},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s=191)}([function(t,e,n){"use strict";n.d(e,"T",(function(){return z.b})),n.d(e,"Fb",(function(){return Tt.a})),n.d(e,"Kb",(function(){return Tt.b})),n.d(e,"W",(function(){return Pt})),n.d(e,"Y",(function(){return $t})),n.d(e,"Z",(function(){return q})),n.d(e,"ab",(function(){return W})),n.d(e,"bb",(function(){return Ft})),n.d(e,"cb",(function(){return Jt})),n.d(e,"db",(function(){return ue})),n.d(e,"eb",(function(){return ce})),n.d(e,"hb",(function(){return he})),n.d(e,"mb",(function(){return de})),n.d(e,"nb",(function(){return pe})),n.d(e,"ob",(function(){return fe})),n.d(e,"pb",(function(){return me})),n.d(e,"rb",(function(){return ge})),n.d(e,"sb",(function(){return be})),n.d(e,"tb",(function(){return we})),n.d(e,"ub",(function(){return Oe})),n.d(e,"xb",(function(){return _t})),n.d(e,"yb",(function(){return Ee})),n.d(e,"zb",(function(){return ke})),n.d(e,"Bb",(function(){return Ae})),n.d(e,"Cb",(function(){return Ne})),n.d(e,"Db",(function(){return Pe})),n.d(e,"Eb",(function(){return _e})),n.d(e,"Gb",(function(){return jt.a})),n.d(e,"Ib",(function(){return Re})),n.d(e,"Mb",(function(){return Fe})),n.d(e,"Nb",(function(){return Ce})),n.d(e,"Ob",(function(){return Le})),n.d(e,"Jb",(function(){return ae})),n.d(e,"ib",(function(){return On})),n.d(e,"Hb",(function(){return En})),n.d(e,"gb",(function(){return kn})),n.d(e,"vb",(function(){return An})),n.d(e,"wb",(function(){return Wn.e})),n.d(e,"jb",(function(){return c.b})),n.d(e,"qb",(function(){return Hn.a})),n.d(e,"kb",(function(){return r})),n.d(e,"Lb",(function(){return At})),n.d(e,"X",(function(){return s})),n.d(e,"Ab",(function(){return o})),n.d(e,"fb",(function(){return Fr})),n.d(e,"lb",(function(){return a})),n.d(e,"w",(function(){return Ur.b})),n.d(e,"k",(function(){return Ur.a})),n.d(e,"a",(function(){return U.a})),n.d(e,"b",(function(){return U.d})),n.d(e,"c",(function(){return U.m})),n.d(e,"d",(function(){return U.o})),n.d(e,"e",(function(){return U.r})),n.d(e,"f",(function(){return U.v})),n.d(e,"g",(function(){return U.w})),n.d(e,"h",(function(){return U.y})),n.d(e,"i",(function(){return U.z})),n.d(e,"j",(function(){return U.G})),n.d(e,"l",(function(){return U.R})),n.d(e,"m",(function(){return U.W})),n.d(e,"n",(function(){return U.X})),n.d(e,"o",(function(){return U.Y})),n.d(e,"p",(function(){return U.ab})),n.d(e,"q",(function(){return U.bb})),n.d(e,"s",(function(){return U.eb})),n.d(e,"u",(function(){return U.jb})),n.d(e,"t",(function(){return U.ib})),n.d(e,"v",(function(){return U.kb})),n.d(e,"x",(function(){return U.sb})),n.d(e,"y",(function(){return U.yb})),n.d(e,"z",(function(){return U.zb})),n.d(e,"A",(function(){return U.Cb})),n.d(e,"B",(function(){return U.Db})),n.d(e,"C",(function(){return U.Fb})),n.d(e,"D",(function(){return U.Ib})),n.d(e,"E",(function(){return U.Kb})),n.d(e,"I",(function(){return U.Pb})),n.d(e,"F",(function(){return U.Mb})),n.d(e,"G",(function(){return U.Nb})),n.d(e,"H",(function(){return U.Ob})),n.d(e,"J",(function(){return U.Xb})),n.d(e,"K",(function(){return U.bc})),n.d(e,"M",(function(){return U.jc})),n.d(e,"O",(function(){return U.qc})),n.d(e,"N",(function(){return U.oc})),n.d(e,"Q",(function(){return U.xc})),n.d(e,"P",(function(){return U.wc})),n.d(e,"R",(function(){return U.Ac})),n.d(e,"S",(function(){return U.Cc})),n.d(e,"U",(function(){return U.Gc})),n.d(e,"V",(function(){return U.Hc})),n.d(e,"r",(function(){return U.db})),n.d(e,"L",(function(){return U.hc}));var r={};n.r(r),n.d(r,"copyModel",(function(){return F})),n.d(r,"listModels",(function(){return D})),n.d(r,"moveModel",(function(){return L})),n.d(r,"removeModel",(function(){return j})),n.d(r,"browserFiles",(function(){return J})),n.d(r,"browserHTTPRequest",(function(){return ut})),n.d(r,"concatenateArrayBuffers",(function(){return l.d})),n.d(r,"decodeWeights",(function(){return l.e})),n.d(r,"encodeWeights",(function(){return l.f})),n.d(r,"fromMemory",(function(){return ht})),n.d(r,"getLoadHandlers",(function(){return m})),n.d(r,"getModelArtifactsInfoForJSON",(function(){return l.g})),n.d(r,"getSaveHandlers",(function(){return f})),n.d(r,"http",(function(){return at})),n.d(r,"isHTTPScheme",(function(){return it})),n.d(r,"loadWeights",(function(){return nt})),n.d(r,"registerLoadRouter",(function(){return p})),n.d(r,"registerSaveRouter",(function(){return d})),n.d(r,"weightsLoaderFactory",(function(){return rt})),n.d(r,"withSaveHandler",(function(){return dt}));var o={};n.r(o),n.d(o,"assertParamsValid",(function(){return pt})),n.d(o,"maskToAxes",(function(){return ft})),n.d(o,"computeOutShape",(function(){return mt})),n.d(o,"stridesWithElidedDims",(function(){return gt})),n.d(o,"getNormalizedAxes",(function(){return vt})),n.d(o,"startIndicesWithElidedDims",(function(){return wt})),n.d(o,"stopIndicesWithElidedDims",(function(){return xt})),n.d(o,"stridesForAxis",(function(){return St})),n.d(o,"startForAxis",(function(){return It})),n.d(o,"stopForAxis",(function(){return Ct})),n.d(o,"isSliceContinous",(function(){return Ot})),n.d(o,"computeFlatOffset",(function(){return Et})),n.d(o,"parseSliceParams",(function(){return kt}));var i={};n.r(i),n.d(i,"segOpComputeOptimalWindowSize",(function(){return _r})),n.d(i,"computeOutShape",(function(){return Rr})),n.d(i,"collectGatherOpShapeInfo",(function(){return $r}));var s={};n.r(s),n.d(s,"axesAreInnerMostDims",(function(){return Zt})),n.d(s,"combineLocations",(function(){return te})),n.d(s,"computeOutAndReduceShapes",(function(){return ee})),n.d(s,"expandShapeToKeepDim",(function(){return ne})),n.d(s,"assertAxesAreInnerMostDims",(function(){return re})),n.d(s,"getAxesPermutation",(function(){return oe})),n.d(s,"getUndoAxesPermutation",(function(){return ie})),n.d(s,"getInnerMostAxes",(function(){return se})),n.d(s,"getBroadcastDims",(function(){return Me})),n.d(s,"getReductionAxes",(function(){return De})),n.d(s,"assertAndGetBroadcastShape",(function(){return je})),n.d(s,"assertParamsConsistent",(function(){return Mt})),n.d(s,"computeOutShape",(function(){return Dt})),n.d(s,"computeDilation2DInfo",(function(){return Lt})),n.d(s,"computePool2DInfo",(function(){return Bt})),n.d(s,"computePool3DInfo",(function(){return zt})),n.d(s,"computeConv2DInfo",(function(){return qt})),n.d(s,"computeConv3DInfo",(function(){return Ut})),n.d(s,"computeDefaultPad",(function(){return Vt})),n.d(s,"tupleValuesAreOne",(function(){return Xt})),n.d(s,"eitherStridesOrDilationsAreOne",(function(){return Qt})),n.d(s,"convertConv2DDataFormat",(function(){return Yt})),n.d(s,"getFusedDyActivation",(function(){return Jn})),n.d(s,"getFusedBiasGradient",(function(){return Zn})),n.d(s,"applyActivation",(function(){return tr})),n.d(s,"shouldFuse",(function(){return er})),n.d(s,"PARALLELIZE_THRESHOLD",(function(){return nr})),n.d(s,"computeOptimalWindowSize",(function(){return rr})),n.d(s,"slice_util",(function(){return o})),n.d(s,"upcastType",(function(){return Tt.b})),n.d(s,"getImageCenter",(function(){return or})),n.d(s,"getReshaped",(function(){return ir})),n.d(s,"getPermuted",(function(){return sr})),n.d(s,"getReshapedPermuted",(function(){return ar})),n.d(s,"getSliceBeginCoords",(function(){return ur})),n.d(s,"getSliceSize",(function(){return cr})),n.d(s,"prepareAndValidate",(function(){return lr})),n.d(s,"validateUpdateShape",(function(){return hr})),n.d(s,"validateInput",(function(){return dr})),n.d(s,"calculateShapes",(function(){return pr})),n.d(s,"SELU_SCALEALPHA",(function(){return fr})),n.d(s,"SELU_SCALE",(function(){return mr})),n.d(s,"ERF_P",(function(){return gr})),n.d(s,"ERF_A1",(function(){return br})),n.d(s,"ERF_A2",(function(){return yr})),n.d(s,"ERF_A3",(function(){return vr})),n.d(s,"ERF_A4",(function(){return wr})),n.d(s,"ERF_A5",(function(){return xr})),n.d(s,"warn",(function(){return Sr})),n.d(s,"log",(function(){return Ir})),n.d(s,"mergeRealAndImagArrays",(function(){return Cr})),n.d(s,"splitRealAndImagArrays",(function(){return Or})),n.d(s,"complexWithEvenIndex",(function(){return Er})),n.d(s,"complexWithOddIndex",(function(){return kr})),n.d(s,"getComplexWithIndex",(function(){return Ar})),n.d(s,"assignToTypedArray",(function(){return Tr})),n.d(s,"exponents",(function(){return Nr})),n.d(s,"exponent",(function(){return Pr})),n.d(s,"prepareSplitSize",(function(){return Te})),n.d(s,"segment_util",(function(){return i})),n.d(s,"castTensor",(function(){return Mr})),n.d(s,"reshapeTensor",(function(){return Dr})),n.d(s,"linspaceImpl",(function(){return jr}));var a={};n.r(a),n.d(a,"nonMaxSuppressionV3Impl",(function(){return nn})),n.d(a,"nonMaxSuppressionV4Impl",(function(){return rn})),n.d(a,"nonMaxSuppressionV5Impl",(function(){return on})),n.d(a,"split",(function(){return Lr})),n.d(a,"tile",(function(){return Br})),n.d(a,"topkImpl",(function(){return zr})),n.d(a,"whereImpl",(function(){return qr}));var u=n(6),c=(n(38),n(11)),l=n(17); /** * @license * Copyright 2018 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ class h{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return null==h.instance&&(h.instance=new h),h.instance}static registerSaveRouter(t){h.getInstance().saveRouters.push(t)}static registerLoadRouter(t){h.getInstance().loadRouters.push(t)}static getSaveHandlers(t){return h.getHandlers(t,"save")}static getLoadHandlers(t,e){return h.getHandlers(t,"load",e)}static getHandlers(t,e,n){const r=[];return("load"===e?h.getInstance().loadRouters:h.getInstance().saveRouters).forEach(e=>{const o=e(t,n);null!==o&&r.push(o)}),r}}const d=t=>h.registerSaveRouter(t),p=t=>h.registerLoadRouter(t),f=t=>h.getSaveHandlers(t),m=(t,e)=>h.getLoadHandlers(t,e) /** * @license * Copyright 2018 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */;function g(){if(!Object(c.b)().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");const t="undefined"==typeof window?self:window,e=t.indexedDB||t.mozIndexedDB||t.webkitIndexedDB||t.msIndexedDB||t.shimIndexedDB;if(null==e)throw new Error("The current browser does not appear to support IndexedDB.");return e}function b(t){const e=t.result;e.createObjectStore("models_store",{keyPath:"modelPath"}),e.createObjectStore("model_info_store",{keyPath:"modelPath"})}class y{constructor(t){if(this.indexedDB=g(),null==t||!t)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=t}async save(t){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return this.databaseAction(this.modelPath,t)}async load(){return this.databaseAction(this.modelPath)}databaseAction(t,e){return new Promise((t,n)=>{const r=this.indexedDB.open("tensorflowjs",1);r.onupgradeneeded=()=>b(r),r.onsuccess=()=>{const o=r.result;if(null==e){const e=o.transaction("models_store","readonly"),r=e.objectStore("models_store").get(this.modelPath);r.onsuccess=()=>{if(null==r.result)return o.close(),n(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));t(r.result.modelArtifacts)},r.onerror=t=>(o.close(),n(r.error)),e.oncomplete=()=>o.close()}else{const r=Object(l.g)(e),i=o.transaction("model_info_store","readwrite");let s=i.objectStore("model_info_store");const a=s.put({modelPath:this.modelPath,modelArtifactsInfo:r});let u;a.onsuccess=()=>{u=o.transaction("models_store","readwrite");const a=u.objectStore("models_store").put({modelPath:this.modelPath,modelArtifacts:e,modelArtifactsInfo:r});a.onsuccess=()=>t({modelArtifactsInfo:r}),a.onerror=t=>{s=i.objectStore("model_info_store");const e=s.delete(this.modelPath);e.onsuccess=()=>(o.close(),n(a.error)),e.onerror=t=>(o.close(),n(a.error))}},a.onerror=t=>(o.close(),n(a.error)),i.oncomplete=()=>{null==u?o.close():u.oncomplete=()=>o.close()}}},r.onerror=t=>n(r.error)})}}y.URL_SCHEME="indexeddb://";const v=t=>{return Object(c.b)().getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(y.URL_SCHEME)?(e=t.slice(y.URL_SCHEME.length),new y(e)):null;var e};h.registerSaveRouter(v),h.registerLoadRouter(v);class w{constructor(){this.indexedDB=g()}async listModels(){return new Promise((t,e)=>{const n=this.indexedDB.open("tensorflowjs",1);n.onupgradeneeded=()=>b(n),n.onsuccess=()=>{const r=n.result,o=r.transaction("model_info_store","readonly"),i=o.objectStore("model_info_store").getAll();i.onsuccess=()=>{const e={};for(const t of i.result)e[t.modelPath]=t.modelArtifactsInfo;t(e)},i.onerror=t=>(r.close(),e(i.error)),o.oncomplete=()=>r.close()},n.onerror=t=>e(n.error)})}async removeModel(t){var e;return t=(e=t).startsWith(y.URL_SCHEME)?e.slice(y.URL_SCHEME.length):e,new Promise((e,n)=>{const r=this.indexedDB.open("tensorflowjs",1);r.onupgradeneeded=()=>b(r),r.onsuccess=()=>{const o=r.result,i=o.transaction("model_info_store","readwrite"),s=i.objectStore("model_info_store"),a=s.get(t);let u;a.onsuccess=()=>{if(null==a.result)return o.close(),n(new Error(`Cannot find model with path '${t}' in IndexedDB.`));{const r=s.delete(t),i=()=>{u=o.transaction("models_store","readwrite");const r=u.objectStore("models_store").delete(t);r.onsuccess=()=>e(a.result.modelArtifactsInfo),r.onerror=t=>n(a.error)};r.onsuccess=i,r.onerror=t=>(i(),o.close(),n(a.error))}},a.onerror=t=>(o.close(),n(a.error)),i.oncomplete=()=>{null==u?o.close():u.oncomplete=()=>o.close()}},r.onerror=t=>n(r.error)})}}var x=n(16); /** * @license * Copyright 2018 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */const S="tensorflowjs_models",I="info",C="model_topology",O="weight_specs",E="weight_data",k="model_metadata";function A(t){return{info:[S,t,I].join("/"),topology:[S,t,C].join("/"),weightSpecs:[S,t,O].join("/"),weightData:[S,t,E].join("/"),modelMetadata:[S,t,k].join("/")}}function T(t){const e=t.split("/");if(e.length<3)throw new Error("Invalid key format: "+t);return e.slice(1,e.length-1).join("/")}class N{constructor(t){if(!Object(c.b)().getBool("IS_BROWSER")||"undefined"==typeof window||void 0===window.localStorage)throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,null==t||!t)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=t,this.keys=A(this.modelPath)}async save(t){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");{const e=JSON.stringify(t.modelTopology),n=JSON.stringify(t.weightSpecs),r=Object(l.g)(t);try{return this.LS.setItem(this.keys.info,JSON.stringify(r)),this.LS.setItem(this.keys.topology,e),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,Object(l.a)(t.weightData)),this.LS.setItem(this.keys.modelMetadata,JSON.stringify({format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,userDefinedMetadata:t.userDefinedMetadata})),{modelArtifactsInfo:r}}catch(t){throw this.LS.removeItem(this.keys.info),this.LS.removeItem(this.keys.topology),this.LS.removeItem(this.keys.weightSpecs),this.LS.removeItem(this.keys.weightData),this.LS.removeItem(this.keys.modelMetadata),new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${r.modelTopologyBytes}, weightSpecsBytes=${r.weightSpecsBytes}, weightDataBytes=${r.weightDataBytes}.`)}}}async load(){const t=JSON.parse(this.LS.getItem(this.keys.info));if(null==t)throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);if("JSON"!==t.modelTopologyType)throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");const e={},n=JSON.parse(this.LS.getItem(this.keys.topology));if(null==n)throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);e.modelTopology=n;const r=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(null==r)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);e.weightSpecs=r;const o=this.LS.getItem(this.keys.modelMetadata);if(null!=o){const t=JSON.parse(o);e.format=t.format,e.generatedBy=t.generatedBy,e.convertedBy=t.convertedBy,e.userDefinedMetadata=t.userDefinedMetadata}const i=this.LS.getItem(this.keys.weightData);if(null==i)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return e.weightData=Object(l.b)(i),e}}N.URL_SCHEME="localstorage://";const P=t=>{return Object(c.b)().getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(N.URL_SCHEME)?(e=t.slice(N.URL_SCHEME.length),new N(e)):null;var e};h.registerSaveRouter(P),h.registerLoadRouter(P);class _{constructor(){Object(x.b)(Object(c.b)().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),Object(x.b)("undefined"==typeof window||void 0!==window.localStorage,()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){const t={},e=S+"/",n="/"+I;for(let r=0;r<this.LS.length;++r){const o=this.LS.key(r);if(o.startsWith(e)&&o.endsWith(n)){t[T(o)]=JSON.parse(this.LS.getItem(o))}}return t}async removeModel(t){var e;const n=A(t=(e=t).startsWith(N.URL_SCHEME)?e.slice(N.URL_SCHEME.length):e);if(null==this.LS.getItem(n.info))throw new Error(`Cannot find model at path '${t}'`);const r=JSON.parse(this.LS.getItem(n.info));return this.LS.removeItem(n.info),this.LS.removeItem(n.topology),this.LS.removeItem(n.weightSpecs),this.LS.removeItem(n.weightData),r}} /** * @license * Copyright 2018 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */class R{constructor(){this.managers={}}static getInstance(){return null==R.instance&&(R.instance=new R),R.instance}static registerManager(t,e){Object(x.b)(null!=t,()=>"scheme must not be undefined or null."),t.endsWith("://")&&(t=t.slice(0,t.indexOf("://"))),Object(x.b)(t.length>0,()=>"scheme must not be an empty string.");const n=R.getInstance();Object(x.b)(null==n.managers[t],()=>`A model store manager is already registered for scheme '${t}'.`),n.managers[t]=e}static getManager(t){const e=this.getInstance().managers[t];if(null==e)throw new Error(`Cannot find model manager for scheme '${t}'`);return e}static getSchemes(){return Object.keys(this.getInstance().managers)}}function $(t){if(-1===t.indexOf("://"))throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+R.getSchemes().join(","));return{scheme:t.split("://")[0],path:t.split("://")[1]}}async function M(t,e,n=!1){Object(x.b)(t!==e,()=>`Old path and new path are the same: '${t}'`);const r=h.getLoadHandlers(t);Object(x.b)(r.length>0,()=>`Copying failed because no load handler is found for source URL ${t}.`),Object(x.b)(r.length<2,()=>`Copying failed because more than one (${r.length}) load handlers for source URL ${t}.`);const o=r[0],i=h.getSaveHandlers(e);Object(x.b)(i.length>0,()=>`Copying failed because no save handler is found for destination URL ${e}.`),Object(x.b)(i.length<2,()=>`Copying failed because more than one (${r.length}) save handlers for destination URL ${e}.`);const s=i[0],a=$(t).scheme,u=$(t).path,c=a===$(t).scheme,l=await o.load();n&&c&&await R.getManager(a).removeModel(u);const d=await s.save(l);return n&&!c&&await R.getManager(a).removeModel(u),d.modelArtifactsInfo}async function D(){const t=R.getSchemes(),e={};for(const n of t){const t=await R.getManager(n).listModels();for(const r in t){e[n+"://"+r]=t[r]}}return e}async function j(t){const e=$(t);return R.getManager(e.scheme).removeModel(e.path)}async function F(t,e){return M(t,e,!1)}async function L(t,e){return M(t,e,!0)} /** * @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */class B{fetch(t,e){return fetch(t,e)}now(){return performance.now()}encode(t,e){if("utf-8"!==e&&"utf8"!==e)throw new Error("Browser's encoder only supports utf-8, but got "+e);return null==this.textEncoder&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(t)}decode(t,e){return new TextDecoder(e).decode(t)}}if(Object(c.b)().get("IS_BROWSER")){Object(c.b)().setPlatform("browser",new B);try{R.registerManager(N.URL_SCHEME,new _)}catch(t){}try{R.registerManager(y.URL_SCHEME,new w)}catch(t){}}n(159);var z=n(5); /** * @license * Copyright 2020 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ function q(t,e="float32",n){return e=e||"float32",x.c(t),new z.b(t,e,n)}var U=n(1),V=n(3),G=n(4);const W=Object(G.a)({cast_: /** * @license * Copyright 2020 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ function(t,e){const n=Object(V.a)(t,"x","cast");if(!x.B(e))throw new Error("Failed to cast to unknown dtype "+e);if("string"===e&&"string"!==n.dtype||"string"!==e&&"string"===n.dtype)throw new Error("Only strings can be casted to strings");const r={x:n},o={dtype:e};return u.a.runKernelFunc(t=>t.cast(n,e),r,null,U.v,o)}}); /** * @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */const H=Object(G.a)({clone_:function(t){const e=Object(V.a)(t,"x","clone",null),n={x:e};return u.a.runKernelFunc(()=>u.a.makeTensorFromDataId(e.dataId,e.shape,e.dtype),n,null,U.jb)}}); /** * @license * Copyright 2020 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ /** * @license * Copyright 2020 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ Object(u.b)();const K={buffer:q,cast:W,clone:H,print:function(t,e=!1){console.log(t.toString(e))}};Object(z.e)(K);function X(t){return new Promise(t=>setTimeout(t)).then(t)}class Q{constructor(t){if(!Object(c.b)().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");t.startsWith(Q.URL_SCHEME)&&(t=t.slice(Q.URL_SCHEME.length)),null!=t&&0!==t.length||(t="model"),this.modelTopologyFileName=t+".json",this.weightDataFileName=t+".weights.bin"}async save(t){if("undefined"==typeof document)throw new Error("Browser downloads are not supported in this environment since `document` is not present");const e=window.URL.createObjectURL(new Blob([t.weightData],{type:"application/octet-stream"}));if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");{const n=[{paths:["./"+this.weightDataFileName],weights:t.weightSpecs}],r={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,weightsManifest:n},o=window.URL.createObjectURL(new Blob([JSON.stringify(r)],{type:"application/json"})),i=null==this.jsonAnchor?document.createElement("a"):this.jsonAnchor;if(i.download=this.modelTopologyFileName,i.href=o,await X(()=>i.dispatchEvent(new MouseEvent("click"))),null!=t.weightData){const t=null==this.weightDataAnchor?document.createElement("a"):this.weightDataAnchor;t.download=this.weightDataFileName,t.href=e,await X(()=>t.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:Object(l.g)(t)}}}}Q.URL_SCHEME="downloads://";class Y{constructor(t){if(null==t||t.length<1)throw new Error("When calling browserFiles, at least 1 file is required, but received "+t);this.files=t}async load(){const t=this.files[0],e=this.files.slice(1);return new Promise((n,r)=>{const o=new FileReader;o.onload=o=>{const i=JSON.parse(o.target.result),s=i.modelTopology;if(null==s)return void r(new Error("modelTopology field is missing from file "+t.name));0===e.length&&n({modelTopology:s});const a=i.weightsManifest;if(null==a)return void r(new Error("weightManifest field is missing from file "+t.name));let u;try{u=this.checkManifestAndWeightFiles(a,e)}catch(t){return void r(t)}const c=[],h=[],d=[];a.forEach(t=>{t.paths.forEach(t=>{h.push(t),d.push(null)}),c.push(...t.weights)}),a.forEach(t=>{t.paths.forEach(t=>{const e=new FileReader;e.onload=e=>{const r=e.target.result,o=h.indexOf(t);d[o]=r,-1===d.indexOf(null)&&n({modelTopology:s,weightSpecs:c,weightData:Object(l.d)(d),format:i.format,generatedBy:i.generatedBy,convertedBy:i.convertedBy,userDefinedMetadata:i.userDefinedMetadata})},e.onerror=e=>r(`Failed to weights data from file of path '${t}'.`),e.readAsArrayBuffer(u[t])})})},o.onerror=e=>r(`Failed to read model topology and weights manifest JSON from file '${t.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),o.readAsText(t)})}checkManifestAndWeightFiles(t,e){const n=[],r=e.map(t=>Object(l.c)(t.name)),o={};for(const i of t)i.paths.forEach(t=>{const i=Object(l.c)(t);if(-1!==n.indexOf(i))throw new Error(`Duplicate file basename found in weights manifest: '${i}'`);if(n.push(i),-1===r.indexOf(i))throw new Error(`Weight file with basename '${i}' is not provided.`);o[t]=e[r.indexOf(i)]});if(n.length!==e.length)throw new Error(`Mismatch in the number of files in weights manifest (${n.length}) and the number of weight files provided (${e.length}).`);return o}}function J(t){return new Y(t)} /** * @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */function Z(t,e,n,r){!function(t){Object(x.b)(null!=t&&Array.isArray(t)&&t.length>0,()=>"promises must be a none empty array")}(t),function(t,e){Object(x.b)(t>=0&&t<=1,()=>"Progress fraction must be in range [0, 1], but got startFraction "+t),Object(x.b)(e>=0&&e<=1,()=>"Progress fraction must be in range [0, 1], but got endFraction "+e),Object(x.b)(e>=t,()=>`startFraction must be no more than endFraction, but got startFraction ${t} and endFraction `+e)}(n=null==n?0:n,r=null==r?1:r);let o=0;return Promise.all(t.map(i=>(i.then(i=>{const s=n+ ++o/t.length*(r-n);return e(s),i}),i)))}h.registerSaveRouter(t=>Object(c.b)().getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(Q.URL_SCHEME)?function(t="model"){return new Q(t)}(t.slice(Q.URL_SCHEME.length)):null);var tt=n(41); /** * @license * Copyright 2018 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */async function et(t,e){null==e&&(e={});const n=null==e.fetchFunc?Object(c.b)().platform.fetch:e.fetchFunc,r=t.map(t=>n(t,e.requestInit,{isBinary:!0})),o=(null==e.onProgress?await Promise.all(r):await Z(r,e.onProgress,0,.5)).map(t=>t.arrayBuffer());return null==e.onProgress?await Promise.all(o):await Z(o,e.onProgress,.5,1)}async function nt(t,e="",n,r){return rt(t=>et(t,{requestInit:r}))(t,e,n)}function rt(t){return async(e,n="",r)=>{const o=e.map(()=>!1),i={},s=null!=r?r.map(()=>!1):[],a=[];if(e.forEach((t,e)=>{let n=0;t.weights.forEach(t=>{const u="quantization"in t?t.quantization.dtype:t.dtype,c=tt.a[u]*x.N(t.shape),l=()=>{o[e]=!0,null==i[e]&&(i[e]=[]),i[e].push({manifestEntry:t,groupOffset:n,sizeBytes:c})};null!=r?r.forEach((e,n)=>{e===t.name&&(l(),s[n]=!0)}):l(),a.push(t.name),n+=c})}),!s.every(t=>t)){const t=r.filter((t,e)=>!s[e]);throw new Error("Could not find weights in manifest with names: "+t.join(", ")+". \nManifest JSON has weights with names: "+a.join(", ")+".")}const u=o.reduce((t,e,n)=>(e&&t.push(n),t),[]),c=[];u.forEach(t=>{e[t].paths.forEach(t=>{const e=n+(n.endsWith("/")?"":"/")+t;c.push(e)})});const h=await t(c),d={};let p=0;return u.forEach(t=>{const n=e[t].paths.length;let r=0;for(let t=0;t<n;t++)r+=h[p+t].byteLength;const o=new ArrayBuffer(r),s=new Uint8Array(o);let a=0;for(let t=0;t<n;t++){const e=new Uint8Array(h[p+t]);s.set(e,a),a+=e.byteLength}i[t].forEach(t=>{const e=o.slice(t.groupOffset,t.groupOffset+t.sizeBytes),n=Object(l.e)(e,[t.manifestEntry]);for(const t in n)d[t]=n[t]}),p+=n}),d}} /** * @license * Copyright 2018 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */class ot{constructor(t,e){if(this.DEFAULT_METHOD="POST",null==e&&(e={}),this.weightPathPrefix=e.weightPathPrefix,this.onProgress=e.onProgress,this.weightUrlConverter=e.weightUrlConverter,null!=e.fetchFunc?(Object(x.b)("function"==typeof e.fetchFunc,()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"),this.fetch=e.fetchFunc):this.fetch=Object(c.b)().platform.fetch,Object(x.b)(null!=t&&t.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(t)&&Object(x.b)(2===t.length,()=>`URL paths for http must have a length of 2, (actual length is ${t.length}).`),this.path=t,null!=e.requestInit&&null!=e.requestInit.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=e.requestInit||{}}async save(t){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");const e=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);e.body=new FormData;const n=[{paths:["./model.weights.bin"],weights:t.weightSpecs}],r={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,userDefinedMetadata:t.userDefinedMetadata,weightsManifest:n};e.body.append("model.json",new Blob([JSON.stringify(r)],{type:"application/json"}),"model.json"),null!=t.weightData&&e.body.append("model.weights.bin",new Blob([t.weightData],{type:"application/octet-stream"}),"model.weights.bin");const o=await this.fetch(this.path,e);if(o.ok)return{modelArtifactsInfo:Object(l.g)(t),responses:[o]};throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+o.status+".")}async load(){const t=await this.fetch(this.path,this.requestInit);if(!t.ok)throw new Error(`Request to ${this.path} failed with status code `+t.status+". Please verify this URL points to the model JSON of the model to load.");let e;try{e=await t.json()}catch(t){let e=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?e+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":e+=" Please make sure the server is serving valid JSON for this request.",new Error(e)}const n=e.modelTopology,r=e.weightsManifest,o=e.generatedBy,i=e.convertedBy,s=e.format,a=e.userDefinedMetadata;if(null==n&&null==r)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);let u,c;if(null!=r){const t=await this.loadWeights(r);[u,c]=t}const l={modelTopology:n,weightSpecs:u,weightData:c,userDefinedMetadata:a,generatedBy:o,convertedBy:i,format:s},h=e.modelInitializer;return h&&(l.modelInitializer=h),l}async loadWeights(t){const e=Array.isArray(this.path)?this.path[1]:this.path,[n,r]=function(t){const e=t.lastIndexOf("/"),n=t.lastIndexOf("?"),r=t.substring(0,e),o=n>e?t.substring(n):"";return[r+"/",o]}(e),o=this.weightPathPrefix||n,i=[];for(const e of t)i.push(...e.weights);const s=[],a=[];for(const e of t)for(const t of e.paths)null!=this.weightUrlConverter?a.push(this.weightUrlConverter(t)):s.push(o+t+r);this.weightUrlConverter&&s.push(...await Promise.all(a));const u=await et(s,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[i,Object(l.d)(u)]}}function it(t){return null!=t.match(ot.URL_SCHEME_REGEX)}ot.URL_SCHEME_REGEX=/^https?:\/\//;const st=(t,e)=>{if("undefined"==typeof fetch&&(null==e||null==e.fetchFunc))return null;{let n=!0;if(n=Array.isArray(t)?t.every(t=>it(t)):it(t),n)return at(t,e)}return null};function at(t,e){return new ot(t,e)}function ut(t,e){return at(t,e)} /** * @license * Copyright 2018 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */h.registerSaveRouter(st),h.registerLoadRouter(st);class ct{constructor(t){this.modelArtifacts=t}async load(){return this.modelArtifacts}}class lt{constructor(t){this.saveHandler=t}async save(t){return this.saveHandler(t)}}function ht(t,e,n,r){if(1===arguments.length){return null!=t.modelTopology||null!=t.weightSpecs?new ct(t):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new ct({modelTopology:t}))}return console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new ct({modelTopology:t,weightSpecs:e,weightData:n,trainingConfig:r})}function dt(t){return new lt(t)} /** * @license * Copyright 2018 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ /** * @license * Copyright 2017 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */function pt(t,e,n){const r=t.shape.length;x.b(r===e.length,()=>`Error in slice${r}D: Length of begin ${e} must match the rank of the array (${r}).`),x.b(r===n.length,()=>`Error in slice${r}D: Length of size ${n} must match the rank of the array (${r}).`);for(let o=0;o<r;++o)x.b(e[o]+n[o]<=t.shape[o],()=>`Error in slice${r}D: begin[${o}] + size[${o}] (${e[o]+n[o]}) would overflow input.shape[${o}] (${t.shape[o]})`)}function ft(t){const e=[];let n=0;for(;t>0;)1&t&&e.push(n),t/=2,n++;return e}function mt(t,e,n){const r=[];for(let o=0;o<t.length;o++)r[o]=Math.ceil((e[o]-t[o])/n[o]);return r}function gt(t,e,n,r){const o=[...t];for(let t=o.length;t<r.length;t++)o.push(1);for(let t=0;t<n;t++)0===t?o[e]=1:(o.splice(e,0,1),o.pop());return o}function bt(t,e,n){return n<=t?n:n-(e-1)}function yt(t,e){const n=[];for(let r=0;r<t;r++)n.push(e+r);return n}function vt(t,e,n,r,o,i,s,a,u){const c=t.length;let l=new Array(c),h=new Array(c),d=new Array(c);if(e.length&&n>0){const u=e[0],c=n+1;l=wt(s,u,c,r,t),h=xt(a,u,c,o,t),d=gt(i,u,c,t)}else for(let e=0;e<c;e++)l[e]=It(s,r,i,t,e,u),h[e]=Ct(a,o,i,t,e,u),d[e]=St(i,e,u);return{begin:l,end:h,strides:d}}function wt(t,e,n,r,o){const i=[...o],s=yt(n,e);for(let o=0;o<i.length;o++)if(s.indexOf(o)>-1)i[o]=0;else{const s=bt(e,n,o);let a=r[s];t&1<<s&&(a=0),i[o]=a}return i}function xt(t,e,n,r,o){const i=[...o],s=yt(n,e);for(let o=0;o<i.length;o++)if(s.indexOf(o)>-1)i[o]=Number.MAX_SAFE_INTEGER;else{const s=bt(e,n,o);let a=r[s];t&1<<s&&(a=Number.MAX_SAFE_INTEGER),i[o]=a}for(let t=0;t<i.length;t++){const e=o[t];i[t]<0&&(i[t]+=e),i[t]=x.i(0,i[t],o[t])}return i}function St(t,e,n){let r=t[e];return(n&1<<e||null==r)&&(r=1),r}function It(t,e,n,r,o,i){let s=e[o];const a=n[o]||1;(t&1<<o||i&1<<o||null==s)&&(s=a>0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);const u=r[o];return s<0&&(s+=u),s=x.i(0,s,u-1),s}function Ct(t,e,n,r,o,i){let s=e[o];const a=n[o]||1;(t&1<<o||i&1<<o||null==s)&&(s=a>0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);const u=r[o];return s<0&&(s+=u),s=a>0?x.i(0,s,u):x.i(-1,s,u-1),s}function Ot(t,e,n){let r=n.length;for(let t=0;t<n.length;t++)if(n[t]>1){r=t;break}for(let o=r+1;o<n.length;o++)if(e[o]>0||n[o]!==t[o])return!1;return!0}function Et(t,e){let n=t.length>0?t[t.length-1]:1;for(let r=0;r<t.length-1;r++)n+=t[r]*e[r];return n}function kt(t,e,n){let r;const o=t.shape.length;let i;return r="number"==typeof e?[e,...new Array(o-1).fill(0)]:e.length<o?e.concat(new Array(o-e.length).fill(0)):e.slice(),r.forEach(t=>{x.b(-1!==t,()=>"slice() does not support negative begin indexing.")}),i=null==n?new Array(o).fill(-1):"number"==typeof n?[n,...new Array(o-1).fill(-1)]:n.length<o?n.concat(new Array(o-n.length).fill(-1)):n,i=i.map((e,n)=>e>=0?e:(x.b(-1===e,()=>`Negative size values should be exactly -1 but got ${e} for the slice() size at index ${n}.`),t.shape[n]-r[n])),[r,i]}var At=n(7),Tt=n(27),Nt=n(14);const Pt=Object(G.a)({add_: /** * @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ function(t,e){let n=Object(V.a)(t,"a","add"),r=Object(V.a)(e,"b","add");[n,r]=Object(Nt.b)(n,r);const o={a:n,b:r};return u.a.runKernelFunc((t,e)=>{const o=t.add(n,r);return e([n,r]),o},o,null,U.d)}}); /** * @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */const _t=Object(G.a)({reshape_:function(t,e){const n=Object(V.a)(t,"x","reshape",null),r={x:n},o={shape:e};return u.a.runKernelFunc((t,r)=>(e=x.s(e,n.size),x.b(n.size===x.N(e),()=>"new shape and old shape must have the same number of elements."),r([n]),t.reshape(n,e)),r,null,U.bc,o)}});function Rt(t){return null==t?null:0===t.rank?_t(t,[t.size]):1===t.rank?t:2===t.rank?_t(t,[1,1,t.shape[0],t.shape[1]]):3===t.rank?_t(t,[1,t.shape[0],t.shape[1],t.shape[2]]):t}const $t=Object(G.a)({batchNorm_: /** * @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ function(t,e,n,r,o,i){null==i&&(i=.001);const s=Object(V.a)(t,"x","batchNorm"),a=Object(V.a)(e,"mean","batchNorm"),c=Object(V.a)(n,"variance","batchNorm");let l,h;null!=o&&(l=Object(V.a)(o,"scale","batchNorm")),null!=r&&(h=Object(V.a)(r,"offset","batchNorm")),x.b(a.rank===c.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),x.b(null==h||a.rank===h.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),x.b(null==l||a.rank===l.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");const d=function(t){let e;return e=0===t.rank||1===t.rank?_t(t,[1,1,1,t.size]):2===t.rank?_t(t,[1,1,t.shape[0],t.shape[1]]):3===t.rank?_t(t,[1,t.shape[