diff --git a/docs/compiled/artplayer-plugin-ads.mjs b/docs/compiled/artplayer-plugin-ads.mjs index b2c413ed7..b5132a64f 100644 --- a/docs/compiled/artplayer-plugin-ads.mjs +++ b/docs/compiled/artplayer-plugin-ads.mjs @@ -4,4 +4,248 @@ * (c) 2017-2026 Harvey Zhao * Released under the MIT License. */ -function l(e){return n=>{!function(e){const{version:n,utils:{errorHandle:a}}=e.constructor,i=n.split(".").map(Number);a(i[0]+i[1]/100>=5,`Artplayer.js@${n} is not compatible the artplayerPluginAds@${l.version}. Please update it to version Artplayer.js@5.x.x`)}(n);const{template:{$player:a},icons:{volume:i,volumeClose:t,fullscreenOn:r,fullscreenOff:d,loading:o},constructor:{validator:s,utils:{query:p,append:u,setStyle:c}}}=n;e=s({html:"",video:"",url:"",playDuration:5,totalDuration:10,muted:!1,i18n:{close:"\u5173\u95ed\u5e7f\u544a",countdown:"%s\u79d2",detail:"\u67e5\u770b\u8be6\u60c5",canBeClosed:"%s\u79d2\u540e\u53ef\u5173\u95ed\u5e7f\u544a"},...e},{html:"?string",video:"?string",url:"?string",playDuration:"number",totalDuration:"number",muted:"?boolean",i18n:{close:"string",countdown:"string",detail:"string",canBeClosed:"string"}});let y=null,g=null,m=null,f=null,v=null,x=null,h=0,b=null,w=!1,$=!1,k=!1;function D(l,e){return e.replace("%s",l)}function A(){w=!0,n.play(),e.video&&y.pause(),c(n.template.$ads,"display","none"),n.emit("artplayerPluginAds:skip",e)}function C(){w||(b=setTimeout(()=>{h+=1;const l=e.playDuration-h;l>=1?m.innerHTML=D(l,e.i18n.canBeClosed):(m.innerHTML=e.i18n.close,k||(k=!0)),f.innerHTML=D(e.totalDuration-h,e.i18n.countdown),h>=e.totalDuration?A():C()},1e3))}function P(){w||clearTimeout(b)}function B(){$||($=!0,function(){n.template.$ads=u(a,'
'),y=u(n.template.$ads,e.video?``:`
${e.html}
`),x=u(n.template.$ads,'
'),u(x,o),g=u(n.template.$ads,`
\n
${e.playDuration<=0?e.i18n.close:D(e.playDuration,e.i18n.canBeClosed)}
\n
${D(e.totalDuration,e.i18n.countdown)}
\n
`),m=p(".artplayer-plugin-ads-close",g),f=p(".artplayer-plugin-ads-countdown",g),e.playDuration>=e.totalDuration&&c(m,"display","none"),n.proxy(m,"click",()=>{k&&A()}),v=u(n.template.$ads,`
\n
${e.i18n.detail}
\n
\n
\n
`);const l=p(".artplayer-plugin-ads-detail",v),s=p(".artplayer-plugin-ads-muted",v),h=p(".artplayer-plugin-ads-fullscreen",v);if(e.url?n.proxy(l,"click",()=>{window.open(e.url),n.emit("artplayerPluginAds:click",e)}):c(l,"display","none"),e.video){const l=u(s,i),a=u(s,t);c(a,"display","none"),e.muted&&(y.muted=!0,c(l,"display","none"),c(a,"display","inline-flex")),n.proxy(s,"click",()=>{y.muted=!y.muted,y.muted?(c(l,"display","none"),c(a,"display","inline-flex")):(c(l,"display","inline-flex"),c(a,"display","none"))})}else c(s,"display","none");const b=u(h,r),w=u(h,d);c(w,"display","none"),n.proxy(h,"click",()=>{n.fullscreen=!n.fullscreen,n.fullscreen?(c(b,"display","inline-flex"),c(w,"display","none")):(c(b,"display","none"),c(w,"display","inline-flex"))}),n.proxy(y,"click",()=>{e.url&&window.open(e.url),n.emit("artplayerPluginAds:click",e)})}(),n.pause(),e.video?(n.proxy(y,"error",A),n.proxy(y,"loadedmetadata",()=>{C(),y.play(),c(g,"display","flex"),c(v,"display","flex"),c(x,"display","none")})):(C(),c(g,"display","flex"),c(v,"display","flex"),c(x,"display","none")),n.on("document:visibilitychange",()=>{document.hidden?P():C()}))}return n.on("ready",()=>{n.once("play",B),n.once("video:playing",B)}),{name:"artplayerPluginAds",skip:A,pause:P,play:C}}}if("undefined"!==typeof document&&!document.getElementById("artplayer-plugin-ads")){const l=document.createElement("style");l.id="artplayer-plugin-ads",l.textContent=".artplayer-plugin-ads{position:absolute;z-index:150;inset:0;width:100%;height:100%;overflow:hidden;font-size:13px;line-height:1;color:#fff;background-color:#000}.artplayer-plugin-ads .artplayer-plugin-ads-html{display:flex;align-items:center;justify-content:center;width:100%;height:100%}.artplayer-plugin-ads .artplayer-plugin-ads-video{width:100%;height:100%}.artplayer-plugin-ads .artplayer-plugin-ads-timer{display:none;position:absolute;top:10px;right:10px}.artplayer-plugin-ads .artplayer-plugin-ads-timer>div{display:flex;align-items:center;background-color:#00000080;border-radius:15px;margin-left:5px;padding:5px 10px;cursor:pointer}.artplayer-plugin-ads .artplayer-plugin-ads-control{display:none;position:absolute;bottom:10px;right:10px}.artplayer-plugin-ads .artplayer-plugin-ads-control>div{display:flex;align-items:center;background-color:#00000080;border-radius:15px;margin-left:5px;padding:5px 10px;cursor:pointer}.artplayer-plugin-ads .artplayer-plugin-ads-control .art-icon svg{width:20px;height:20px}.artplayer-plugin-ads .artplayer-plugin-ads-loading{display:flex;align-items:center;justify-content:center;position:absolute;inset:0;width:100%;height:100%}",document.head.appendChild(l)}export{l as default}; +const style = ".artplayer-plugin-ads {\n position: absolute;\n z-index: 150;\n left: 0;\n top: 0;\n right: 0;\n bottom: 0;\n width: 100%;\n height: 100%;\n overflow: hidden;\n font-size: 13px;\n line-height: 1;\n color: #fff;\n background-color: #000;\n}\n.artplayer-plugin-ads .artplayer-plugin-ads-html {\n display: flex;\n align-items: center;\n justify-content: center;\n width: 100%;\n height: 100%;\n}\n.artplayer-plugin-ads .artplayer-plugin-ads-video {\n width: 100%;\n height: 100%;\n}\n.artplayer-plugin-ads .artplayer-plugin-ads-timer {\n display: none;\n position: absolute;\n top: 10px;\n right: 10px;\n}\n.artplayer-plugin-ads .artplayer-plugin-ads-timer > div {\n display: flex;\n align-items: center;\n background-color: rgba(0, 0, 0, 0.5);\n border-radius: 15px;\n margin-left: 5px;\n padding: 5px 10px;\n cursor: pointer;\n}\n.artplayer-plugin-ads .artplayer-plugin-ads-control {\n display: none;\n position: absolute;\n bottom: 10px;\n right: 10px;\n}\n.artplayer-plugin-ads .artplayer-plugin-ads-control > div {\n display: flex;\n align-items: center;\n background-color: rgba(0, 0, 0, 0.5);\n border-radius: 15px;\n margin-left: 5px;\n padding: 5px 10px;\n cursor: pointer;\n}\n.artplayer-plugin-ads .artplayer-plugin-ads-control .art-icon svg {\n width: 20px;\n height: 20px;\n}\n.artplayer-plugin-ads .artplayer-plugin-ads-loading {\n display: flex;\n align-items: center;\n justify-content: center;\n position: absolute;\n left: 0;\n top: 0;\n right: 0;\n bottom: 0;\n width: 100%;\n height: 100%;\n}\n"; +function checkVersion(art) { + const { + version, + utils: { errorHandle } + } = art.constructor; + const arr = version.split(".").map(Number); + const major = arr[0]; + const minor = arr[1] / 100; + errorHandle( + major + minor >= 5, + `Artplayer.js@${version} is not compatible the artplayerPluginAds@${artplayerPluginAds.version}. Please update it to version Artplayer.js@5.x.x` + ); +} +function artplayerPluginAds(option) { + return (art) => { + checkVersion(art); + const { + template: { $player }, + icons: { volume, volumeClose, fullscreenOn, fullscreenOff, loading }, + constructor: { + validator, + utils: { query, append, setStyle } + } + } = art; + option = validator( + { + html: "", + video: "", + url: "", + playDuration: 5, + totalDuration: 10, + muted: false, + i18n: { + close: "关闭广告", + countdown: "%s秒", + detail: "查看详情", + canBeClosed: "%s秒后可关闭广告" + }, + ...option + }, + { + html: "?string", + video: "?string", + url: "?string", + playDuration: "number", + totalDuration: "number", + muted: "?boolean", + i18n: { + close: "string", + countdown: "string", + detail: "string", + canBeClosed: "string" + } + } + ); + let $ads = null; + let $timer = null; + let $close = null; + let $countdown = null; + let $control = null; + let $loading = null; + let time = 0; + let timer = null; + let isEnd = false; + let isInit = false; + let isCanClose = false; + function getI18n(val, str) { + return str.replace("%s", val); + } + function skip() { + isEnd = true; + art.play(); + if (option.video) + $ads.pause(); + setStyle(art.template.$ads, "display", "none"); + art.emit("artplayerPluginAds:skip", option); + } + function play() { + if (isEnd) + return; + timer = setTimeout(() => { + time += 1; + const playDuration = option.playDuration - time; + if (playDuration >= 1) { + $close.innerHTML = getI18n(playDuration, option.i18n.canBeClosed); + } else { + $close.innerHTML = option.i18n.close; + if (!isCanClose) { + isCanClose = true; + } + } + $countdown.innerHTML = getI18n(option.totalDuration - time, option.i18n.countdown); + if (time >= option.totalDuration) { + skip(); + } else { + play(); + } + }, 1e3); + } + function pause() { + if (isEnd) + return; + clearTimeout(timer); + } + function show() { + art.template.$ads = append($player, '
'); + $ads = append( + art.template.$ads, + option.video ? `` : `
${option.html}
` + ); + $loading = append(art.template.$ads, '
'); + append($loading, loading); + $timer = append( + art.template.$ads, + `
+
${option.playDuration <= 0 ? option.i18n.close : getI18n(option.playDuration, option.i18n.canBeClosed)}
+
${getI18n( + option.totalDuration, + option.i18n.countdown + )}
+
` + ); + $close = query(".artplayer-plugin-ads-close", $timer); + $countdown = query(".artplayer-plugin-ads-countdown", $timer); + if (option.playDuration >= option.totalDuration) { + setStyle($close, "display", "none"); + } + art.proxy($close, "click", () => { + if (isCanClose) { + skip(); + } + }); + $control = append( + art.template.$ads, + `
+
${option.i18n.detail}
+
+
+
` + ); + const $detail = query(".artplayer-plugin-ads-detail", $control); + const $muted = query(".artplayer-plugin-ads-muted", $control); + const $fullscreen = query(".artplayer-plugin-ads-fullscreen", $control); + if (option.url) { + art.proxy($detail, "click", () => { + window.open(option.url); + art.emit("artplayerPluginAds:click", option); + }); + } else { + setStyle($detail, "display", "none"); + } + if (option.video) { + const $volume = append($muted, volume); + const $volumeClose = append($muted, volumeClose); + setStyle($volumeClose, "display", "none"); + if (option.muted) { + $ads.muted = true; + setStyle($volume, "display", "none"); + setStyle($volumeClose, "display", "inline-flex"); + } + art.proxy($muted, "click", () => { + $ads.muted = !$ads.muted; + if ($ads.muted) { + setStyle($volume, "display", "none"); + setStyle($volumeClose, "display", "inline-flex"); + } else { + setStyle($volume, "display", "inline-flex"); + setStyle($volumeClose, "display", "none"); + } + }); + } else { + setStyle($muted, "display", "none"); + } + const $fullscreenOn = append($fullscreen, fullscreenOn); + const $fullscreenOff = append($fullscreen, fullscreenOff); + setStyle($fullscreenOff, "display", "none"); + art.proxy($fullscreen, "click", () => { + art.fullscreen = !art.fullscreen; + if (art.fullscreen) { + setStyle($fullscreenOn, "display", "inline-flex"); + setStyle($fullscreenOff, "display", "none"); + } else { + setStyle($fullscreenOn, "display", "none"); + setStyle($fullscreenOff, "display", "inline-flex"); + } + }); + art.proxy($ads, "click", () => { + if (option.url) + window.open(option.url); + art.emit("artplayerPluginAds:click", option); + }); + } + function init() { + if (isInit) + return; + isInit = true; + show(); + art.pause(); + if (option.video) { + art.proxy($ads, "error", skip); + art.proxy($ads, "loadedmetadata", () => { + play(); + $ads.play(); + setStyle($timer, "display", "flex"); + setStyle($control, "display", "flex"); + setStyle($loading, "display", "none"); + }); + } else { + play(); + setStyle($timer, "display", "flex"); + setStyle($control, "display", "flex"); + setStyle($loading, "display", "none"); + } + art.on("document:visibilitychange", () => { + if (document.hidden) { + pause(); + } else { + play(); + } + }); + } + art.on("ready", () => { + art.once("play", init); + art.once("video:playing", init); + }); + return { + name: "artplayerPluginAds", + skip, + pause, + play + }; + }; +} +if (typeof document !== "undefined") { + if (!document.getElementById("artplayer-plugin-ads")) { + const $style = document.createElement("style"); + $style.id = "artplayer-plugin-ads"; + $style.textContent = style; + document.head.appendChild($style); + } +} +export { + artplayerPluginAds as default +}; diff --git a/docs/compiled/artplayer-plugin-ambilight.mjs b/docs/compiled/artplayer-plugin-ambilight.mjs index a70e04807..19196e4c8 100644 --- a/docs/compiled/artplayer-plugin-ambilight.mjs +++ b/docs/compiled/artplayer-plugin-ambilight.mjs @@ -4,4 +4,101 @@ * (c) 2017-2026 Harvey Zhao * Released under the MIT License. */ -function t(t={}){return e=>{const{$video:n}=e.template,{createElement:r,addClass:o,setStyles:i}=e.constructor.utils,{blur:a="50px",opacity:l=.5,frequency:s=10,duration:c=.3}=t,u=r("div"),d=((f=u).innerHTML=Array.from({length:9}).fill("
").join(""),Array.from(f.children));var f,m,g,p;!function(t,e){o(t,"artplayer-plugin-ambilight"),e.parentNode.insertBefore(t,e),i(t,{position:"absolute",top:0,left:0,zIndex:9,inset:0,display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gridTemplateRows:"1fr 1fr 1fr"})}(u,n),m=a,g=l,p=c,d.forEach(t=>{i(t,{opacity:g,filter:`blur(${m})`,transition:`background-color ${p}s ease`})});const y=function(t,n,o){const i=r("canvas"),a=i.getContext("2d");i.width=3,i.height=3;let l=0;return function r(){const i=performance.now();if(i-l<1e3/o||!e.playing)return void(h=requestAnimationFrame(r));l=i;const s=t.videoWidth/3,c=t.videoHeight/3,u=[[0,0],[s,0],[2*s,0],[0,c],[s,c],[2*s,c],[0,2*c],[s,2*c],[2*s,2*c]].map(([e,n])=>function(e,n,r,o){a.drawImage(t,e,n,r,o,0,0,1,1);const[i,l,s]=a.getImageData(0,0,1,1).data;return`rgb(${i}, ${l}, ${s})`}(e,n,s,c));n.forEach((t,e)=>{t.style.backgroundColor=u[e]}),h=requestAnimationFrame(r)}}(n,d,s);let h=null;function v(){h||y()}function b(){h&&(cancelAnimationFrame(h),h=null)}return e.on("ready",v),e.on("destroy",b),{name:"artplayerPluginAmbilight",start:v,stop:b}}}export{t as default}; +function artplayerPluginAmbilight(option = {}) { + return (art) => { + const { $video } = art.template; + const { createElement, addClass, setStyles } = art.constructor.utils; + const { blur = "50px", opacity = 0.5, frequency = 10, duration = 0.3 } = option; + const $ambilight = createElement("div"); + const gridItems = createGridItems($ambilight); + setupAmbilight($ambilight, $video); + setupGridItems(gridItems, blur, opacity, duration); + const updateColors = createColorUpdater($video, gridItems, frequency); + let animationFrameId = null; + function start() { + if (!animationFrameId) { + updateColors(); + } + } + function stop() { + if (animationFrameId) { + cancelAnimationFrame(animationFrameId); + animationFrameId = null; + } + } + art.on("ready", start); + art.on("destroy", stop); + return { + name: "artplayerPluginAmbilight", + start, + stop + }; + function createGridItems($ambilight2) { + $ambilight2.innerHTML = Array.from({ length: 9 }).fill("
").join(""); + return Array.from($ambilight2.children); + } + function setupAmbilight($ambilight2, $video2) { + addClass($ambilight2, "artplayer-plugin-ambilight"); + $video2.parentNode.insertBefore($ambilight2, $video2); + setStyles($ambilight2, { + position: "absolute", + top: 0, + left: 0, + zIndex: 9, + inset: 0, + display: "grid", + gridTemplateColumns: "1fr 1fr 1fr", + gridTemplateRows: "1fr 1fr 1fr" + }); + } + function setupGridItems(gridItems2, blur2, opacity2, duration2) { + gridItems2.forEach(($item) => { + setStyles($item, { + opacity: opacity2, + filter: `blur(${blur2})`, + transition: `background-color ${duration2}s ease` + }); + }); + } + function createColorUpdater($video2, gridItems2, frequency2) { + const canvas = createElement("canvas"); + const ctx = canvas.getContext("2d"); + canvas.width = 3; + canvas.height = 3; + function getAverageColor(x, y, w, h) { + ctx.drawImage($video2, x, y, w, h, 0, 0, 1, 1); + const [r, g, b] = ctx.getImageData(0, 0, 1, 1).data; + return `rgb(${r}, ${g}, ${b})`; + } + let lastUpdateTime = 0; + return function updateColors2() { + const now = performance.now(); + if (now - lastUpdateTime < 1e3 / frequency2 || !art.playing) { + animationFrameId = requestAnimationFrame(updateColors2); + return; + } + lastUpdateTime = now; + const w = $video2.videoWidth / 3; + const h = $video2.videoHeight / 3; + const colors = [ + [0, 0], + [w, 0], + [2 * w, 0], + [0, h], + [w, h], + [2 * w, h], + [0, 2 * h], + [w, 2 * h], + [2 * w, 2 * h] + ].map(([x, y]) => getAverageColor(x, y, w, h)); + gridItems2.forEach(($item, index) => { + $item.style.backgroundColor = colors[index]; + }); + animationFrameId = requestAnimationFrame(updateColors2); + }; + } + }; +} +export { + artplayerPluginAmbilight as default +}; diff --git a/docs/compiled/artplayer-plugin-asr.mjs b/docs/compiled/artplayer-plugin-asr.mjs index d35dbe4eb..691a4e3a1 100644 --- a/docs/compiled/artplayer-plugin-asr.mjs +++ b/docs/compiled/artplayer-plugin-asr.mjs @@ -4,4 +4,249 @@ * (c) 2017-2026 Harvey Zhao * Released under the MIT License. */ -function t(t={}){const{length:e=3,interval:n=100,sampleRate:r=16e3,autoHideTimeout:a=1e4,onAudioChunk:o=()=>null}=t;return t=>{let i=!1,l=null,s=null,u=null,c=null,p=[],d=null,m=!1,y=null,f=null,g=null;const w=t.layers.add({name:"asr",html:""});function h(){w.style.display="none"}function v(t){var n;"string"===typeof t&&(clearTimeout(y),y=setTimeout(h,a),w.style.display="",w.innerHTML=(n=t,n.split(/(?<=[\u3001\u3002\uff01\uff1f!?.])\s*/u).map(t=>t.trim()).filter(Boolean).slice(-e)).map(t=>`
${t}
`).join(""))}async function b(){if(!s&&t.video)try{return s=l.createMediaElementSource(t.video),s}catch(e){console.warn("[artplayerPluginAsr] Direct connection failed:",e)}try{if(f||(f=await async function(t){try{return t.captureStream?t.captureStream():t.mozCaptureStream?t.mozCaptureStream():(console.warn("[artplayerPluginAsr] captureStream not supported"),null)}catch(e){return console.warn("[artplayerPluginAsr] Error capturing stream:",e),null}}(t.video)),f)return g=l.createMediaStreamSource(f),g}catch(e){console.warn("[artplayerPluginAsr] MediaStream fallback failed:",e)}return null}async function x(){i&&(i=!1,clearInterval(d),d=null,u&&(u.disconnect(),u.port.onmessage=null,u=null),c&&(c.disconnect(),c=null),p=[])}async function A(){await x(),g&&(g.disconnect(),g=null),s&&(s.disconnect(),s=null),f&&(f.getTracks().forEach(t=>t.stop()),f=null),l&&(await l.close(),l=null),m=!1}return t.on("video:volumechange",()=>{c&&(c.gain.value=t.volume)}),t.on("play",async function(){if(!i)try{await async function(){return l||(l=new(window.AudioContext||window.webkitAudioContext)({sampleRate:r}),"suspended"===l.state&&await l.resume(),l)}();const t=await b();if(!t)throw new Error("Could not establish audio source");if(!m){const t=(()=>{const t=new Blob(["\n class RecorderProcessor extends AudioWorkletProcessor {\n process(inputs) {\n const input = inputs[0];\n if (input && input[0]) {\n this.port.postMessage(input[0]);\n }\n return true;\n }\n }\n registerProcessor('recorder-processor', RecorderProcessor);\n "],{type:"application/javascript"});return URL.createObjectURL(t)})();await l.audioWorklet.addModule(t),URL.revokeObjectURL(t),m=!0}c=l.createGain(),c.gain.value=1,u=new AudioWorkletNode(l,"recorder-processor"),u.port.onmessage=t=>{p.push(new Float32Array(t.data))},t.connect(u),t.connect(c),c.connect(l.destination);const e=r*(n/1e3);d=setInterval(async()=>{if(0===p.length)return;let t=new Float32Array(0);for(;t.length{for(let n=0;n null + } = option; + return (art) => { + let started = false; + let audioCtx = null; + let sourceNode = null; + let recorderNode = null; + let gainNode = null; + let bufferChunks = []; + let timer = null; + let workletLoaded = false; + let hideTimer = null; + let mediaStream = null; + let mediaStreamSource = null; + const $asr = art.layers.add({ + name: "asr", + html: "" + }); + function splitByPunctuation(text) { + return text.split(/(?<=[、。!?!?.])\s*/u).map((s) => s.trim()).filter(Boolean).slice(-length); + } + function hide() { + $asr.style.display = "none"; + } + function append(subtitle) { + if (typeof subtitle !== "string") + return; + clearTimeout(hideTimer); + hideTimer = setTimeout(hide, autoHideTimeout); + $asr.style.display = ""; + $asr.innerHTML = splitByPunctuation(subtitle).map((line) => `
${line}
`).join(""); + } + const recorderProcessorCode = ` + class RecorderProcessor extends AudioWorkletProcessor { + process(inputs) { + const input = inputs[0]; + if (input && input[0]) { + this.port.postMessage(input[0]); + } + return true; + } + } + registerProcessor('recorder-processor', RecorderProcessor); + `; + const createWorkletBlobUrl = () => { + const blob = new Blob([recorderProcessorCode], { type: "application/javascript" }); + return URL.createObjectURL(blob); + }; + function floatTo16BitPCM(float32Array) { + const len = float32Array.length; + const buffer = new ArrayBuffer(len * 2); + const view = new DataView(buffer); + for (let i = 0; i < len; i++) { + const s = Math.max(-1, Math.min(1, float32Array[i])); + view.setInt16(i * 2, s < 0 ? s * 32768 : s * 32767, true); + } + return buffer; + } + function pcmToWav(pcmBuffer, sampleRate2) { + const pcmLength = pcmBuffer.byteLength; + const wavBuffer = new ArrayBuffer(44 + pcmLength); + const view = new DataView(wavBuffer); + const writeString = (offset, str) => { + for (let i = 0; i < str.length; i++) { + view.setUint8(offset + i, str.charCodeAt(i)); + } + }; + writeString(0, "RIFF"); + view.setUint32(4, 36 + pcmLength, true); + writeString(8, "WAVE"); + writeString(12, "fmt "); + view.setUint32(16, 16, true); + view.setUint16(20, 1, true); + view.setUint16(22, 1, true); + view.setUint32(24, sampleRate2, true); + view.setUint32(28, sampleRate2 * 2, true); + view.setUint16(32, 2, true); + view.setUint16(34, 16, true); + writeString(36, "data"); + view.setUint32(40, pcmLength, true); + new Uint8Array(wavBuffer).set(new Uint8Array(pcmBuffer), 44); + return wavBuffer; + } + async function setupAudioContext() { + if (audioCtx) + return audioCtx; + audioCtx = new (window.AudioContext || window.webkitAudioContext)({ sampleRate }); + if (audioCtx.state === "suspended") + await audioCtx.resume(); + return audioCtx; + } + async function setupAudioSource() { + if (!sourceNode && art.video) { + try { + sourceNode = audioCtx.createMediaElementSource(art.video); + return sourceNode; + } catch (err) { + console.warn("[artplayerPluginAsr] Direct connection failed:", err); + } + } + try { + if (!mediaStream) { + mediaStream = await captureAudioFromVideo(art.video); + } + if (mediaStream) { + mediaStreamSource = audioCtx.createMediaStreamSource(mediaStream); + return mediaStreamSource; + } + } catch (err) { + console.warn("[artplayerPluginAsr] MediaStream fallback failed:", err); + } + return null; + } + async function captureAudioFromVideo(videoElement) { + try { + if (videoElement.captureStream) + return videoElement.captureStream(); + if (videoElement.mozCaptureStream) + return videoElement.mozCaptureStream(); + console.warn("[artplayerPluginAsr] captureStream not supported"); + return null; + } catch (err) { + console.warn("[artplayerPluginAsr] Error capturing stream:", err); + return null; + } + } + async function startCapture() { + if (started) + return; + try { + await setupAudioContext(); + const audioSource = await setupAudioSource(); + if (!audioSource) + throw new Error("Could not establish audio source"); + if (!workletLoaded) { + const blobUrl = createWorkletBlobUrl(); + await audioCtx.audioWorklet.addModule(blobUrl); + URL.revokeObjectURL(blobUrl); + workletLoaded = true; + } + gainNode = audioCtx.createGain(); + gainNode.gain.value = 1; + recorderNode = new AudioWorkletNode(audioCtx, "recorder-processor"); + recorderNode.port.onmessage = (event) => { + bufferChunks.push(new Float32Array(event.data)); + }; + audioSource.connect(recorderNode); + audioSource.connect(gainNode); + gainNode.connect(audioCtx.destination); + const CHUNK_SAMPLES = sampleRate * (interval / 1e3); + timer = setInterval(async () => { + if (bufferChunks.length === 0) + return; + let accumulated = new Float32Array(0); + while (accumulated.length < CHUNK_SAMPLES && bufferChunks.length) { + const next = bufferChunks.shift(); + const tmp = new Float32Array(accumulated.length + next.length); + tmp.set(accumulated, 0); + tmp.set(next, accumulated.length); + accumulated = tmp; + } + if (accumulated.length < CHUNK_SAMPLES) + return; + const chunkToSend = accumulated.slice(0, CHUNK_SAMPLES); + const pcm = floatTo16BitPCM(chunkToSend); + const wav = pcmToWav(pcm, sampleRate); + const subtitle = await onAudioChunk({ pcm, wav }); + append(subtitle); + }, interval); + started = true; + } catch (err) { + console.error("[artplayerPluginAsr] Initialization failed:", err); + await stopCapture(); + } + } + async function stopCapture() { + if (!started) + return; + started = false; + clearInterval(timer); + timer = null; + if (recorderNode) { + recorderNode.disconnect(); + recorderNode.port.onmessage = null; + recorderNode = null; + } + if (gainNode) { + gainNode.disconnect(); + gainNode = null; + } + bufferChunks = []; + } + async function destroy() { + await stopCapture(); + if (mediaStreamSource) { + mediaStreamSource.disconnect(); + mediaStreamSource = null; + } + if (sourceNode) { + sourceNode.disconnect(); + sourceNode = null; + } + if (mediaStream) { + mediaStream.getTracks().forEach((track) => track.stop()); + mediaStream = null; + } + if (audioCtx) { + await audioCtx.close(); + audioCtx = null; + } + workletLoaded = false; + } + art.on("video:volumechange", () => { + if (gainNode) { + gainNode.gain.value = art.volume; + } + }); + art.on("play", startCapture); + art.on("pause", stopCapture); + art.on("destroy", destroy); + return { + name: "artplayerPluginAsr", + stop: destroy, + hide, + append + }; + }; +} +if (typeof document !== "undefined") { + if (!document.getElementById("artplayer-plugin-asr")) { + const $style = document.createElement("style"); + $style.id = "artplayer-plugin-asr"; + $style.textContent = style; + document.head.appendChild($style); + } +} +export { + artplayerPluginAsr as default +}; diff --git a/docs/compiled/artplayer-plugin-audio-track.mjs b/docs/compiled/artplayer-plugin-audio-track.mjs index e00c8166a..65bc77c9e 100644 --- a/docs/compiled/artplayer-plugin-audio-track.mjs +++ b/docs/compiled/artplayer-plugin-audio-track.mjs @@ -4,4 +4,89 @@ * (c) 2017-2026 Harvey Zhao * Released under the MIT License. */ -function e(e){return a=>{let{url:o,offset:n=0,sync:t=.3}=e;const u=new Audio;function c(){if(!a.video||!o)return;const e=a.currentTime+n;Math.abs(u.currentTime-e)>t&&(u.currentTime=e)}return u.preload="auto",o&&(u.src=o),a.on("play",()=>{o&&(c(),u.play().catch(e=>{console.warn(e)}))}),a.on("pause",()=>{u.pause()}),a.on("seek",()=>{c()}),a.on("video:timeupdate",()=>{a.playing&&c()}),a.on("video:ratechange",()=>{u.playbackRate=a.video.playbackRate}),a.on("video:volumechange",()=>{u.volume=a.volume,u.muted=a.muted}),a.on("video:waiting",()=>{u.pause()}),a.on("video:playing",()=>{o&&a.playing&&u.play().catch(e=>{console.warn(e)})}),a.on("destroy",()=>{u.pause(),u.src="",u.load()}),u.volume=a.volume,u.muted=a.muted,u.playbackRate=a.video?.playbackRate||1,{name:"artplayerPluginAudioTrack",audio:u,update:function(e){e.url&&e.url!==o&&(o=e.url,u.src=o,a.playing&&u.play().catch(e=>console.warn(e))),void 0!==e.offset&&(n=e.offset),void 0!==e.sync&&(t=e.sync)}}}}export{e as default}; +function artplayerPluginAudioTrack(option) { + return (art) => { + let { url, offset = 0, sync = 0.3 } = option; + const audio = new Audio(); + audio.preload = "auto"; + if (url) { + audio.src = url; + } + function syncAudio() { + if (!art.video || !url) + return; + const videoTime = art.currentTime; + const targetTime = videoTime + offset; + if (Math.abs(audio.currentTime - targetTime) > sync) { + audio.currentTime = targetTime; + } + } + art.on("play", () => { + if (!url) + return; + syncAudio(); + audio.play().catch((err) => { + console.warn(err); + }); + }); + art.on("pause", () => { + audio.pause(); + }); + art.on("seek", () => { + syncAudio(); + }); + art.on("video:timeupdate", () => { + if (art.playing) { + syncAudio(); + } + }); + art.on("video:ratechange", () => { + audio.playbackRate = art.video.playbackRate; + }); + art.on("video:volumechange", () => { + audio.volume = art.volume; + audio.muted = art.muted; + }); + art.on("video:waiting", () => { + audio.pause(); + }); + art.on("video:playing", () => { + if (url && art.playing) { + audio.play().catch((err) => { + console.warn(err); + }); + } + }); + art.on("destroy", () => { + audio.pause(); + audio.src = ""; + audio.load(); + }); + function update(newOption) { + if (newOption.url && newOption.url !== url) { + url = newOption.url; + audio.src = url; + if (art.playing) { + audio.play().catch((err) => console.warn(err)); + } + } + if (newOption.offset !== void 0) { + offset = newOption.offset; + } + if (newOption.sync !== void 0) { + sync = newOption.sync; + } + } + audio.volume = art.volume; + audio.muted = art.muted; + audio.playbackRate = art.video?.playbackRate || 1; + return { + name: "artplayerPluginAudioTrack", + audio, + update + }; + }; +} +export { + artplayerPluginAudioTrack as default +}; diff --git a/docs/compiled/artplayer-plugin-auto-thumbnail.mjs b/docs/compiled/artplayer-plugin-auto-thumbnail.mjs index 74673a601..057c7208f 100644 --- a/docs/compiled/artplayer-plugin-auto-thumbnail.mjs +++ b/docs/compiled/artplayer-plugin-auto-thumbnail.mjs @@ -4,4 +4,60 @@ * (c) 2017-2026 Harvey Zhao * Released under the MIT License. */ -function e(e){return async t=>(t.on("video:loadedmetadata",()=>{const n=e.url||t.option.url,o=e.width||160,a=e.number||100,r=e.scale||1;!function({url:e,width:t,number:n},o){const a=document.createElement("video");a.crossOrigin="anonymous",a.src=e,a.onloadedmetadata=()=>{const e=a.duration,r=document.createElement("canvas"),i=r.getContext("2d"),u=Math.floor(t*a.videoHeight/a.videoWidth);r.width=10*t,r.height=u*Math.ceil(n/10);let l=null;!function d(c){r.toBlob(e=>{URL.revokeObjectURL(l),l=URL.createObjectURL(e),o({url:l,height:u})},"image/jpeg"),c>=n||(a.currentTime=e*c/n,a.onseeked=()=>{i.drawImage(a,c%10*t,Math.floor(c/10)*u,t,u),d(c+1)})}(0)}}({url:n,width:o,number:a},e=>{t.thumbnails={...e,column:10,number:a,width:o,scale:r}})}),{name:"artplayerPluginAutoThumbnail"})}export{e as default}; +function create({ url, width, number }, callback) { + const video = document.createElement("video"); + video.crossOrigin = "anonymous"; + video.src = url; + video.onloadedmetadata = () => { + const duration = video.duration; + const canvas = document.createElement("canvas"); + const ctx = canvas.getContext("2d"); + const height = Math.floor(width * video.videoHeight / video.videoWidth); + canvas.width = width * 10; + canvas.height = height * Math.ceil(number / 10); + let blobUrl = null; + function seekAndDraw(index) { + canvas.toBlob((blob) => { + URL.revokeObjectURL(blobUrl); + blobUrl = URL.createObjectURL(blob); + callback({ + url: blobUrl, + height + }); + }, "image/jpeg"); + if (index >= number) + return; + video.currentTime = duration * index / number; + video.onseeked = () => { + ctx.drawImage(video, index % 10 * width, Math.floor(index / 10) * height, width, height); + seekAndDraw(index + 1); + }; + } + seekAndDraw(0); + }; +} +function artplayerPluginAutoThumbnail(option) { + return async (art) => { + art.on("video:loadedmetadata", () => { + const url = option.url || art.option.url; + const width = option.width || 160; + const number = option.number || 100; + const scale = option.scale || 1; + create({ url, width, number }, (config) => { + art.thumbnails = { + ...config, + column: 10, + number, + width, + scale + }; + }); + }); + return { + name: "artplayerPluginAutoThumbnail" + }; + }; +} +export { + artplayerPluginAutoThumbnail as default +}; diff --git a/docs/compiled/artplayer-plugin-chapter.mjs b/docs/compiled/artplayer-plugin-chapter.mjs index f8ede6d03..fff9ff1f3 100644 --- a/docs/compiled/artplayer-plugin-chapter.mjs +++ b/docs/compiled/artplayer-plugin-chapter.mjs @@ -4,4 +4,156 @@ * (c) 2017-2026 Harvey Zhao * Released under the MIT License. */ -function t(t={}){return r=>{const{$player:e}=r.template,{setStyle:a,append:n,clamp:o,query:i,addClass:p,removeClass:s}=r.constructor.utils;let d=[];const l=r.query(".art-control-progress-inner"),c=n(l,'
'),h=n(l,'
');function u({$chapter:t,width:r}){const e=t.dataset.title.trim();if(e){h.textContent=e;const t=h.clientWidth;r<=t/2?a(h,"left",0):r>l.clientWidth-t/2?a(h,"left",l.clientWidth-t+"px"):a(h,"left",r-t/2+"px")}}function g(t=[]){if(d=[],c.textContent="",s(e,"artplayer-plugin-chapter"),Array.isArray(t)&&t.length&&r.duration){t=t.sort((t,r)=>t.start-r.start);for(let e=0;er.duration||a.start>=a.end)throw new Error("Illegal chapter time point");if(n&&a.end>n.start)throw new Error("Illegal chapter time point")}t[0].start>0&&t.unshift({start:0,end:t[0].start,title:""}),t[t.length-1].end{const e=n(c,'\n
\n
\n
\n
\n
\n
\n
\n '),a=o(t.start,0,r.duration),p=o(t.end,0,r.duration),s=p-a,d=s/r.duration;return e.dataset.start=a,e.dataset.end=p,e.dataset.duration=s,e.dataset.title=t.title.trim(),e.style.width=100*d+"%",{$chapter:e,$hover:i(".art-progress-hover",e),$loaded:i(".art-progress-loaded",e),$played:i(".art-progress-played",e)}}),p(e,"artplayer-plugin-chapter"),r.emit("setBar","loaded",r.loaded||0)}}return r.on("setBar",(t,e)=>{if(d.length)for(let n=0;nf&&a(l,"width","100%"),g>=y&&g<=f){a(l,"width",100*((g-y)/m)+"%"),"hover"===t&&h>0&&u({$chapter:o,width:h})}}}),r.once("video:loadedmetadata",()=>g(t.chapters)),{name:"artplayerPluginChapter",update:({chapters:t})=>g(t)}}}if("undefined"!==typeof document){const t="artplayer-plugin-chapter";let r=document.getElementById(t);r||(r=document.createElement("style"),r.id=t,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{document.head.appendChild(r)}):(document.head||document.documentElement).appendChild(r)),r.textContent=".artplayer-plugin-chapter .art-control-progress-inner{height:100%!important;background-color:transparent!important}.artplayer-plugin-chapter .art-control-progress-inner>.art-progress-hover,.artplayer-plugin-chapter .art-control-progress-inner>.art-progress-loaded,.artplayer-plugin-chapter .art-control-progress-inner>.art-progress-played{display:none!important}.artplayer-plugin-chapter .art-control-thumbnails{bottom:calc(var(--art-bottom-gap) + 64px)!important}.artplayer-plugin-chapter .art-chapters{position:absolute;z-index:0;inset:0;display:flex;align-items:center;gap:4px;height:100%;transform:scaleY(1.25)}.artplayer-plugin-chapter .art-chapters .art-chapter{display:flex;align-items:center;height:100%}.artplayer-plugin-chapter .art-chapters .art-chapter .art-chapter-inner{position:relative;cursor:pointer;width:100%;height:50%;border-radius:10px;overflow:hidden;transition:height var(--art-transition-duration) ease;background-color:var(--art-progress-color)}.artplayer-plugin-chapter .art-chapters .art-chapter:hover .art-chapter-inner{height:100%}.artplayer-plugin-chapter .art-chapter-title{transform-origin:bottom center;transform:scale(.5);opacity:0;position:absolute;z-index:70;top:-50px;left:0;padding:3px 5px;line-height:1;font-size:14px;border-radius:var(--art-border-radius);white-space:nowrap;background-color:var(--art-tip-background);transition:transform var(--art-transition-duration) ease,opacity var(--art-transition-duration) ease}.artplayer-plugin-chapter.art-progress-hover .art-chapter-title{transform:scale(1);opacity:1}"}export{t as default}; +const style = ".artplayer-plugin-chapter .art-control-progress-inner {\n height: 100% !important;\n background-color: transparent !important;\n}\n.artplayer-plugin-chapter .art-control-progress-inner > .art-progress-hover,\n.artplayer-plugin-chapter .art-control-progress-inner > .art-progress-loaded,\n.artplayer-plugin-chapter .art-control-progress-inner > .art-progress-played {\n display: none !important;\n}\n.artplayer-plugin-chapter .art-control-thumbnails {\n bottom: calc(var(--art-bottom-gap) + 64px) !important;\n}\n.artplayer-plugin-chapter .art-chapters {\n position: absolute;\n z-index: 0;\n inset: 0;\n display: flex;\n align-items: center;\n gap: 4px;\n height: 100%;\n transform: scaleY(1.25);\n}\n.artplayer-plugin-chapter .art-chapters .art-chapter {\n display: flex;\n align-items: center;\n height: 100%;\n}\n.artplayer-plugin-chapter .art-chapters .art-chapter .art-chapter-inner {\n position: relative;\n cursor: pointer;\n width: 100%;\n height: 50%;\n border-radius: 10px;\n overflow: hidden;\n transition: height var(--art-transition-duration) ease;\n background-color: var(--art-progress-color);\n}\n.artplayer-plugin-chapter .art-chapters .art-chapter:hover .art-chapter-inner {\n height: 100%;\n}\n.artplayer-plugin-chapter .art-chapter-title {\n transform-origin: bottom center;\n transform: scale(0.5);\n opacity: 0;\n position: absolute;\n z-index: 70;\n top: -50px;\n left: 0;\n padding: 3px 5px;\n line-height: 1;\n font-size: 14px;\n border-radius: var(--art-border-radius);\n white-space: nowrap;\n background-color: var(--art-tip-background);\n transition: transform var(--art-transition-duration) ease, opacity var(--art-transition-duration) ease;\n}\n.artplayer-plugin-chapter.art-progress-hover .art-chapter-title {\n transform: scale(1);\n opacity: 1;\n}\n"; +function artplayerPluginChapter(option = {}) { + return (art) => { + const { $player } = art.template; + const { setStyle, append, clamp, query, addClass, removeClass } = art.constructor.utils; + const html = ` +
+
+
+
+
+
+
+ `; + let $chapters = []; + const $inner = art.query(".art-control-progress-inner"); + const $control = append($inner, '
'); + const $title = append($inner, '
'); + function showTitle({ $chapter, width }) { + const title = $chapter.dataset.title.trim(); + if (title) { + $title.textContent = title; + const titleWidth = $title.clientWidth; + if (width <= titleWidth / 2) { + setStyle($title, "left", 0); + } else if (width > $inner.clientWidth - titleWidth / 2) { + setStyle($title, "left", `${$inner.clientWidth - titleWidth}px`); + } else { + setStyle($title, "left", `${width - titleWidth / 2}px`); + } + } + } + function update(chapters = []) { + $chapters = []; + $control.textContent = ""; + removeClass($player, "artplayer-plugin-chapter"); + if (!Array.isArray(chapters)) + return; + if (!chapters.length) + return; + if (!art.duration) + return; + chapters = chapters.sort((a, b) => a.start - b.start); + for (let i = 0; i < chapters.length; i++) { + const chapter = chapters[i]; + const nextChapter = chapters[i + 1]; + if (chapter.end === Infinity) { + chapter.end = art.duration; + } + if (typeof chapter.start !== "number" || typeof chapter.end !== "number" || typeof chapter.title !== "string") { + throw new TypeError("Illegal chapter data type"); + } + if (chapter.start < 0 || chapter.end > art.duration || chapter.start >= chapter.end) { + throw new Error("Illegal chapter time point"); + } + if (nextChapter && chapter.end > nextChapter.start) { + throw new Error("Illegal chapter time point"); + } + } + if (chapters[0].start > 0) { + chapters.unshift({ start: 0, end: chapters[0].start, title: "" }); + } + if (chapters[chapters.length - 1].end < art.duration) { + chapters.push({ start: chapters[chapters.length - 1].end, end: art.duration, title: "" }); + } + for (let i = 0; i < chapters.length - 1; i++) { + if (chapters[i].end !== chapters[i + 1].start) { + chapters.splice(i + 1, 0, { + start: chapters[i].end, + end: chapters[i + 1].start, + title: "" + }); + } + } + $chapters = chapters.map((chapter) => { + const $chapter = append($control, html); + const start = clamp(chapter.start, 0, art.duration); + const end = clamp(chapter.end, 0, art.duration); + const duration = end - start; + const percentage = duration / art.duration; + $chapter.dataset.start = start; + $chapter.dataset.end = end; + $chapter.dataset.duration = duration; + $chapter.dataset.title = chapter.title.trim(); + $chapter.style.width = `${percentage * 100}%`; + return { + $chapter, + $hover: query(".art-progress-hover", $chapter), + $loaded: query(".art-progress-loaded", $chapter), + $played: query(".art-progress-played", $chapter) + }; + }); + addClass($player, "artplayer-plugin-chapter"); + art.emit("setBar", "loaded", art.loaded || 0); + } + art.on("setBar", (type, percentage) => { + if (!$chapters.length) + return; + for (let i = 0; i < $chapters.length; i++) { + const { $chapter, $loaded, $played, $hover } = $chapters[i]; + const $target = { + hover: $hover, + loaded: $loaded, + played: $played + }[type]; + if (!$target) + return; + const width = $control.clientWidth * percentage; + const currentTime = art.duration * percentage; + const duration = Number.parseFloat($chapter.dataset.duration); + const start = Number.parseFloat($chapter.dataset.start); + const end = Number.parseFloat($chapter.dataset.end); + if (currentTime < start) { + setStyle($target, "width", 0); + } + if (currentTime > end) { + setStyle($target, "width", "100%"); + } + if (currentTime >= start && currentTime <= end) { + const percentage2 = (currentTime - start) / duration; + setStyle($target, "width", `${percentage2 * 100}%`); + if (type === "hover" && width > 0) { + showTitle({ $chapter, width }); + } + } + } + }); + art.once("video:loadedmetadata", () => update(option.chapters)); + return { + name: "artplayerPluginChapter", + update: ({ chapters }) => update(chapters) + }; + }; +} +if (typeof document !== "undefined") { + const id = "artplayer-plugin-chapter"; + let $style = document.getElementById(id); + if (!$style) { + $style = document.createElement("style"); + $style.id = id; + if (document.readyState === "loading") { + document.addEventListener("DOMContentLoaded", () => { + document.head.appendChild($style); + }); + } else { + (document.head || document.documentElement).appendChild($style); + } + } + $style.textContent = style; +} +export { + artplayerPluginChapter as default +}; diff --git a/docs/compiled/artplayer-plugin-chromecast.mjs b/docs/compiled/artplayer-plugin-chromecast.mjs index 9b4175ab0..1a828128a 100644 --- a/docs/compiled/artplayer-plugin-chromecast.mjs +++ b/docs/compiled/artplayer-plugin-chromecast.mjs @@ -4,4 +4,173 @@ * (c) 2017-2026 Harvey Zhao * Released under the MIT License. */ -function e(e){let t=!1,o=null,a=null;const n=e=>{const t=document.querySelector(".art-icon-cast");if(t)switch(e){case"connected":t.style.color="red";break;case"connecting":case"disconnecting":t.style.color="orange";break;default:t.style.color="white"}},c=()=>new Promise((c,s)=>{var i;window.__onGCastApiAvailable=i=>{if(i){const s=window.cast.framework.CastContext.getInstance();s.setOptions({receiverApplicationId:window.chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,autoJoinPolicy:window.chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}),s.addEventListener(window.cast.framework.CastContextEventType.SESSION_STATE_CHANGED,t=>{const c=window.cast.framework.SessionState;switch(a=t.sessionState,o=t.session,t.sessionState){case c.NO_SESSION:e.onStateChange?.("disconnected"),n("disconnected");break;case c.SESSION_STARTING:e.onStateChange?.("connecting"),n("connecting");break;case c.SESSION_STARTED:e.onStateChange?.("connected"),n("connected");break;case c.SESSION_ENDING:e.onStateChange?.("disconnecting"),n("disconnecting");break;case c.SESSION_RESUMED:e.onStateChange?.("connected"),n("connected")}}),s.addEventListener(window.cast.framework.CastContextEventType.CAST_STATE_CHANGED,t=>{const o=window.cast.framework.CastState;switch(t.castState){case o.NO_DEVICES_AVAILABLE:e.onCastAvailable?.(!1);break;case o.NOT_CONNECTED:case o.CONNECTING:case o.CONNECTED:e.onCastAvailable?.(!0)}}),t=!0,c()}else s(new Error("Cast API is not available"))},window.chrome&&window.chrome.cast||(i=e.sdk||"https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1",new Promise((e,t)=>{const o=document.createElement("script");o.src=i,o.onload=e,o.onerror=t,document.body.appendChild(o)})).catch(s)}),s=(t,o)=>{const a=e.url||t.option.url,n=new window.chrome.cast.media.MediaInfo(a,e.mimeType||function(e){return{mp4:"video/mp4",webm:"video/webm",ogg:"video/ogg",ogv:"video/ogg",mp3:"audio/mp3",wav:"audio/wav",flv:"video/x-flv",mov:"video/quicktime",avi:"video/x-msvideo",wmv:"video/x-ms-wmv",mpd:"application/dash+xml",m3u8:"application/x-mpegURL"}[e.split("?")[0].split("#")[0].split(".").pop().toLowerCase()]||"application/octet-stream"}(a)),c=new window.chrome.cast.media.LoadRequest(n);o.loadMedia(c).then(()=>{t.notice.show="Casting started",e.onCastStart?.()}).catch(o=>{throw t.notice.show="Error casting media",e.onError?.(o),o})};return async n=>(n.controls.add({name:"chromecast",position:"right",tooltip:"Chromecast",html:`${e.icon||''}`,click:async()=>{if(!t)try{await c()}catch(i){throw n.notice.show="Failed to initialize Cast API",e.onError?.(i),i}const a=window.cast.framework.CastContext.getInstance();if(o)s(n,o);else try{const e=await a.requestSession();s(n,e)}catch(i){throw n.notice.show="Error connecting to cast session",e.onError?.(i),i}}}),{name:"artplayerPluginChromecast",getCastState:()=>a,isCasting:()=>null!==o})}export{e as default}; +function loadScript(src) { + return new Promise((resolve, reject) => { + const script = document.createElement("script"); + script.src = src; + script.onload = resolve; + script.onerror = reject; + document.body.appendChild(script); + }); +} +function getMimeType(url) { + const extension = url.split("?")[0].split("#")[0].split(".").pop().toLowerCase(); + const mimeTypes = { + mp4: "video/mp4", + webm: "video/webm", + ogg: "video/ogg", + ogv: "video/ogg", + mp3: "audio/mp3", + wav: "audio/wav", + flv: "video/x-flv", + mov: "video/quicktime", + avi: "video/x-msvideo", + wmv: "video/x-ms-wmv", + mpd: "application/dash+xml", + m3u8: "application/x-mpegURL" + }; + return mimeTypes[extension] || "application/octet-stream"; +} +function artplayerPluginChromecast(option) { + const DEFAULT_ICON = ``; + const DEFAULT_SDK = "https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1"; + let isCastInitialized = false; + let castSession = null; + let castState = null; + const updateCastButton = (state) => { + const button = document.querySelector(".art-icon-cast"); + if (button) { + switch (state) { + case "connected": + button.style.color = "red"; + break; + case "connecting": + case "disconnecting": + button.style.color = "orange"; + break; + case "disconnected": + default: + button.style.color = "white"; + break; + } + } + }; + const initializeCastApi = () => { + return new Promise((resolve, reject) => { + window.__onGCastApiAvailable = (isAvailable) => { + if (isAvailable) { + const context = window.cast.framework.CastContext.getInstance(); + context.setOptions({ + receiverApplicationId: window.chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID, + autoJoinPolicy: window.chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED + }); + context.addEventListener( + window.cast.framework.CastContextEventType.SESSION_STATE_CHANGED, + (event) => { + const SessionState = window.cast.framework.SessionState; + castState = event.sessionState; + castSession = event.session; + switch (event.sessionState) { + case SessionState.NO_SESSION: + option.onStateChange?.("disconnected"); + updateCastButton("disconnected"); + break; + case SessionState.SESSION_STARTING: + option.onStateChange?.("connecting"); + updateCastButton("connecting"); + break; + case SessionState.SESSION_STARTED: + option.onStateChange?.("connected"); + updateCastButton("connected"); + break; + case SessionState.SESSION_ENDING: + option.onStateChange?.("disconnecting"); + updateCastButton("disconnecting"); + break; + case SessionState.SESSION_RESUMED: + option.onStateChange?.("connected"); + updateCastButton("connected"); + break; + } + } + ); + context.addEventListener(window.cast.framework.CastContextEventType.CAST_STATE_CHANGED, (event) => { + const CastState = window.cast.framework.CastState; + switch (event.castState) { + case CastState.NO_DEVICES_AVAILABLE: + option.onCastAvailable?.(false); + break; + case CastState.NOT_CONNECTED: + option.onCastAvailable?.(true); + break; + case CastState.CONNECTING: + case CastState.CONNECTED: + option.onCastAvailable?.(true); + break; + } + }); + isCastInitialized = true; + resolve(); + } else { + reject(new Error("Cast API is not available")); + } + }; + if (!window.chrome || !window.chrome.cast) { + loadScript(option.sdk || DEFAULT_SDK).catch(reject); + } + }); + }; + const castVideo = (art, session) => { + const url = option.url || art.option.url; + const mediaInfo = new window.chrome.cast.media.MediaInfo(url, option.mimeType || getMimeType(url)); + const request = new window.chrome.cast.media.LoadRequest(mediaInfo); + session.loadMedia(request).then(() => { + art.notice.show = "Casting started"; + option.onCastStart?.(); + }).catch((error) => { + art.notice.show = "Error casting media"; + option.onError?.(error); + throw error; + }); + }; + return async (art) => { + art.controls.add({ + name: "chromecast", + position: "right", + tooltip: "Chromecast", + html: `${option.icon || DEFAULT_ICON}`, + click: async () => { + if (!isCastInitialized) { + try { + await initializeCastApi(); + } catch (error) { + art.notice.show = "Failed to initialize Cast API"; + option.onError?.(error); + throw error; + } + } + const context = window.cast.framework.CastContext.getInstance(); + if (castSession) { + castVideo(art, castSession); + } else { + try { + const session = await context.requestSession(); + castVideo(art, session); + } catch (error) { + art.notice.show = "Error connecting to cast session"; + option.onError?.(error); + throw error; + } + } + } + }); + return { + name: "artplayerPluginChromecast", + getCastState: () => castState, + isCasting: () => castSession !== null + }; + }; +} +export { + artplayerPluginChromecast as default +}; diff --git a/docs/compiled/artplayer-plugin-danmuku-mask.mjs b/docs/compiled/artplayer-plugin-danmuku-mask.mjs index 8c45bdc9e..5b74e387a 100644 --- a/docs/compiled/artplayer-plugin-danmuku-mask.mjs +++ b/docs/compiled/artplayer-plugin-danmuku-mask.mjs @@ -4,4 +4,49172 @@ * (c) 2017-2026 Harvey Zhao * Released under the MIT License. */ -function e(e,t){for(var n=0;nr[t]})}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}class t{constructor(e,t){this.backend=e,this.dataMover=t,this.data=/* @__PURE__ */new WeakMap,this.dataIdsCount=0}get(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)}set(e,t){this.dataIdsCount++,this.data.set(e,t)}has(e){return this.data.has(e)}delete(e){return this.dataIdsCount--,this.data.delete(e)}numDataIds(){return this.dataIdsCount}}class n{refCount(e){return r("refCount")}incRef(e){return r("incRef")}timerAvailable(){return!0}time(e){return r("time")}read(e){return r("read")}readSync(e){return r("readSync")}readToGPU(e,t){return r("readToGPU")}numDataIds(){return r("numDataIds")}disposeData(e,t){return r("disposeData")}write(e,t,n){return r("write")}move(e,t,n,a,s){return r("move")}createTensorFromGPUData(e,t,n){return r("createTensorFromGPUData")}memory(){return r("memory")}floatPrecision(){return r("floatPrecision")}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}dispose(){return r("dispose")}}function r(e){throw new Error(`'${e}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}function a(e,t,n){return Math.max(e,Math.min(t,n))}function s(e){return e%2===0?e:e+1}function o(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function i(e,t){if(!e)throw new Error("string"===typeof t?t:t())}function u(e,t,n=""){i(d(e,t),()=>n+` Shapes ${e} and ${t} must match`)}function l(e){i(null!=e,()=>"The input to the tensor constructor must be a non-null value.")}function c(e){if(0===e.length)return 1;let t=e[0];for(let n=1;n0,n,r){return new Promise((a,s)=>{let o=0;const i=()=>{if(e())return void a();o++;const u=t(o);null!=n&&o>=n?s():null!=r?r(i,u):setTimeout(i,u)};i()})}function g(e,t){let n=1,r=-1;for(let s=0;s=0)n*=e[s];else if(-1===e[s]){if(-1!==r)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${r} and dim ${s}`);r=s}else if(e[s]<0)throw Error(`Shapes can not be < 0. Found ${e[s]} at dim ${s}`);if(-1===r){if(t>0&&t!==n)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(0===n)throw Error(`Cannot infer the missing size in [${e}] when there are 0 elements`);if(t%n!==0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${n}`);const a=e.slice();return a[r]=t/n,a}function y(e,t){const n=t.length;return i((e=null==e?t.map((e,t)=>t):[].concat(e)).every(e=>e>=-n&&e`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`),i(e.every(e=>p(e)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(e=>e<0?n+e:e)}function b(e,t){const n=[],r=[],a=null!=t&&Array.isArray(t)&&0===t.length,s=null==t||a?null:y(t,e).sort();let o=0;for(let i=0;ii)&&1===e[i]&&(n.push(e[i]),r.push(i)),s[o]<=i&&o++}1!==e[i]&&(n.push(e[i]),r.push(i))}return{newShape:n,keptDims:r}}function x(e,t){return v(e,t)}function v(e,t){let n=null;if(null==e||"float32"===e)n=new Float32Array(t);else if("int32"===e)n=new Int32Array(t);else if("bool"===e)n=new Uint8Array(t);else{if("string"!==e)throw new Error(`Unknown data type ${e}`);n=new Array(t)}return n}function w(e,t){return"complex64"!==t&&(("float32"!==t||"complex64"===e)&&(("int32"!==t||"float32"===e||"complex64"===e)&&("bool"!==t||"bool"!==e)))}function k(e){if("float32"===e||"int32"===e)return 4;if("complex64"===e)return 8;if("bool"===e)return 1;throw new Error(`Unknown dtype ${e}`)}function I(e){return"string"===typeof e||e instanceof String}function N(e){return Array.isArray(e)?N(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":"number"===typeof e?"float32":I(e)?"string":function(e){return"boolean"===typeof e}(e)?"bool":"float32"}function S(e){return!!(e&&e.constructor&&e.call&&e.apply)}function T(e,t){for(let n=t;n=0;--r)n[r]=n[r+1]*e[r+1];return n}function $(e,t,n,r=!1){const a=new Array;if(1===t.length){const s=t[0]*(r?2:1);for(let t=0;te*t)*(r?2:1);for(let t=0;te*t)*(n?2:1);if(0===r)return[];if(r!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${n?" for a complex tensor":""}.`);return $(0,e,t,n)}function R(e,t){const n=_(e,t);for(let r=0;re*t,1);if(null==t||"float32"===t)return E(e,new Float32Array(n));if("int32"===t)return E(e,new Int32Array(n));if("bool"===t)return E(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function O(e){e.forEach(t=>{i(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function F(e,t,n){if(0===t)return 0;if(1===t)return e[0];let r=e[e.length-1];for(let a=0;a{const[t,n]=e.split(":");this.urlFlags[t]=function(e,t){const n=t.toLowerCase();return"true"===n||"false"===n?"true"===n:""+ +n===n?+n:t}(0,n)})}}}function B(e){const t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(e,...n)=>(function(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}(t,n[0],n[1]),n.join("="))),t}function V(){return z}let W,z=null;function U(){if(null==W){let e;if("undefined"!==typeof window)e=window;else if("undefined"!==typeof global)e=global;else if("undefined"!==typeof process)e=process;else{if("undefined"===typeof self)throw new Error("Could not find a global object");e=self}W=e}return W}function G(e,t){const n=function(){const e=U();return null==e._tfGlobals&&(e._tfGlobals=/* @__PURE__ */new Map),e._tfGlobals}();if(n.has(e))return n.get(e);{const r=t();return n.set(e,r),n.get(e)}}const H="Abs",j="Acos",q="Acosh",K="Add",X="AddN",Y="All",Q="Any",Z="ArgMax",J="ArgMin",ee="Asin",te="Asinh",ne="Atan",re="Atanh",ae="Atan2",se="AvgPool",oe="AvgPoolGrad",ie="AvgPool3D",ue="AvgPool3DGrad",le="BatchMatMul",ce="BatchToSpaceND",de="Bincount",pe="BitwiseAnd",he="BroadcastArgs",fe="Cast",me="Ceil",ge="ClipByValue",ye="Complex",be="ComplexAbs",xe="Concat",ve="Conv2D",we="Conv2DBackpropFilter",ke="Conv2DBackpropInput",Ie="Conv3D",Ne="Conv3DBackpropFilterV2",Se="Conv3DBackpropInputV2",Te="Cos",Ce="Cosh",$e="Cumprod",Ee="Cumsum",Re="CropAndResize",_e="DenseBincount",Ae="DepthToSpace",Oe="DepthwiseConv2dNative",Fe="DepthwiseConv2dNativeBackpropFilter",De="DepthwiseConv2dNativeBackpropInput",Me="Diag",Pe="Dilation2D",Le="Dilation2DBackpropInput",Be="Dilation2DBackpropFilter",Ve="Draw",We="RealDiv",ze="Einsum",Ue="Elu",Ge="EluGrad",He="Erf",je="Equal",qe="Exp",Ke="ExpandDims",Xe="Expm1",Ye="FFT",Qe="Fill",Ze="FlipLeftRight",Je="Floor",et="FloorDiv",tt="FusedBatchNorm",nt="GatherV2",rt="GatherNd",at="Greater",st="GreaterEqual",ot="Identity",it="IFFT",ut="Imag",lt="IsFinite",ct="IsInf",dt="IsNan",pt="LeakyRelu",ht="Less",ft="LessEqual",mt="LinSpace",gt="Log",yt="Log1p",bt="LogicalAnd",xt="LogicalNot",vt="LogicalOr",wt="LRN",kt="LRNGrad",It="Max",Nt="Maximum",St="MaxPool",Tt="MaxPoolGrad",Ct="MaxPool3D",$t="MaxPool3DGrad",Et="MaxPoolWithArgmax",Rt="Mean",_t="Min",At="Minimum",Ot="MirrorPad",Ft="Mod",Dt="Multinomial",Mt="Multiply",Pt="Neg",Lt="NotEqual",Bt="NonMaxSuppressionV3",Vt="NonMaxSuppressionV4",Wt="NonMaxSuppressionV5",zt="OnesLike",Ut="OneHot",Gt="Pack",Ht="PadV2",jt="Pow",qt="Prelu",Kt="Prod",Xt="RaggedGather",Yt="RaggedRange",Qt="RaggedTensorToTensor",Zt="Range",Jt="Real",en="Reciprocal",tn="Relu",nn="Reshape",rn="ResizeNearestNeighbor",an="ResizeNearestNeighborGrad",sn="ResizeBilinear",on="ResizeBilinearGrad",un="Relu6",ln="Reverse",cn="Round",dn="Rsqrt",pn="ScatterNd",hn="TensorScatterUpdate",fn="SearchSorted",mn="Select",gn="Selu",yn="Slice",bn="Sin",xn="Sinh",vn="Sign",wn="Sigmoid",kn="Softplus",In="Sqrt",Nn="Sum",Sn="SpaceToBatchND",Tn="SplitV",Cn="Softmax",$n="SparseFillEmptyRows",En="SparseReshape",Rn="SparseSegmentMean",_n="SparseSegmentSum",An="SparseToDense",On="SquaredDifference",Fn="Square",Dn="StaticRegexReplace",Mn="StridedSlice",Pn="StringNGrams",Ln="StringSplit",Bn="StringToHashBucketFast",Vn="Sub",Wn="Tan",zn="Tanh",Un="Tile",Gn="TopK",Hn="Transform",jn="Transpose",qn="Unique",Kn="Unpack",Xn="UnsortedSegmentSum",Yn="ZerosLike",Qn="Step",Zn="FromPixels",Jn="RotateWithOffset",er="_FusedMatMul",tr="FusedConv2D",nr="FusedDepthwiseConv2D";function rr(...e){V().getBool("IS_TEST")||V().getBool("PROD")||console.warn(...e)}const ar=G("kernelRegistry",()=>/* @__PURE__ */new Map),sr=G("gradRegistry",()=>/* @__PURE__ */new Map);function or(e,t){const n=cr(e,t);return ar.get(n)}function ir(e){return sr.get(e)}function ur(e){const t=ar.entries(),n=[];for(;;){const{done:r,value:a}=t.next();if(r)break;const[s,o]=a,[i]=s.split("_");i===e&&n.push(o)}return n}function lr(e){const{kernelName:t,backendName:n}=e,r=cr(t,n);ar.has(r)&&rr(`The kernel '${t}' for backend '${n}' is already registered`),ar.set(r,e)}function cr(e,t){return`${t}_${e}`}function dr(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray}var pr,hr,fr="undefined"!==typeof globalThis?globalThis:"undefined"!==typeof window?window:"undefined"!==typeof global?global:"undefined"!==typeof self?self:{};function mr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function gr(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if("function"==typeof t){var n=function e(){var n=!1;try{n=this instanceof e}catch{}return n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,r.get?r:{enumerable:!0,get:function(){return e[t]}})}),n}var yr=function(){if(hr)return pr;hr=1,pr=t;var e=null;try{e=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(N){}function t(e,t,n){this.low=0|e,this.high=0|t,this.unsigned=!!n}function n(e){return!0===(e&&e.__isLong__)}t.prototype.__isLong__,Object.defineProperty(t.prototype,"__isLong__",{value:!0}),t.isLong=n;var r={},a={};function s(e,t){var n,s,o;return t?(o=0<=(e>>>=0)&&e<256)&&(s=a[e])?s:(n=i(e,(0|e)<0?-1:0,!0),o&&(a[e]=n),n):(o=-128<=(e|=0)&&e<128)&&(s=r[e])?s:(n=i(e,e<0?-1:0,!1),o&&(r[e]=n),n)}function o(e,t){if(isNaN(e))return t?g:m;if(t){if(e<0)return g;if(e>=p)return w}else{if(e<=-h)return k;if(e+1>=h)return v}return e<0?o(-e,t).neg():i(e%d|0,e/d|0,t)}function i(e,n,r){return new t(e,n,r)}t.fromInt=s,t.fromNumber=o,t.fromBits=i;var u=Math.pow;function l(e,t,n){if(0===e.length)throw Error("empty string");if("NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return m;if("number"===typeof t?(n=t,t=!1):t=!!t,(n=n||10)<2||360)throw Error("interior hyphen");if(0===r)return l(e.substring(1),t,n).neg();for(var a=o(u(n,8)),s=m,i=0;i>>0:this.low},I.toNumber=function(){return this.unsigned?(this.high>>>0)*d+(this.low>>>0):this.high*d+(this.low>>>0)},I.toString=function(e){if((e=e||10)<2||36>>0).toString(e);if((s=l).isZero())return c+i;for(;c.length<6;)c="0"+c;i=""+c+i}},I.getHighBits=function(){return this.high},I.getHighBitsUnsigned=function(){return this.high>>>0},I.getLowBits=function(){return this.low},I.getLowBitsUnsigned=function(){return this.low>>>0},I.getNumBitsAbs=function(){if(this.isNegative())return this.eq(k)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&0==(e&1<=0},I.isOdd=function(){return 1===(1&this.low)},I.isEven=function(){return 0===(1&this.low)},I.equals=function(e){return n(e)||(e=c(e)),(this.unsigned===e.unsigned||this.high>>>31!==1||e.high>>>31!==1)&&(this.high===e.high&&this.low===e.low)},I.eq=I.equals,I.notEquals=function(e){return!this.eq(e)},I.neq=I.notEquals,I.ne=I.notEquals,I.lessThan=function(e){return this.comp(e)<0},I.lt=I.lessThan,I.lessThanOrEqual=function(e){return this.comp(e)<=0},I.lte=I.lessThanOrEqual,I.le=I.lessThanOrEqual,I.greaterThan=function(e){return this.comp(e)>0},I.gt=I.greaterThan,I.greaterThanOrEqual=function(e){return this.comp(e)>=0},I.gte=I.greaterThanOrEqual,I.ge=I.greaterThanOrEqual,I.compare=function(e){if(n(e)||(e=c(e)),this.eq(e))return 0;var t=this.isNegative(),r=e.isNegative();return t&&!r?-1:!t&&r?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},I.comp=I.compare,I.negate=function(){return!this.unsigned&&this.eq(k)?k:this.not().add(y)},I.neg=I.negate,I.add=function(e){n(e)||(e=c(e));var t=this.high>>>16,r=65535&this.high,a=this.low>>>16,s=65535&this.low,o=e.high>>>16,u=65535&e.high,l=e.low>>>16,d=0,p=0,h=0,f=0;return h+=(f+=s+(65535&e.low))>>>16,p+=(h+=a+l)>>>16,d+=(p+=r+u)>>>16,d+=t+o,i((h&=65535)<<16|(f&=65535),(d&=65535)<<16|(p&=65535),this.unsigned)},I.subtract=function(e){return n(e)||(e=c(e)),this.add(e.neg())},I.sub=I.subtract,I.multiply=function(t){if(this.isZero())return m;if(n(t)||(t=c(t)),e)return i(e.mul(this.low,this.high,t.low,t.high),e.get_high(),this.unsigned);if(t.isZero())return m;if(this.eq(k))return t.isOdd()?k:m;if(t.eq(k))return this.isOdd()?k:m;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(f)&&t.lt(f))return o(this.toNumber()*t.toNumber(),this.unsigned);var r=this.high>>>16,a=65535&this.high,s=this.low>>>16,u=65535&this.low,l=t.high>>>16,d=65535&t.high,p=t.low>>>16,h=65535&t.low,g=0,y=0,b=0,x=0;return b+=(x+=u*h)>>>16,y+=(b+=s*h)>>>16,b&=65535,y+=(b+=u*p)>>>16,g+=(y+=a*h)>>>16,y&=65535,g+=(y+=s*p)>>>16,y&=65535,g+=(y+=u*d)>>>16,g+=r*h+a*p+s*d+u*l,i((b&=65535)<<16|(x&=65535),(g&=65535)<<16|(y&=65535),this.unsigned)},I.mul=I.multiply,I.divide=function(t){if(n(t)||(t=c(t)),t.isZero())throw Error("division by zero");var r,a,s;if(e)return this.unsigned||-2147483648!==this.high||-1!==t.low||-1!==t.high?i((this.unsigned?e.div_u:e.div_s)(this.low,this.high,t.low,t.high),e.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?g:m;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return g;if(t.gt(this.shru(1)))return b;s=g}else{if(this.eq(k))return t.eq(y)||t.eq(x)?k:t.eq(k)?y:(r=this.shr(1).div(t).shl(1)).eq(m)?t.isNegative()?y:x:(a=this.sub(t.mul(r)),s=r.add(a.div(t)));if(t.eq(k))return this.unsigned?g:m;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();s=m}for(a=this;a.gte(t);){r=Math.max(1,Math.floor(a.toNumber()/t.toNumber()));for(var l=Math.ceil(Math.log(r)/Math.LN2),d=l<=48?1:u(2,l-48),p=o(r),h=p.mul(t);h.isNegative()||h.gt(a);)h=(p=o(r-=d,this.unsigned)).mul(t);p.isZero()&&(p=y),s=s.add(p),a=a.sub(h)}return s},I.div=I.divide,I.modulo=function(t){return n(t)||(t=c(t)),e?i((this.unsigned?e.rem_u:e.rem_s)(this.low,this.high,t.low,t.high),e.get_high(),this.unsigned):this.sub(this.div(t).mul(t))},I.mod=I.modulo,I.rem=I.modulo,I.not=function(){return i(~this.low,~this.high,this.unsigned)},I.and=function(e){return n(e)||(e=c(e)),i(this.low&e.low,this.high&e.high,this.unsigned)},I.or=function(e){return n(e)||(e=c(e)),i(this.low|e.low,this.high|e.high,this.unsigned)},I.xor=function(e){return n(e)||(e=c(e)),i(this.low^e.low,this.high^e.high,this.unsigned)},I.shiftLeft=function(e){return n(e)&&(e=e.toInt()),0===(e&=63)?this:e<32?i(this.low<>>32-e,this.unsigned):i(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):i(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},I.shr=I.shiftRight,I.shiftRightUnsigned=function(e){if(n(e)&&(e=e.toInt()),0===(e&=63))return this;var t=this.high;return e<32?i(this.low>>>e|t<<32-e,t>>>e,this.unsigned):i(32===e?t:t>>>e-32,0,this.unsigned)},I.shru=I.shiftRightUnsigned,I.shr_u=I.shiftRightUnsigned,I.toSigned=function(){return this.unsigned?i(this.low,this.high,!1):this},I.toUnsigned=function(){return this.unsigned?this:i(this.low,this.high,!0)},I.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},I.toBytesLE=function(){var e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]},I.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]},t.fromBytes=function(e,n,r){return r?t.fromBytesLE(e,n):t.fromBytesBE(e,n)},t.fromBytesLE=function(e,n){return new t(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,n)},t.fromBytesBE=function(e,n){return new t(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],n)},pr}();const br=/* @__PURE__ */mr(yr),xr=br||/* @__PURE__ */e({__proto__:null,default:br},[yr]);function vr(e){return xr.fromString(e,!0,16)}const wr=vr("c3a5c85c97cb3127"),kr=vr("b492b66fbe98f273"),Ir=vr("9ae16a3b2f90404f");function Nr(e){return e.xor(e.shru(47))}function Sr(e,t,n){const r=e.slice(t,t+n);return xr.fromBytes(Array.from(r),!0,!0)}function Tr(e,t){return Sr(e,t,8)}function Cr(e,t){return Sr(e,t,4)}function $r(e,t){return 0===t?e:e.shru(t).or(e.shl(64-t))}function Er(e,t,n=vr("9ddfea08eb382d69")){let r=e.xor(t).mul(n);r=r.xor(r.shru(47));let a=t.xor(r).mul(n);return a=a.xor(a.shru(47)),a=a.mul(n),a}function Rr(e,t,n,r){return function(e,t,n,r,a,s){a=a.add(e),s=$r(s.add(a).add(r),21);const o=a;return a=(a=a.add(t)).add(n),s=s.add($r(a,44)),[a.add(r),s.add(o)]}(Tr(e,t),Tr(e,t+8),Tr(e,t+16),Tr(e,t+24),n,r)}function _r(e,t=e.length){const n=xr.fromNumber(81,!0);if(t<=32)return t<=16?function(e,t=e.length){if(t>=8){const n=Ir.add(2*t),r=Tr(e,0).add(Ir),a=Tr(e,t-8);return Er($r(a,37).mul(n).add(r),$r(r,25).add(a).mul(n),n)}if(t>=4){const n=Ir.add(2*t);return Er(Cr(e,0).shl(3).add(t),Cr(e,t-4),n)}if(t>0){const n=e[0]+(e[t>>1]<<8),r=t+(e[t-1]<<2);return Nr(Ir.mul(n).xor(wr.mul(r))).mul(Ir)}return Ir}(e,t):function(e,t=e.length){const n=Ir.add(2*t),r=Tr(e,0).mul(kr),a=Tr(e,8),s=Tr(e,t-8).mul(n),o=Tr(e,t-16).mul(Ir);return Er($r(r.add(a),43).add($r(s,30)).add(o),r.add($r(a.add(Ir),18)).add(s),n)}(e,t);if(t<=64)return function(e,t=e.length){const n=Ir.add(2*t),r=Tr(e,0).mul(Ir),a=Tr(e,8),s=Tr(e,t-8).mul(n),o=Tr(e,t-16).mul(Ir),i=$r(r.add(a),43).add($r(s,30)).add(o),u=Er(i,r.add($r(a.add(Ir),18)).add(s),n),l=Tr(e,16).mul(n),c=Tr(e,24),d=i.add(Tr(e,t-32)).mul(n),p=u.add(Tr(e,t-24)).mul(n);return Er($r(l.add(c),43).add($r(d,30)).add(p),l.add($r(c.add(r),18)).add(d),n)}(e,t);let r=n,a=n.mul(kr).add(113),s=Nr(a.mul(Ir).add(113)).mul(Ir),o=[xr.UZERO,xr.UZERO],i=[xr.UZERO,xr.UZERO];r=r.mul(Ir).add(Tr(e,0));let u=0;const l=64*(t-1>>6),c=l+(t-1&63)-63;do{r=$r(r.add(a).add(o[0]).add(Tr(e,u+8)),37).mul(kr),a=$r(a.add(o[1]).add(Tr(e,u+48)),42).mul(kr),r=r.xor(i[1]),a=a.add(o[0]).add(Tr(e,u+40)),s=$r(s.add(i[0]),33).mul(kr),o=Rr(e,u,o[1].mul(kr),r.add(i[0])),i=Rr(e,u+32,s.add(i[1]),a.add(Tr(e,u+16))),[s,r]=[r,s],u+=64}while(u!==l);const d=kr.add(s.and(255).shl(1));return u=c,i[0]=i[0].add(t-1&63),o[0]=o[0].add(i[0]),i[0]=i[0].add(o[0]),r=$r(r.add(a).add(o[0]).add(Tr(e,u+8)),37).mul(d),a=$r(a.add(o[1]).add(Tr(e,u+48)),42).mul(d),r=r.xor(i[1].mul(9)),a=a.add(o[0].mul(9).add(Tr(e,u+40))),s=$r(s.add(i[0]),33).mul(d),o=Rr(e,u,o[1].mul(d),r.add(i[0])),i=Rr(e,u+32,s.add(i[1]),a.add(Tr(e,u+16))),[s,r]=[r,s],Er(Er(o[0],i[0],d).add(Nr(a).mul(wr)).add(s),Er(o[1],i[1],d).add(r),d)}function Ar(e,t){return"string"===t?Dr(e):Or([e],t)}function Or(e,t){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=Lr(e)),V().getBool("DEBUG")&&function(e,t){for(let n=0;n{r=n()};let s;const o=Fr();if(this.backendTimer.timerAvailable())s=this.backendTimer.time(a);else{a();for(const e of r)e.dataSync();s=Promise.resolve({kernelMs:Fr()-o})}if(V().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let i=0;i{Vr(n,t.dtype,e)})}return{kernelName:e,outputs:r,inputs:t,timeMs:s.then(e=>e.kernelMs),extraInfo:s.then(e=>null!=e.getExtraProfileInfo?e.getExtraProfileInfo():"")}}logKernelProfile(e){const{kernelName:t,outputs:n,timeMs:r,inputs:a,extraInfo:s}=e;n.forEach(e=>{Promise.all([e.data(),r,s]).then(n=>{this.logger.logKernelProfile(t,e,n[0],n[1],a,n[2])})})}}function Vr(e,t,n){if("float32"!==t)return!1;for(let r=0;r0?n:""} `}}console.log(`%c${i}\t%c${o}\t%c${u}D ${c}\t%c${l}\t%c${d}\t%c${s}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}function zr(e,t,n,r){const a=C(t),s=function(e,t,n,r){const a=c(t),s=r[r.length-1],o=new Array(s).fill(0),i=t.length,u="complex64"===n?jr(e):e;if(i>1)for(let l=0;l" "+e).join("\n")),u.join("\n")}function Ur(e,t,n){let r;return r=Array.isArray(e)?`${parseFloat(e[0].toFixed(7))} + ${parseFloat(e[1].toFixed(7))}j`:I(e)?`'${e}'`:"bool"===n?Gr(e):parseFloat(e.toFixed(7)).toString(),f(r,t)}function Gr(e){return 0===e?"false":"true"}function Hr(e,t,n,r,a,s=!0){const o="complex64"===n?2:1,i=t[0],u=t.length;if(0===u){if("complex64"===n){return[Ur(jr(e)[0],0,n)]}return"bool"===n?[Gr(e[0])]:[e[0].toString()]}if(1===u){if(i>20){const t=3*o;let r=Array.from(e.slice(0,t)),s=Array.from(e.slice((i-3)*o,i*o));return"complex64"===n&&(r=jr(r),s=jr(s)),["["+r.map((e,t)=>Ur(e,a[t],n)).join(", ")+", ..., "+s.map((e,t)=>Ur(e,a[i-3+t],n)).join(", ")+"]"]}return["["+("complex64"===n?jr(e):Array.from(e)).map((e,t)=>Ur(e,a[t],n)).join(", ")+"]"]}const l=t.slice(1),c=r.slice(1),d=r[0]*o,p=[];if(i>20){for(let t=0;t<3;t++){const r=t*d,s=r+d;p.push(...Hr(e.slice(r,s),l,n,c,a,!1))}p.push("...");for(let t=i-3;t0?p[0]+h:"");for(let m=1;m`Length of values '${e}' does not match the size inferred by the shape '${this.size}'.`)}if("complex64"===t)throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||v(t,this.size),this.strides=C(e)}set(e,...t){0===t.length&&(t=[0]),i(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);const n=this.locToIndex(t);this.values[n]=e}get(...e){0===e.length&&(e=[0]);let t=0;for(const r of e){if(r<0||r>=this.shape[t]){const t=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(t)}t++}let n=e[e.length-1];for(let r=0;rMr(e))}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataToGPU(e){return this.throwIfDisposed(),Kr().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();const e=Kr().readSync(this.dataId);if("string"===this.dtype)try{return e.map(e=>Mr(e))}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e}async bytes(){this.throwIfDisposed();const e=await Kr().read(this.dataId);return"string"===this.dtype?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(this.kerasMask&&this.kerasMask.dispose(),Kr().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Xr.print(this,e)}clone(){return this.throwIfDisposed(),Xr.clone(this)}toString(e=!1){return zr(this.dataSync(),this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Xr.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Kr().makeVariable(this,e,t,n)}}function Qr(){return G("Tensor",()=>Yr)}Object.defineProperty(Yr,Symbol.hasInstance,{value:e=>!!e&&null!=e.data&&null!=e.dataSync&&null!=e.throwIfDisposed}),Qr();class Zr extends Yr{constructor(e,t,n,r){super(e.shape,e.dtype,e.dataId,r),this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!d(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Kr().disposeTensor(this),this.dataId=e.dataId,Kr().incRef(this,null)}dispose(){Kr().disposeVariable(this),this.isDisposedInternal=!0}}var Jr,ea,ta,na,ra,aa,sa,oa,ia,ua;Object.defineProperty(Zr,Symbol.hasInstance,{value:e=>e instanceof Yr&&null!=e.assign&&e.assign instanceof Function}),(ea=Jr||(Jr={})).R0="R0",ea.R1="R1",ea.R2="R2",ea.R3="R3",ea.R4="R4",ea.R5="R5",ea.R6="R6",(na=ta||(ta={})).float32="float32",na.int32="int32",na.bool="int32",na.complex64="complex64",(aa=ra||(ra={})).float32="float32",aa.int32="int32",aa.bool="bool",aa.complex64="complex64",(oa=sa||(sa={})).float32="float32",oa.int32="float32",oa.bool="float32",oa.complex64="complex64",(ua=ia||(ia={})).float32="complex64",ua.int32="complex64",ua.bool="complex64",ua.complex64="complex64";const la={float32:sa,int32:ta,bool:ra,complex64:ia};function ca(e,t){if("string"===e||"string"===t){if("string"===e&&"string"===t)return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return la[e][t]}function da(e){return ca(e,"int32")}function pa(e){return null!=e&&"object"===typeof e&&"texture"in e&&e.texture instanceof WebGLTexture}function ha(e){return"undefined"!==typeof GPUBuffer&&null!=e&&"object"===typeof e&&"buffer"in e&&e.buffer instanceof GPUBuffer}function fa(e,t){if(e.dtype===t.dtype)return[e,t];const n=ca(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function ma(e){const t=[];return ga(e,t,/* @__PURE__ */new Set),t}function ga(e,t,n){if(null==e)return;if(e instanceof Yr)return void t.push(e);if(r=e,!Array.isArray(r)&&"object"!==typeof r)return;var r;const a=e;for(const s in a){const e=a[s];n.has(e)||(n.add(e),ga(e,t,n))}}function ya(e){return null!=e.kernelName}class ba{constructor(){this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.gradientDepth=0,this.kernelDepth=0,this.scopeStack=[],this.numDataMovesStack=[],this.nextScopeId=0,this.tensorInfo=/* @__PURE__ */new WeakMap,this.profiling=!1,this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null,get kernelNames(){return Array.from(new Set(this.kernels.map(e=>e.name)))}}}dispose(){for(const e in this.registeredVariables)this.registeredVariables[e].dispose()}}class xa{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new ba}async ready(){if(null!=this.pendingBackendInit)return this.pendingBackendInit.then(()=>{});if(null!=this.backendInstance)return;const e=this.getSortedBackends();for(let t=0;t{null!=e.setupFunc&&e.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){ur(e).forEach(t=>{null!=t.disposeFunc&&t.disposeFunc(this.registry[e])})}initializeBackend(e){const t=this.registryFactory[e];if(null==t)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{const r=t.factory();if(!r||r instanceof n||"function"!==typeof r.then)return this.registry[e]=r,{success:!0,asyncInit:!1};{const t=++this.pendingBackendInitId,n=r.then(n=>!(t(tthis.registryFactory[t].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){const e=this.getSortedBackends();for(let t=0;tthis.startScope(r),()=>this.endScope(n),()=>(n=t(),n instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n))}scopedRun(e,t,n){e();try{const e=n();return t(),e}catch(r){throw t(),r}}nextTensorId(){return xa.nextTensorId++}nextVariableId(){return xa.nextVariableId++}clone(e){const t=wa.runKernel(ot,{x:e}),n={x:e};return this.addTapeNode(this.state.activeScope.name,n,[t],e=>({x:()=>{const t={x:e},n={dtype:"float32"};return wa.runKernel(fe,t,n)}}),[],{}),t}runKernel(e,t,n){null==this.backendName&&this.backend;if(!(null!=or(e,this.backendName)))throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){const r=this.backend.numDataIds();let a=0;n.forEach(e=>{a+="complex64"===e.dtype?3:1});const s=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],o=r-t-a-s;if(o>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${o} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[];const r=this.isTapeOn(),a=this.state.numBytes,s=this.state.numTensors;let o,u;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0),null==this.backendName&&this.backend;const l=ya(e)?e.kernelName:null!=this.state.activeScope?this.state.activeScope.name:"";if(ya(e)){const{kernelName:t,inputs:a,attrs:s}=e;null==this.backendName&&this.backend;const l=or(t,this.backendName);i(null!=l,()=>`Cannot find registered kernel '${t}' for backend '${this.backendName}'`),o=()=>{const e=this.backend.numDataIds();u=l.kernelFunc({inputs:a,attrs:s,backend:this.backend});const o=Array.isArray(u)?u:[u];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(t,e,o);const i=o.map(e=>null!=e.rank?e:this.makeTensorFromTensorInfo(e));if(r){const e=this.getTensorsForGradient(t,a,i);n=this.saveTensorsForBackwardMode(e)}return i}}else{const{forwardFunc:t}=e,a=e=>{r&&(n=e.map(e=>this.keep(this.clone(e))))};o=()=>{const e=this.backend.numDataIds();u=this.tidy(()=>t(this.backend,a));const n=Array.isArray(u)?u:[u];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,e,n),n}}const{inputs:c,attrs:d}=e,p=ya(e)?null:e.backwardsFunc;let h;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{this.ENV.getBool("DEBUG")||this.state.profiling?(h=this.profiler.profileKernel(l,c,()=>o()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(h),t=h.outputs):t=o()}),r&&this.addTapeNode(l,c,t,p,n,d),this.state.profiling&&this.state.activeProfile.kernels.push({name:l,bytesAdded:this.state.numBytes-a,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-s,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(c).map(e=>null!=c[e]?c[e].shape:null),outputShapes:t.map(e=>e.shape),kernelTimeMs:h.timeMs,extraInfo:h.extraInfo}),Array.isArray(u)?t:t[0]}saveTensorsForBackwardMode(e){return e.map(e=>this.keep(this.clone(e)))}getTensorsForGradient(e,t,n){const r=ir(e);if(null!=r){const e=r.inputsToSave||[],a=r.outputsToSave||[];let s;r.saveAllInputs?(i(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),s=Object.keys(t).map(e=>t[e])):s=e.map(e=>t[e]);const o=n.filter((e,t)=>a[t]);return s.concat(o)}return[]}makeTensor(e,t,n,r){if(null==e)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",r=r||this.backend;let a=e;"string"===n&&I(e[0])&&(a=e.map(e=>Dr(e)));const s=r.write(a,t,n),o=new Yr(t,n,s,this.nextTensorId());if(this.trackTensor(o,r),"string"===n){const e=this.state.tensorInfo.get(s),t=function(e){if(null==e)return 0;let t=0;return e.forEach(e=>t+=e.length),t}(a);this.state.numBytes+=t-e.bytes,e.bytes=t}return o}makeTensorFromDataId(e,t,n,r){const a={dataId:e,shape:t,dtype:n=n||"float32"};return this.makeTensorFromTensorInfo(a,r)}makeTensorFromTensorInfo(e,t){const{dataId:n,shape:r,dtype:a}=e,s=new Yr(r,a,n,this.nextTensorId());return this.trackTensor(s,t),s}makeVariable(e,t=!0,n,r){n=n||this.nextVariableId().toString(),null!=r&&r!==e.dtype&&(e=e.cast(r));const a=new Zr(e,t,n,this.nextTensorId());if(null!=this.state.registeredVariables[a.name])throw new Error(`Variable with name ${a.name} was already registered`);return this.state.registeredVariables[a.name]=a,this.incRef(a,this.backend),a}trackTensor(e,t){this.state.numTensors++,"string"===e.dtype&&this.state.numStringTensors++;let n=0;"complex64"!==e.dtype&&"string"!==e.dtype&&(n=e.size*k(e.dtype)),this.state.numBytes+=n,this.state.tensorInfo.has(e.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:n})),e instanceof Zr||this.track(e)}incRef(e,t){this.trackTensor(e,t),this.backend.incRef(e.dataId)}removeDataId(e,t){this.state.tensorInfo.has(e)&&this.state.tensorInfo.get(e).backend===t&&(this.state.tensorInfo.delete(e),this.state.numDataBuffers--)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;const t=this.state.tensorInfo.get(e.dataId);if(this.state.numTensors--,"string"===e.dtype&&(this.state.numStringTensors--,this.state.numBytes-=t.bytes),"complex64"!==e.dtype&&"string"!==e.dtype){const t=e.size*k(e.dtype);this.state.numBytes-=t}t.backend.disposeData(e.dataId)&&this.removeDataId(e.dataId,t.backend)}disposeVariables(){for(const e in this.state.registeredVariables){const t=this.state.registeredVariables[e];this.disposeVariable(t)}}disposeVariable(e){this.disposeTensor(e),null!=this.state.registeredVariables[e.name]&&delete this.state.registeredVariables[e.name]}memory(){const e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,null==e.reasons&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e}async profile(e){this.state.profiling=!0;const t=this.state.numBytes,n=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map(e=>e.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(const r of this.state.activeProfile.kernels)r.kernelTimeMs=await r.kernelTimeMs,r.extraInfo=await r.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&0===this.state.kernelDepth}addTapeNode(e,t,n,r,a,s){const o={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:a},i=ir(e);null!=i&&(r=i.gradFunc),null!=r&&(o.gradient=e=>(e=e.map((e,t)=>{if(null==e){const e=n[t],r=_(e.size,e.dtype);return this.makeTensor(r,e.shape,e.dtype)}return e}),r(e.length>1?e:e[0],a,s))),this.state.activeTape.push(o)}keep(e){return e.kept=!0,e}startTape(){0===this.state.gradientDepth&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){const t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){const t=ma(e),n=new Set(t.map(e=>e.id));for(let a=0;a{e.kept||e.scopeId!==r.id||this.track(e)})}gradients(e,t,n,r=!1){if(i(t.length>0,()=>"gradients() received an empty list of xs."),null!=n&&"float32"!==n.dtype)throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`);const a=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));i(a instanceof Yr,()=>"The result y returned by f() must be a tensor.");const s=function(e,t,n){const r={},a={};for(let u=0;ur[e.id]=!0),i=!0,a[n.id]=!0;break}if(i)break}}const s={};s[n.id]=!0;const o={};for(let u=e.length-1;u>=0;u--){const t=e[u],n=t.inputs;for(let e=0;e0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",()=>{const e={};e[a.id]=n??function(e){const t=R(c(e),"float32");return wa.makeTensor(t,e,"float32")}(a.shape),function(e,t,n,r){for(let a=t.length-1;a>=0;a--){const s=t[a],o=[];if(s.outputs.forEach(t=>{const n=e[t.id];null!=n?o.push(n):o.push(null)}),null==s.gradient)throw new Error(`Cannot compute gradient: gradient function not found for ${s.kernelName}.`);const i=s.gradient(o);for(const t in s.inputs){if(!(t in i))throw new Error(`Cannot backprop through input ${t}. Available gradients found: ${Object.keys(i)}.`);const a=n(()=>i[t]());if("float32"!==a.dtype)throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input ${t} must have 'float32' dtype, but has '${a.dtype}'`);const o=s.inputs[t];if(!d(a.shape,o.shape))throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input '${t}' has shape '${a.shape}', which does not match the shape of the input '${o.shape}'`);if(null==e[o.id])e[o.id]=a;else{const t=e[o.id];e[o.id]=r(t,a),t.dispose()}}}}(e,s,e=>this.tidy(e),ka);const r=t.map(t=>e[t.id]);return 0===this.state.gradientDepth&&(this.state.activeTape.forEach(e=>{for(const t of e.saved)t.dispose()}),this.state.activeTape=null),{value:a,grads:r}})}customGrad(e){return i(S(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{let n;i(t.every(e=>e instanceof Yr),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");const r={};t.forEach((e,t)=>{r[t]=e});return this.runKernelFunc({forwardFunc:(r,a)=>(n=e(...t,a),i(n.value instanceof Yr,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),i(S(n.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),n.value),backwardsFunc:(e,r)=>{const a=n.gradFunc(e,r),s=Array.isArray(a)?a:[a];i(s.length===t.length,()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."),i(s.every(e=>e instanceof Yr),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");const o={};return s.forEach((e,t)=>{o[t]=()=>e}),o},inputs:r})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}readToGPU(e,t){return this.state.tensorInfo.get(e).backend.readToGPU(e,t)}async time(e){const t=Fr(),n=await this.backend.time(e);return n.wallMs=Fr()-t,n}track(e){return null!=this.state.activeScope&&(e.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(e)),e}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new ba;for(const e in this.registry)this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}}function va(){const e=U();if(null==e._tfengine){const t=new L(e);e._tfengine=new xa(t)}var t;return t=e._tfengine.ENV,z=t,Kr=()=>e._tfengine,e._tfengine}xa.nextTensorId=0,xa.nextVariableId=0;const wa=va();function ka(e,t){const n={a:e,b:t};return wa.runKernel(K,n)}function Ia(e){if(e||"undefined"!==typeof navigator&&null!=navigator){if(e||(e=navigator),"ReactNative"===e.product)return!0;const t=e.userAgent||e.vendor||("undefined"!==typeof window?window.opera:"");if(!t){const t=e;return t.userAgentData&&t.userAgentData.mobile}return/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(t)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(t.substr(0,4))}return!1}function Na(){return"undefined"!==typeof window&&null!=window.document||"undefined"!==typeof WorkerGlobalScope}const Sa=V();function Ta(e,t){let n=e;if(Pr(e))return"string"===t?[]:[e.length];if(pa(e)){const t=e.channels||"RGBA";return[e.height,e.width*t.length]}if(ha(e))return[e.buffer.size/(null==t?4:k(t))];if(!Array.isArray(e))return[];const r=[];for(;Array.isArray(n)||Pr(n)&&"string"!==t;)r.push(n.length),n=n[0];return Array.isArray(e)&&V().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&Ca(e,r,[]),r}function Ca(e,t,n){if(n=n||[],!Array.isArray(e)&&!Pr(e))return void i(0===t.length,()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);i(t.length>0,()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`),i(e.length===t[0],()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`);const r=t.slice(1);for(let a=0;a=0&&(a=r),$a(r,a,t,n),null==e||!Pr(e)&&!Array.isArray(e)&&"number"!==typeof e&&"boolean"!==typeof e&&"string"!==typeof e){const r=null==e?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${n}' must be a Tensor or TensorLike, but got '${r}'`)}const s=Ta(e,a);Pr(e)||Array.isArray(e)||(e=[e]);const o="string"!==a?Or(e,a):Lr(e,[],!0);return wa.makeTensor(o,s,a)}function Ra(e,t,n,r="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);return e.map((e,a)=>Ea(e,`${t}[${a}]`,n,r))}Sa.registerFlag("DEBUG",()=>!1,e=>{e&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")}),Sa.registerFlag("IS_BROWSER",()=>Na()),Sa.registerFlag("IS_NODE",()=>"undefined"!==typeof process&&"undefined"!==typeof process.versions&&"undefined"!==typeof process.versions.node),Sa.registerFlag("IS_CHROME",()=>"undefined"!==typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)),Sa.registerFlag("IS_SAFARI",()=>"undefined"!==typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Safari/.test(navigator.userAgent)&&/Apple/.test(navigator.vendor)),Sa.registerFlag("PROD",()=>!1),Sa.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Sa.getBool("DEBUG")),Sa.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0),Sa.registerFlag("IS_TEST",()=>!1),Sa.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>Sa.getBool("DEBUG")),Sa.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1),Sa.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU",()=>!1),Sa.registerFlag("USE_SETTIMEOUTCUSTOM",()=>!1);const _a="__op";function Aa(e){const t=Object.keys(e);if(1!==t.length)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${t.length} keys.`);let n=t[0];const r=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1)),n+=_a;const a=(...e)=>{wa.startScope(n);try{const t=r(...e);return M(t)&&console.error("Cannot return a Promise inside of tidy."),wa.endScope(t),t}catch(t){throw wa.endScope(null),t}};return Object.defineProperty(a,"name",{value:n,configurable:!0}),a}const Oa=/* @__PURE__ */Aa({complex_:function(e,t){const n=Ea(e,"real","complex"),r=Ea(t,"imag","complex");u(n.shape,r.shape,`real and imag shapes, ${n.shape} and ${r.shape}, must match in call to tf.complex().`);const a={real:n,imag:r};return wa.runKernel(ye,a)}});function Fa(e,t,n,r){if(null==r)r=N(e);else if("complex64"===r)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(ha(e)||pa(e)){if("float32"!==r&&"int32"!==r)throw new Error(`Creating tensor from GPU data only supports 'float32'|'int32' dtype, while the dtype is ${r}.`);return wa.backend.createTensorFromGPUData(e,t||n,r)}if(!Pr(e)&&!Array.isArray(e)&&"number"!==typeof e&&"boolean"!==typeof e&&"string"!==typeof e)throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(null!=t){O(t);const e=c(t),r=c(n);i(e===r,()=>`Based on the provided shape, [${t}], the tensor should have ${e} values but has ${r}`);for(let a=0;a`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `)}}return Pr(e)||Array.isArray(e)||(e=[e]),t=t||n,e="string"!==r?Or(e,r):Lr(e,[],!0),wa.makeTensor(e,t,r)}function Da(e,t,n){return Fa(e,t,Ta(e,n),n)}const Ma={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};class Pa{static join(e){return new Pa(e).slice()}constructor(e){if(this.shards=[],this.previousShardIndex=0,null==e)return;if(e instanceof Array||(e=[e]),0===(e=e.map(e=>Pr(e)?e.buffer:e)).length)return;this.bufferUniformSize=e[0].byteLength;let t=0;for(let n=0;n=this.byteLength)return-1;if(null!=this.bufferUniformSize)return this.previousShardIndex=Math.floor(e/this.bufferUniformSize),this.previousShardIndex;function t(t){return e=t.end?1:0}if(0===t(this.shards[this.previousShardIndex]))return this.previousShardIndex;const n=function(e,t){let n=0,r=e.length;for(;n<=r;){const a=Math.floor((r-n)/2)+n,s=t(e[a]);if(0===s)return a;s<0?r=a:n=a+1}return-1}(this.shards,t);return-1===n?-1:(this.previousShardIndex=n,this.previousShardIndex)}}function La(){return wa}function Ba(e,t){return wa.tidy(e,t)}function Va(e){ma(e).forEach(e=>e.dispose())}function Wa(e){return wa.keep(e)}function za(e){return wa.setBackend(e)}function Ua(){return wa.backendName}function Ga(e,t,n=1){return wa.registerBackend(e,t,n)}function Ha(){return wa.backend}function ja(e,t){const n=new Pa(e),r={};let a=0;for(const s of t){const e=qa(s,(e,t)=>n.slice(a+e,a+t));r[s.name]=Xa(s,n.slice(a,a+e)),a+=e}return r}function qa(e,t){const n=c(e.shape);let r;if("quantization"in e){const t=e.quantization;r=Ma[t.dtype]}else{if("string"===e.dtype){let e=0;for(let r=0;r{let t=e<<13,n=0;for(;0===(8388608&t);)n-=8388608,t<<=1;return t&=-8388609,n+=947912704,t|n},t=new Uint32Array(2048);t[0]=0;for(let n=1;n<1024;n++)t[n]=e(n);for(let n=1024;n<2048;n++)t[n]=939524096+(n-1024<<13);return t}(),t=function(){const e=new Uint32Array(64);e[0]=0,e[31]=1199570944,e[32]=2147483648,e[63]=3347054592;for(let t=1;t<31;t++)e[t]=t<<23;for(let t=33;t<63;t++)e[t]=2147483648+(t-32<<23);return e}(),n=function(){const e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}();return r=>{const a=new ArrayBuffer(4*r.length),s=new Uint32Array(a);for(let o=0;o>10]+(1023&a)]+t[a>>10];s[o]=i}return new Float32Array(a)}}();o=e(l)}}else{if("int32"!==r)throw new Error(`Unsupported dtype in weight '${n}': ${r}`);if("uint8"!==a.dtype&&"uint16"!==a.dtype)throw new Error(`Unsupported quantization type ${a.dtype} for weight type int32.`);o=new Int32Array(l.length);for(let e=0;e(a=await Ya(r,a,t),a.slice(e,t)));a=await Ya(r,a,e);const t=a.slice(0,e);a=a.slice(e);const o=Xa(s,t);if(n[s.name]=o,"webgpu"===Ua()){const e=Ha();"uploadToGPU"in e&&c(o.shape)>=V().get("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD")&&e.uploadToGPU(o.dataId)}}return n}function Za(e){if(null===e)throw new Error(`Invalid input value: ${JSON.stringify(e)}`);let t=0;const n=[];e.forEach(e=>{if(t+=e.byteLength,n.push(e.byteLength===e.buffer.byteLength?e:new e.constructor(e)),!(e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${e.constructor.name}`)});const r=new Uint8Array(t);let a=0;return n.forEach(e=>{r.set(new Uint8Array(e.buffer),a),a+=e.byteLength}),r.buffer}const Ja="undefined"!==typeof Buffer&&("undefined"===typeof Blob||"undefined"===typeof atob||"undefined"===typeof btoa);function es(e){return Ja?Buffer.byteLength(e,"utf8"):new Blob([e]).size}function ts(e){for(e=e.trim();e.endsWith("/");)e=e.slice(0,e.length-1);const t=e.split("/");return t[t.length-1]}function ns(e,t){const n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:t};return null!=e.signature&&(n.signature=e.signature),null!=e.userDefinedMetadata&&(n.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(n.modelInitializer=e.modelInitializer),null!=e.initializerSignature&&(n.initializerSignature=e.initializerSignature),null!=e.trainingConfig&&(n.trainingConfig=e.trainingConfig),n}function rs(e,t,n){const r={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};if(null!=e.trainingConfig&&(r.trainingConfig=e.trainingConfig),null!=e.weightsManifest){if(!t)throw new Error("modelJSON has weightsManifest but weightSpecs is null");if(!n)throw new Error("modelJSON has weightsManifest but weightData is null");r.weightSpecs=t,r.weightData=n}return null!=e.signature&&(r.signature=e.signature),null!=e.userDefinedMetadata&&(r.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(r.modelInitializer=e.modelInitializer),null!=e.initializerSignature&&(r.initializerSignature=e.initializerSignature),r}async function as(e,t){let n,r;return null!=e.weightsManifest&&([n,r]=await t(e.weightsManifest)),rs(e,n,r)}function ss(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:/* @__PURE__ */new Date,modelTopologyType:"JSON",modelTopologyBytes:null==e.modelTopology?0:es(JSON.stringify(e.modelTopology)),weightSpecsBytes:null==e.weightSpecs?0:es(JSON.stringify(e.weightSpecs)),weightDataBytes:null==e.weightData?0:new Pa(e.weightData).byteLength}}function os(e){const t=[];for(const n of e)t.push(...n.weights);return t}class is{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return null==is.instance&&(is.instance=new is),is.instance}static registerSaveRouter(e){is.getInstance().saveRouters.push(e)}static registerLoadRouter(e){is.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return is.getHandlers(e,"save")}static getLoadHandlers(e,t){return is.getHandlers(e,"load",t)}static getHandlers(e,t,n){const r=[];return("load"===t?is.getInstance().loadRouters:is.getInstance().saveRouters).forEach(t=>{const a=t(e,n);null!==a&&r.push(a)}),r}}const us="tensorflowjs",ls="models_store",cs="model_info_store";function ds(){if(!V().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");const e="undefined"===typeof window?self:window,t=e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB||e.shimIndexedDB;if(null==t)throw new Error("The current browser does not appear to support IndexedDB.");return t}function ps(e){const t=e.result;t.createObjectStore(ls,{keyPath:"modelPath"}),t.createObjectStore(cs,{keyPath:"modelPath"})}class hs{constructor(e){if(this.indexedDB=ds(),null==e||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return this.databaseAction(this.modelPath,e)}async load(){return this.databaseAction(this.modelPath)}databaseAction(e,t){return new Promise((e,n)=>{const r=this.indexedDB.open(us,1);r.onupgradeneeded=()=>ps(r),r.onsuccess=()=>{const a=r.result;if(null==t){const t=a.transaction(ls,"readonly"),r=t.objectStore(ls).get(this.modelPath);r.onsuccess=()=>{if(null==r.result)return a.close(),n(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));e(r.result.modelArtifacts)},r.onerror=e=>(a.close(),n(r.error)),t.oncomplete=()=>a.close()}else{t.weightData=Pa.join(t.weightData);const r=ss(t),o=a.transaction(cs,"readwrite");let i,u,l=o.objectStore(cs);try{i=l.put({modelPath:this.modelPath,modelArtifactsInfo:r})}catch(s){return n(s)}i.onsuccess=()=>{u=a.transaction(ls,"readwrite");const i=u.objectStore(ls);let c;try{c=i.put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:r})}catch(s){return n(s)}c.onsuccess=()=>e({modelArtifactsInfo:r}),c.onerror=e=>{l=o.objectStore(cs);const t=l.delete(this.modelPath);t.onsuccess=()=>(a.close(),n(c.error)),t.onerror=e=>(a.close(),n(c.error))}},i.onerror=e=>(a.close(),n(i.error)),o.oncomplete=()=>{null==u?a.close():u.oncomplete=()=>a.close()}}},r.onerror=e=>n(r.error)})}}hs.URL_SCHEME="indexeddb://";const fs=e=>{return V().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(hs.URL_SCHEME)?(t=e.slice(hs.URL_SCHEME.length),new hs(t)):null;var t};is.registerSaveRouter(fs),is.registerLoadRouter(fs);class ms{constructor(){this.indexedDB=ds()}async listModels(){return new Promise((e,t)=>{const n=this.indexedDB.open(us,1);n.onupgradeneeded=()=>ps(n),n.onsuccess=()=>{const r=n.result,a=r.transaction(cs,"readonly"),s=a.objectStore(cs).getAll();s.onsuccess=()=>{const t={};for(const e of s.result)t[e.modelPath]=e.modelArtifactsInfo;e(t)},s.onerror=e=>(r.close(),t(s.error)),a.oncomplete=()=>r.close()},n.onerror=e=>t(n.error)})}async removeModel(e){var t;return e=(t=e).startsWith(hs.URL_SCHEME)?t.slice(hs.URL_SCHEME.length):t,new Promise((t,n)=>{const r=this.indexedDB.open(us,1);r.onupgradeneeded=()=>ps(r),r.onsuccess=()=>{const a=r.result,s=a.transaction(cs,"readwrite"),o=s.objectStore(cs),i=o.get(e);let u;i.onsuccess=()=>{if(null==i.result)return a.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{const r=o.delete(e),s=()=>{u=a.transaction(ls,"readwrite");const r=u.objectStore(ls).delete(e);r.onsuccess=()=>t(i.result.modelArtifactsInfo),r.onerror=e=>n(i.error)};r.onsuccess=s,r.onerror=e=>(s(),a.close(),n(i.error))}},i.onerror=e=>(a.close(),n(i.error)),s.oncomplete=()=>{null==u?a.close():u.oncomplete=()=>a.close()}},r.onerror=e=>n(r.error)})}}const gs="/",ys="tensorflowjs_models",bs="info",xs="model_topology",vs="weight_specs",ws="weight_data",ks="model_metadata";function Is(e){return{info:[ys,e,bs].join(gs),topology:[ys,e,xs].join(gs),weightSpecs:[ys,e,vs].join(gs),weightData:[ys,e,ws].join(gs),modelMetadata:[ys,e,ks].join(gs)}}function Ns(e){for(const t of Object.values(e))window.localStorage.removeItem(t)}function Ss(e){const t=e.split(gs);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(gs)}class Ts{constructor(e){if(!V().getBool("IS_BROWSER")||"undefined"===typeof window||"undefined"===typeof window.localStorage)throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,null==e||!e)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=e,this.keys=Is(this.modelPath)}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");{const n=JSON.stringify(e.modelTopology),r=JSON.stringify(e.weightSpecs),a=ss(e),s=Pa.join(e.weightData);try{this.LS.setItem(this.keys.info,JSON.stringify(a)),this.LS.setItem(this.keys.topology,n),this.LS.setItem(this.keys.weightSpecs,r),this.LS.setItem(this.keys.weightData,function(e){if(Ja)return Buffer.from(e).toString("base64");const t=new Uint8Array(e);let n="";for(let r=0,a=t.length;r{return V().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Ts.URL_SCHEME)?(t=e.slice(Ts.URL_SCHEME.length),new Ts(t)):null;var t};is.registerSaveRouter(Cs),is.registerLoadRouter(Cs);class $s{constructor(){i(V().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),i("undefined"===typeof window||"undefined"!==typeof window.localStorage,()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){const e={},t=ys+gs,n=gs+bs;for(let r=0;r"scheme must not be undefined or null."),e.endsWith(Es)&&(e=e.slice(0,e.indexOf(Es))),i(e.length>0,()=>"scheme must not be an empty string.");const n=Rs.getInstance();i(null==n.managers[e],()=>`A model store manager is already registered for scheme '${e}'.`),n.managers[e]=t}static getManager(e){const t=Rs.getInstance().managers[e];if(null==t)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(Rs.getInstance().managers)}}function _s(e){if(-1===e.indexOf(Es))throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Rs.getSchemes().join(",")}`);return{scheme:e.split(Es)[0],path:e.split(Es)[1]}}async function As(e,t,n=!1){i(e!==t,()=>`Old path and new path are the same: '${e}'`);const r=is.getLoadHandlers(e);i(r.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),i(r.length<2,()=>`Copying failed because more than one (${r.length}) load handlers for source URL ${e}.`);const a=r[0],s=is.getSaveHandlers(t);i(s.length>0,()=>`Copying failed because no save handler is found for destination URL ${t}.`),i(s.length<2,()=>`Copying failed because more than one (${r.length}) save handlers for destination URL ${t}.`);const o=s[0],u=_s(e).scheme,l=_s(e).path,c=u===_s(e).scheme,d=await a.load();n&&c&&await Rs.getManager(u).removeModel(l);const p=await o.save(d);return n&&!c&&await Rs.getManager(u).removeModel(l),p.modelArtifactsInfo}class Os{constructor(){this.messageName="setTimeoutCustom",this.functionRefs=[],this.handledMessageCount=0,this.hasEventListener=!1}fetch(e,t){return fetch(e,t)}now(){return performance.now()}encode(e,t){if("utf-8"!==t&&"utf8"!==t)throw new Error(`Browser's encoder only supports utf-8, but got ${t}`);return null==this.textEncoder&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(e)}decode(e,t){return new TextDecoder(t).decode(e)}setTimeoutCustom(e,t){"undefined"!==typeof window&&V().getBool("USE_SETTIMEOUTCUSTOM")?(this.functionRefs.push(e),setTimeout(()=>{window.postMessage({name:this.messageName,index:this.functionRefs.length-1},"*")},t),this.hasEventListener||(this.hasEventListener=!0,window.addEventListener("message",e=>{if(e.source===window&&e.data.name===this.messageName){e.stopPropagation();(0,this.functionRefs[e.data.index])(),this.handledMessageCount++,this.handledMessageCount===this.functionRefs.length&&(this.functionRefs=[],this.handledMessageCount=0)}},!0))):setTimeout(e,t)}isTypedArray(e){return dr(e)}}if(V().get("IS_BROWSER")){V().setPlatform("browser",new Os);try{Rs.registerManager(Ts.URL_SCHEME,new $s)}catch(fO){}try{Rs.registerManager(hs.URL_SCHEME,new ms)}catch(fO){}}const Fs=()=>require("node-fetch");let Ds;class Ms{constructor(){this.util=require("util"),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return null!=V().global.fetch?V().global.fetch(e,t):(null==Ds&&(Ds=Fs()),Ds(e,t))}now(){const e=process.hrtime();return 1e3*e[0]+e[1]/1e6}encode(e,t){if("utf-8"!==t&&"utf8"!==t)throw new Error(`Node built-in encoder only supports utf-8, but got ${t}`);return this.textEncoder.encode(e)}decode(e,t){return 0===e.length?"":new this.util.TextDecoder(t).decode(e)}isTypedArray(e){return this.util.types.isFloat32Array(e)||this.util.types.isInt32Array(e)||this.util.types.isUint8Array(e)||this.util.types.isUint8ClampedArray(e)}}function Ps(e,t="float32",n){return t=t||"float32",O(e),new qr(e,t,n)}V().get("IS_NODE")&&!V().get("IS_BROWSER")&&V().setPlatform("node",new Ms);const Ls=/* @__PURE__ */Aa({cast_:function(e,t){const n=Ea(e,"x","cast");if(!function(e){return"bool"===e||"complex64"===e||"float32"===e||"int32"===e||"string"===e}(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if("string"===t&&"string"!==n.dtype||"string"!==t&&"string"===n.dtype)throw new Error("Only strings can be casted to strings");const r={x:n},a={dtype:t};return wa.runKernel(fe,r,a)}});const Bs=/* @__PURE__ */Aa({clone_:function(e){const t={x:Ea(e,"x","clone","string_or_numeric")};return wa.runKernel(ot,t)}});function Vs(e,t=!1){console.log(e.toString(t))}va();Xr={buffer:Ps,cast:Ls,clone:Bs,print:Vs};const Ws=/* @__PURE__ */Aa({add_:function(e,t){let n=Ea(e,"a","add"),r=Ea(t,"b","add");[n,r]=fa(n,r);const a={a:n,b:r};return wa.runKernel(K,a)}});const zs=/* @__PURE__ */Aa({floorDiv_:function(e,t){let n=Ea(e,"a","floorDiv"),r=Ea(t,"b","floorDiv");[n,r]=fa(n,r);const a={a:n,b:r};return wa.runKernel(et,a)}});const Us=/* @__PURE__ */Aa({div_:function(e,t){let n=Ea(e,"a","div"),r=Ea(t,"b","div");if([n,r]=fa(n,r),"int32"===n.dtype&&"int32"===r.dtype)return zs(n,r);const a={a:n,b:r};return wa.runKernel(We,a,{})}});const Gs=/* @__PURE__ */Aa({mul_:function(e,t){let n=Ea(e,"a","mul"),r=Ea(t,"b","mul");[n,r]=fa(n,r);const a={a:n,b:r};return wa.runKernel(Mt,a)}});const Hs=/* @__PURE__ */Aa({abs_:function(e){const t=Ea(e,"x","abs");if("complex64"===t.dtype){const e={x:t};return wa.runKernel(be,e)}{const e={x:t};return wa.runKernel(H,e)}}});const js=/* @__PURE__ */Aa({acos_:function(e){const t={x:Ea(e,"x","acos")};return wa.runKernel(j,t)}});const qs=/* @__PURE__ */Aa({acosh_:function(e){const t={x:Ea(e,"x","acosh")};return wa.runKernel(q,t)}});const Ks=/* @__PURE__ */Aa({addN_:function(e){i(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),i(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);const t=e.map((e,t)=>Ea(e,`tensors${t}`,"addN")),n=t[0];t.forEach(e=>{if(e.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(e=>{if(!d(e.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});const r=t;return wa.runKernel(X,r)}});const Xs=/* @__PURE__ */Aa({all_:function(e,t=null,n=!1){const r={x:Ea(e,"x","all","bool")},a={axis:t,keepDims:n};return wa.runKernel(Y,r,a)}});const Ys=/* @__PURE__ */Aa({any_:function(e,t=null,n=!1){const r={x:Ea(e,"x","any","bool")},a={axis:t,keepDims:n};return wa.runKernel(Q,r,a)}});const Qs=/* @__PURE__ */Aa({argMax_:function(e,t=0){const n={x:Ea(e,"x","argMax")},r={axis:t};return wa.runKernel(Z,n,r)}});const Zs=/* @__PURE__ */Aa({argMin_:function(e,t=0){const n={x:Ea(e,"x","argMin")},r={axis:t};return wa.runKernel(J,n,r)}});const Js=/* @__PURE__ */Aa({asin_:function(e){const t={x:Ea(e,"x","asin")};return wa.runKernel(ee,t)}});const eo=/* @__PURE__ */Aa({asinh_:function(e){const t={x:Ea(e,"x","asinh")};return wa.runKernel(te,t)}});const to=/* @__PURE__ */Aa({atan_:function(e){const t={x:Ea(e,"x","atan")};return wa.runKernel(ne,t)}});const no=/* @__PURE__ */Aa({atan2_:function(e,t){let n=Ea(e,"a","atan2"),r=Ea(t,"b","atan2");[n,r]=fa(n,r);const a={a:n,b:r};return wa.runKernel(ae,a)}});const ro=/* @__PURE__ */Aa({atanh_:function(e){const t={x:Ea(e,"x","atanh")};return wa.runKernel(re,t)}});function ao(e,t,n,r,a="NHWC",s){return io(e,[...t,e[3]],n,s,r,null,null,bo(a))}function so(e,t,n,r,a,s,o="channelsLast"){const[i,u]=co(t);let l;if("channelsLast"===o)l=[i,u,e[3],e[3]];else{if("channelsFirst"!==o)throw new Error(`Unknown dataFormat ${o}`);l=[i,u,e[1],e[1]]}return io(e,l,n,r,a,s,!1,o)}function oo(e,t,n,r,a,s,o="NDHWC"){const[i,u,l]=po(t);let c,d;if("NDHWC"===o)d="channelsLast",c=[i,u,l,e[4],e[4]];else{if("NCDHW"!==o)throw new Error(`Unknown dataFormat ${o}`);d="channelsFirst",c=[i,u,l,e[1],e[1]]}return uo(e,c,n,r,a,!1,d,s)}function io(e,t,n,r,a,s,o=!1,i="channelsLast"){let[u,l,c,d]=[-1,-1,-1,-1];if("channelsLast"===i)[u,l,c,d]=e;else{if("channelsFirst"!==i)throw new Error(`Unknown dataFormat ${i}`);[u,d,l,c]=e}const[p,h,,f]=t,[m,g]=co(n),[y,b]=co(r),x=ho(p,y),v=ho(h,b),{padInfo:w,outHeight:k,outWidth:I}=function(e,t,n,r,a,s,o,i,u){let l,c,d;if("number"===typeof e){l={top:e,bottom:e,left:e,right:e,type:0===e?"VALID":"NUMBER"};const a=function(e,t,n,r,a){null==r&&(r=lo(e,t,n));const s=e[0],o=e[1],i=fo((s-t+2*r)/n+1,a),u=fo((o-t+2*r)/n+1,a);return[i,u]}([t,n],s,r,e,i);c=a[0],d=a[1]}else if("same"===e){c=Math.ceil(t/r),d=Math.ceil(n/a);const e=Math.max(0,(c-1)*r+s-t),i=Math.max(0,(d-1)*a+o-n),u=Math.floor(e/2),p=e-u,h=Math.floor(i/2);l={top:u,bottom:p,left:h,right:i-h,type:"SAME"}}else if("valid"===e)l={top:0,bottom:0,left:0,right:0,type:"VALID"},c=Math.ceil((t-s+1)/r),d=Math.ceil((n-o+1)/a);else{if("object"!==typeof e)throw Error(`Unknown padding parameter: ${e}`);{const p="channelsLast"===u?e[1][0]:e[2][0],h="channelsLast"===u?e[1][1]:e[2][1],f="channelsLast"===u?e[2][0]:e[3][0],m="channelsLast"===u?e[2][1]:e[3][1];l={top:p,bottom:h,left:f,right:m,type:0===p&&0===h&&0===f&&0===m?"VALID":"EXPLICIT"},c=fo((t-s+p+h)/r+1,i),d=fo((n-o+f+m)/a+1,i)}}return{padInfo:l,outHeight:c,outWidth:d}}(a,l,c,m,g,x,v,s,i),N=o?f*d:f;let S;return"channelsFirst"===i?S=[u,N,k,I]:"channelsLast"===i&&(S=[u,k,I,N]),{batchSize:u,dataFormat:i,inHeight:l,inWidth:c,inChannels:d,outHeight:k,outWidth:I,outChannels:N,padInfo:w,strideHeight:m,strideWidth:g,filterHeight:p,filterWidth:h,effectiveFilterHeight:x,effectiveFilterWidth:v,dilationHeight:y,dilationWidth:b,inShape:e,outShape:S,filterShape:t}}function uo(e,t,n,r,a,s=!1,o="channelsLast",i){let[u,l,c,d,p]=[-1,-1,-1,-1,-1];if("channelsLast"===o)[u,l,c,d,p]=e;else{if("channelsFirst"!==o)throw new Error(`Unknown dataFormat ${o}`);[u,p,l,c,d]=e}const[h,f,m,,g]=t,[y,b,x]=po(n),[v,w,k]=po(r),I=ho(h,v),N=ho(f,w),S=ho(m,k),{padInfo:T,outDepth:C,outHeight:$,outWidth:E}=function(e,t,n,r,a,s,o,i,u,l,c){let d,p,h,f;"valid"===e&&(e=0);if("number"===typeof e){d={top:e,bottom:e,left:e,right:e,front:e,back:e,type:0===e?"VALID":"NUMBER"};const m=function(e,t,n,r,a,s){null==a&&(a=lo(e,t[0],r[0]));const o=[0,0,0,n];for(let i=0;i<3;i++)e[i]+2*a>=t[i]&&(o[i]=fo((e[i]-t[i]+2*a)/r[i]+1,s));return o}([t,n,r,1],[i,u,l],1,[a,s,o],e,c);p=m[0],h=m[1],f=m[2]}else{if("same"!==e)throw Error(`Unknown padding parameter: ${e}`);{p=Math.ceil(t/a),h=Math.ceil(n/s),f=Math.ceil(r/o);const e=(p-1)*a+i-t,c=(h-1)*s+u-n,m=(f-1)*o+l-r,g=Math.floor(e/2),y=e-g,b=Math.floor(c/2),x=c-b,v=Math.floor(m/2);d={top:b,bottom:x,left:v,right:m-v,front:g,back:y,type:"SAME"}}}return{padInfo:d,outDepth:p,outHeight:h,outWidth:f}}(a,l,c,d,y,b,x,I,N,S,i),R=s?g*p:g;let _;return"channelsFirst"===o?_=[u,R,C,$,E]:"channelsLast"===o&&(_=[u,C,$,E,R]),{batchSize:u,dataFormat:o,inDepth:l,inHeight:c,inWidth:d,inChannels:p,outDepth:C,outHeight:$,outWidth:E,outChannels:R,padInfo:T,strideDepth:y,strideHeight:b,strideWidth:x,filterDepth:h,filterHeight:f,filterWidth:m,effectiveFilterDepth:I,effectiveFilterHeight:N,effectiveFilterWidth:S,dilationDepth:v,dilationHeight:w,dilationWidth:k,inShape:e,outShape:_,filterShape:t}}function lo(e,t,n,r=1){const a=ho(t,r);return Math.floor((e[0]*(n-1)-n+a)/2)}function co(e){return"number"===typeof e?[e,e,e]:2===e.length?[e[0],e[1],1]:e}function po(e){return"number"===typeof e?[e,e,e]:e}function ho(e,t){return t<=1?e:e+(e-1)*(t-1)}function fo(e,t){if(!t)return Math.trunc(e);switch(t){case"round":return Math.round(e);case"ceil":return Math.ceil(e);case"floor":return Math.floor(e);default:throw new Error(`Unknown roundingMode ${t}`)}}function mo(e){const[t,n,r]=co(e);return 1===t&&1===n&&1===r}function go(e,t){return mo(e)||mo(t)}function yo(e){return co(e).every(e=>e>0)}function bo(e){if("NHWC"===e)return"channelsLast";if("NCHW"===e)return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function xo(e,t,n){if(null!=n){if("string"===typeof t)throw Error(`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`);if("number"===typeof t)i(p(t),()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`);else{if("object"!==typeof t)throw Error(`Error in ${e}: Unknown padding parameter: ${t}`);t.forEach(t=>{t.forEach(t=>{i(p(t),()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`)})})}}}const vo=/* @__PURE__ */Aa({reshape_:function(e,t){const n={x:Ea(e,"x","reshape","string_or_numeric")},r={shape:t};return wa.runKernel(nn,n,r)}});const wo=/* @__PURE__ */Aa({avgPool_:function(e,t,n,r,a){const s=Ea(e,"x","avgPool","float32");i(go(n,1),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`);let o=s,u=!1;3===s.rank&&(u=!0,o=vo(s,[1,s.shape[0],s.shape[1],s.shape[2]])),i(4===o.rank,()=>`Error in avgPool: x must be rank 4 but got rank ${o.rank}.`),xo("avgPool",r,a);const l={x:o},c={filterSize:t,strides:n,pad:r,dimRoundingMode:a};let d=wa.runKernel(se,l,c);return d=Ls(d,s.dtype),u?vo(d,[d.shape[1],d.shape[2],d.shape[3]]):d}});const ko=/* @__PURE__ */Aa({avgPool3d_:function(e,t,n,r,a,s="NDHWC"){const o=Ea(e,"x","avgPool3d","float32");let u=o,l=!1;4===o.rank&&(l=!0,u=vo(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),i(5===u.rank,()=>`Error in avgPool3d: x must be rank 5 but got rank ${u.rank}.`),i("NDHWC"===s,()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),i("number"===typeof n&&n>0||Array.isArray(n)&&n[0]>0&&n[1]>0&&n[2]>0,()=>`Error in avgPool3d: Stride must be > 0, but got '${n}'`),xo("avgPool3d",r,a);const c={x:u},d={filterSize:t,strides:n,pad:r,dimRoundingMode:a,dataFormat:s};let p=wa.runKernel(ie,c,d);return p=Ls(p,u.dtype),l?vo(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}});const Io=/* @__PURE__ */Aa({concat_:function(e,t=0){i(e.length>=1,()=>"Pass at least one tensor to concat");const n=Ra(e,"tensors","concat","string_or_numeric");if("complex64"===n[0].dtype&&n.forEach(e=>{if("complex64"!==e.dtype)throw new Error(`Cannot concatenate complex64 tensors with a tensor\n with dtype ${e.dtype}. `)}),1===n.length)return Bs(n[0]);const r=n,a={axis:t};return wa.runKernel(xe,r,a)}});const No=/* @__PURE__ */Aa({matMul_:function(e,t,n=!1,r=!1){let a=Ea(e,"a","matMul"),s=Ea(t,"b","matMul");[a,s]=fa(a,s);const o={a,b:s},i={transposeA:n,transposeB:r};return wa.runKernel(le,o,i)}});const So=/* @__PURE__ */Aa({sigmoid_:function(e){const t={x:Ea(e,"x","sigmoid","float32")};return wa.runKernel(wn,t)}});const To=/* @__PURE__ */Aa({slice_:function(e,t,n){const r=Ea(e,"x","slice","string_or_numeric");if(0===r.rank)throw new Error("Slicing scalar is not possible");const a={x:r},s={begin:t,size:n};return wa.runKernel(yn,a,s)}});const Co=/* @__PURE__ */Aa({tanh_:function(e){const t={x:Ea(e,"x","tanh","float32")};return wa.runKernel(zn,t)}});const $o=/* @__PURE__ */Aa({basicLSTMCell_:function(e,t,n,r,a,s){const o=Ea(e,"forgetBias","basicLSTMCell"),i=Ea(t,"lstmKernel","basicLSTMCell"),u=Ea(n,"lstmBias","basicLSTMCell"),l=Ea(r,"data","basicLSTMCell"),c=Ea(a,"c","basicLSTMCell"),d=Ea(s,"h","basicLSTMCell"),p=Io([l,d],1),h=No(p,i),f=Ws(h,u),m=f.shape[0],g=f.shape[1]/4,y=[m,g],b=To(f,[0,0],y),x=To(f,[0,g],y),v=To(f,[0,2*g],y),w=To(f,[0,3*g],y),k=Ws(Gs(So(b),Co(x)),Gs(c,So(Ws(o,v))));return[k,Gs(Co(k),So(w))]}});const Eo=/* @__PURE__ */Aa({batchToSpaceND_:function(e,t,n){const r=Ea(e,"x","batchToSpaceND"),a=t.reduce((e,t)=>e*t);i(r.rank>=1+t.length,()=>`input rank is ${r.rank} but should be > than blockShape.length ${t.length}`),i(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),i(r.shape[0]%a===0,()=>`input tensor batch is ${r.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${a}`);const s={x:r},o={blockShape:t,crops:n};return wa.runKernel(ce,s,o)}});const Ro=/* @__PURE__ */Aa({batchNorm_:function(e,t,n,r,a,s){null==s&&(s=.001);const o=Ea(e,"x","batchNorm"),u=Ea(t,"mean","batchNorm"),l=Ea(n,"variance","batchNorm");let c,d;null!=a&&(c=Ea(a,"scale","batchNorm")),null!=r&&(d=Ea(r,"offset","batchNorm")),i(u.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),i(null==d||u.rank===d.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),i(null==c||u.rank===c.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");const p={x:function(e){let t;return t=0===e.rank||1===e.rank?vo(e,[1,1,1,e.size]):2===e.rank?vo(e,[1,1,e.shape[0],e.shape[1]]):3===e.rank?vo(e,[1,e.shape[0],e.shape[1],e.shape[2]]):e,t}(o),scale:c,offset:d,mean:u,variance:l},h={varianceEpsilon:s},f=wa.runKernel(tt,p,h);return vo(f,o.shape)}});const _o=/* @__PURE__ */Aa({batchNorm2d_:function(e,t,n,r,a,s){const o=Ea(e,"x","batchNorm"),u=Ea(t,"mean","batchNorm"),l=Ea(n,"variance","batchNorm");let c,d;return null!=a&&(c=Ea(a,"scale","batchNorm")),null!=r&&(d=Ea(r,"offset","batchNorm")),i(2===o.rank,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${o.rank}.`),i(2===u.rank||1===u.rank,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${u.rank}.`),i(2===l.rank||1===l.rank,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),null!=c&&i(2===c.rank||1===c.rank,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${c.rank}.`),null!=d&&i(2===d.rank||1===d.rank,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${d.rank}.`),Ro(o,u,l,d,c,s)}});const Ao=/* @__PURE__ */Aa({batchNorm3d_:function(e,t,n,r,a,s){const o=Ea(e,"x","batchNorm"),u=Ea(t,"mean","batchNorm"),l=Ea(n,"variance","batchNorm");let c,d;return null!=a&&(c=Ea(a,"scale","batchNorm")),null!=r&&(d=Ea(r,"offset","batchNorm")),i(3===o.rank,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${o.rank}.`),i(3===u.rank||1===u.rank,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${u.rank}.`),i(3===l.rank||1===l.rank,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),null!=c&&i(3===c.rank||1===c.rank,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${c.rank}.`),null!=d&&i(3===d.rank||1===d.rank,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${d.rank}.`),Ro(o,u,l,d,c,s)}});const Oo=/* @__PURE__ */Aa({batchNorm4d_:function(e,t,n,r,a,s){const o=Ea(e,"x","batchNorm"),u=Ea(t,"mean","batchNorm"),l=Ea(n,"variance","batchNorm");let c,d;return null!=a&&(c=Ea(a,"scale","batchNorm")),null!=r&&(d=Ea(r,"offset","batchNorm")),i(4===o.rank,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${o.rank}.`),i(4===u.rank||1===u.rank,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${u.rank}.`),i(4===l.rank||1===l.rank,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),null!=c&&i(4===c.rank||1===c.rank,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${c.rank}.`),null!=d&&i(4===d.rank||1===d.rank,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${d.rank}.`),Ro(o,u,l,d,c,s)}});const Fo=/* @__PURE__ */Aa({bincount_:function(e,t,n){const r=Ea(e,"x","bincount"),a=Ea(t,"weights","bincount");i("int32"===r.dtype,()=>`Error in bincount: input dtype must be int32, but got ${r.dtype}`),i(n>=0,()=>`size must be non-negative, but got ${n}.`),i(a.size===r.size||0===a.size,()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${r.shape}, weights shape: ${a.shape}.`);const s={x:r,weights:a},o={size:n};return wa.runKernel(de,s,o)}});const Do=/* @__PURE__ */Aa({bitwiseAnd_:function(e,t){const n=Ea(e,"x","bitwiseAnd"),r=Ea(t,"y","bitwiseAnd");if(!d(n.shape,r.shape))throw new Error(`BitwiseAnd: Tensors must have the same shape. x: ${n.shape}, y: ${r.shape}`);if("int32"!==n.dtype||"int32"!==r.dtype)throw new Error(`BitwiseAnd: Only supports 'int32' values in tensor, found type of x: ${n.dtype} and type of y: ${r.dtype}`);const a={a:n,b:r};return wa.runKernel(pe,a)}});const Mo=/* @__PURE__ */Aa({broadcastArgs_:function(e,t){const n=Ea(e,"s0","broadcastArgs","int32"),r=Ea(t,"s1","broadcastArgs","int32");if(1!==n.rank)throw new Error(`broadcastArgs(): first input must be a vector (rank=1). Has rank ${n.rank}`);if(1!==r.rank)throw new Error(`broadcastArgs(): second input must be a vector (rank=1). Has rank ${r.rank}`);const a={s0:n,s1:r};return wa.runKernel(he,a)}});const Po=/* @__PURE__ */Aa({broadcastTo_:function(e,t){let n=Ea(e,"broadcastTo","x");const r=n.shape;if(O(t),t.lengthn.rank){const e=n.shape.slice();for(;e.length=0;u--)if(a[u]===t[u])s[u]=1;else if(1!==n.shape[u])throw new Error(`broadcastTo(): [${r}] cannot be broadcast to [${t}].`);if(0===s.map((e,t)=>e>1?t:-1).filter(e=>e>=0).length)return Bs(n);const o={x:n},i={reps:s};return wa.runKernel(Un,o,i)}});const Lo=/* @__PURE__ */Aa({ceil_:function(e){const t={x:Ea(e,"x","ceil","float32")};return wa.runKernel(me,t)}});function Bo(e,t,n){O(e);const r={shape:e,value:t,dtype:n=n||N(t)};return wa.runKernel(Qe,{},r)}const Vo=/* @__PURE__ */Aa({clipByValue_:function(e,t,n){const r=Ea(e,"x","clipByValue");if(i(t<=n,()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`),t===n)return Bo(r.shape,t,r.dtype);const a={x:r},s={clipValueMin:t,clipValueMax:n};return wa.runKernel(ge,a,s)}});const Wo=/* @__PURE__ */Aa({concat1d_:function(e){return Io(e,0)}});const zo=/* @__PURE__ */Aa({concat2d_:function(e,t){return Io(e,t)}});const Uo=/* @__PURE__ */Aa({concat3d_:function(e,t){return Io(e,t)}});const Go=/* @__PURE__ */Aa({concat4d_:function(e,t){return Io(e,t)}});const Ho=/* @__PURE__ */Aa({conv2d_:function(e,t,n,r,a="NHWC",s=[1,1],o){const u=Ea(e,"x","conv2d","float32"),l=Ea(t,"filter","conv2d","float32");let c=u,d=!1;3===u.rank&&(d=!0,c=vo(u,[1,u.shape[0],u.shape[1],u.shape[2]])),i(4===c.rank,()=>`Error in conv2d: input must be rank 4, but got rank ${c.rank}.`),i(4===l.rank,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),xo("conv2d",r,o);const p="NHWC"===a?c.shape[3]:c.shape[1];i(p===l.shape[2],()=>`Error in conv2d: depth of input (${p}) must match input depth for filter ${l.shape[2]}.`),i(go(n,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`),i(yo(s),()=>"Error in conv2D: Dilated rates should be larger than 0."),i(yo(n),()=>"Error in conv2D: Strides should be larger than 0.");const h={x:c,filter:l},f={strides:n,pad:r,dataFormat:a,dilations:s,dimRoundingMode:o},m=wa.runKernel(ve,h,f);return d?vo(m,[m.shape[1],m.shape[2],m.shape[3]]):m}});const jo=/* @__PURE__ */Aa({conv1d_:function(e,t,n,r,a="NWC",s=1,o){const u=Ea(e,"x","conv1d"),l=Ea(t,"filter","conv1d");let c=u,d=!1;2===u.rank&&(d=!0,c=vo(u,[1,u.shape[0],u.shape[1]])),i(3===c.rank,()=>`Error in conv1d: input must be rank 3, but got rank ${c.rank}.`),i(3===l.rank,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),xo("conv1d",r,o),i(c.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${c.shape[2]}) must match input depth for filter ${l.shape[1]}.`),i(go(n,s),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${s}'`),i(yo(s),()=>"Error in conv1D: Dilated rates should be larger than 0."),i(yo(n),()=>"Error in conv1D: Stride should be larger than 0."),i("NWC"===a,()=>`Error in conv1d: got dataFormat of ${a} but only NWC is currently supported.`);const p=vo(l,[1,l.shape[0],l.shape[1],l.shape[2]]),h=vo(c,[c.shape[0],1,c.shape[1],c.shape[2]]),f=Ho(h,p,[1,n],r,"NHWC",[1,s],o);return vo(f,d?[f.shape[2],f.shape[3]]:[f.shape[0],f.shape[2],f.shape[3]])}});const qo=/* @__PURE__ */Aa({conv2DBackpropInput_:function(e,t,n,r,a,s="NHWC",o){i(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let u=e,l=t,c=!1;3===t.rank&&(c=!0,l=vo(t,[1,t.shape[0],t.shape[1],t.shape[2]]),u=[1,e[0],e[1],e[2]]),i(4===u.length,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${u.length}.`),i(4===l.rank,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),i(4===n.rank,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`);const d="NHWC"===s?u[3]:u[1],p="NHWC"===s?l.shape[3]:l.shape[1];i(d===n.shape[2],()=>`Error in conv2dDerInput: depth of input (${d}) must match input depth for filter ${n.shape[2]}.`),i(p===n.shape[3],()=>`Error in conv2dDerInput: depth of output (${p}) must match output depth for filter ${n.shape[3]}.`),xo("conv2dDerInput",a,o);const h={dy:l,filter:n},f={strides:r,pad:a,dataFormat:s,dimRoundingMode:o,inputShape:u},m=wa.runKernel(ke,h,f);return c?vo(m,[m.shape[1],m.shape[2],m.shape[3]]):m}});const Ko=/* @__PURE__ */Aa({conv2dTranspose_:function(e,t,n,r,a,s){const o=Ea(e,"x","conv2dTranspose"),i=Ea(t,"filter","conv2dTranspose");return qo(n,o,i,r,a,"NHWC",s)}});const Xo=/* @__PURE__ */Aa({conv3d_:function(e,t,n,r,a="NDHWC",s=[1,1,1]){const o=Ea(e,"x","conv3d"),u=Ea(t,"filter","conv3d");let l=o,c=!1;4===o.rank&&(c=!0,l=vo(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),i(5===l.rank,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),i(5===u.rank,()=>`Error in conv3d: filter must be rank 5, but got rank ${u.rank}.`),i(l.shape[4]===u.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${u.shape[3]}.`),i(go(n,s),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`),i("NDHWC"===a,()=>`Error in conv3d: got dataFormat of ${a} but only NDHWC is currently supported.`),i(yo(s),()=>"Error in conv3D: Dilated rates should be larger than 0."),i(yo(n),()=>"Error in conv3D: Strides should be larger than 0.");const d={x:l,filter:u},p={strides:n,pad:r,dataFormat:a,dilations:s},h=wa.runKernel(Ie,d,p);return c?vo(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}});const Yo=/* @__PURE__ */Aa({conv3DBackpropInput_:function(e,t,n,r,a){i(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let s=e,o=t,u=!1;4===t.rank&&(u=!0,o=vo(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),s=[1,e[0],e[1],e[2],e[3]]);const l=s[4],c=o.shape[4];i(5===s.length,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${s.length}.`),i(5===o.rank,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${o.rank}`),i(5===n.rank,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`),i(l===n.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${n.shape[3]}.`),i(c===n.shape[4],()=>`Error in conv3dDerInput: depth of output (${c}) must match output depth for filter ${n.shape[4]}.`);const d={dy:o,filter:n},p={pad:a,strides:r,inputShape:s},h=wa.runKernel(Se,d,p);return u?vo(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}});const Qo=/* @__PURE__ */Aa({conv3dTranspose_:function(e,t,n,r,a){const s=Ea(e,"x","conv3dTranspose"),o=Ea(t,"filter","conv3dTranspose");return Yo(n,s,o,r,a)}});const Zo=/* @__PURE__ */Aa({cos_:function(e){const t={x:Ea(e,"x","cos","float32")};return wa.runKernel(Te,t)}});const Jo=/* @__PURE__ */Aa({cosh_:function(e){const t={x:Ea(e,"x","cosh","float32")};return wa.runKernel(Ce,t)}});const ei=/* @__PURE__ */Aa({cumprod_:function(e,t=0,n=!1,r=!1){const a={x:Ea(e,"x","cumprod")},s={axis:t,exclusive:n,reverse:r};return wa.runKernel($e,a,s)}});const ti=/* @__PURE__ */Aa({cumsum_:function(e,t=0,n=!1,r=!1){const a={x:Ea(e,"x","cumsum")},s={axis:t,exclusive:n,reverse:r};return wa.runKernel(Ee,a,s)}});const ni=/* @__PURE__ */Aa({denseBincount_:function(e,t,n,r=!1){const a=Ea(e,"x","denseBincount"),s=Ea(t,"weights","denseBincount");i("int32"===a.dtype,()=>`Error in denseBincount: input dtype must be int32, but got ${a.dtype}`),i(a.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${a.rank}.`),i(n>=0,()=>`size must be non-negative, but got ${n}.`),i(s.size===a.size||0===s.size,()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${a.shape}, weights shape: ${s.shape}.`);const o={x:a,weights:s},u={size:n,binaryOutput:r};return wa.runKernel(_e,o,u)}});const ri=/* @__PURE__ */Aa({depthToSpace_:function(e,t,n="NHWC"){const r=Ea(e,"x","depthToSpace","float32"),a="NHWC"===n?r.shape[1]:r.shape[2],s="NHWC"===n?r.shape[2]:r.shape[3],o="NHWC"===n?r.shape[3]:r.shape[1];i(t>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`),i(a*t>=0,()=>`Negative dimension size caused by overflow when multiplying\n ${a} and ${t} for depthToSpace with input shape\n ${r.shape}`),i(s*t>=0,()=>`Negative dimension size caused by overflow when multiplying\n ${s} and ${t} for depthToSpace with input shape\n ${r.shape}`),i(o%(t*t)===0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${o} for depthToSpace with input shape ${r.shape}`);const u={x:r},l={blockSize:t,dataFormat:n};return wa.runKernel(Ae,u,l)}});const ai=/* @__PURE__ */Aa({depthwiseConv2d_:function(e,t,n,r,a="NHWC",s=[1,1],o){const u=Ea(e,"x","depthwiseConv2d","float32"),l=Ea(t,"filter","depthwiseConv2d","float32");let c=u,d=!1;3===u.rank&&(d=!0,c=vo(u,[1,u.shape[0],u.shape[1],u.shape[2]])),i(4===c.rank,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${c.rank}.`),i(4===l.rank,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`);const p="NHWC"===a?c.shape[3]:c.shape[1];i(p===l.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${p}) must match the inChannels dimension in filter ${l.shape[2]}.`),xo("depthwiseConv2d",r,o);const h={x:c,filter:l},f={strides:n,pad:r,dataFormat:a,dilations:s,dimRoundingMode:o},m=wa.runKernel(Oe,h,f);return d?vo(m,[m.shape[1],m.shape[2],m.shape[3]]):m}});const si=/* @__PURE__ */Aa({diag_:function(e){const t={x:Ea(e,"x","diag")};return wa.runKernel(Me,t)}});const oi=/* @__PURE__ */Aa({dilation2d_:function(e,t,n,r,a=[1,1],s="NHWC"){const o=Ea(e,"x","dilation2d"),u=Ea(t,"filter","dilation2d");i(3===o.rank||4===o.rank,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${o.rank}.`),i(3===u.rank,()=>`Error in dilation2d: filter must be rank 3, but got rank ${u.rank}.`),i("NHWC"===s,()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${s}`);let l=o,c=!1;3===o.rank&&(l=vo(o,[1,o.shape[0],o.shape[1],o.shape[2]]),c=!0),i(l.shape[3]===u.shape[2],()=>`Error in dilation2d: input and filter must have the same depth: ${l.shape[3]} vs ${u.shape[2]}`);const d={x:l,filter:u},p={strides:n,pad:r,dilations:a},h=wa.runKernel(Pe,d,p);return c?vo(h,[h.shape[1],h.shape[2],h.shape[3]]):h}});function ii(e,t){const n=e.length,r=[];for(let a=0;a1&&1===o&&r.unshift(s)}return r}function ui(e,t){const n=[];for(let r=0;r1)&&n.unshift(s)}return n}function li(e,t){const n=Math.max(e.length,t.length),r=new Array(n);for(let a=0;a`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${r.rank}.`);const a=1===n.rank?n.size:n.shape[1],s=1===r.rank?r.size:r.shape[0];if(i(a===s,()=>`Error in dot: inner dimensions of inputs must match, but got ${a} and ${s}.`),1===n.rank&&1===r.rank){const e=vo(n,[1,-1]),t=vo(r,[-1,1]),a=No(e,t);return vo(a,[])}if(1===n.rank&&2===r.rank){const e=vo(n,[1,-1]),t=vo(r,[r.shape[0],r.shape[1]]),a=No(e,t);return vo(a,[a.size])}if(2===n.rank&&1===r.rank){const e=vo(r,[-1,1]),t=No(n,e);return vo(t,[t.size])}{const e=vo(r,[r.shape[0],r.shape[1]]);return No(n,e)}}});const mi=/* @__PURE__ */Aa({einsum_:function(e,...t){const n=t.map((e,t)=>Ea(e,`tensors${t}`,"einsum")),r={equation:e};return wa.runKernel(ze,n,r)}});const gi=/* @__PURE__ */Aa({elu_:function(e){const t={x:Ea(e,"x","elu","float32")};return wa.runKernel(Ue,t)}});const yi=/* @__PURE__ */Aa({ensureShape_:function(e,t){const n=Ea(e,"x","ensureShape","string_or_numeric");if(!function(e,t){if(e===t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;for(let n=0;n"Input dtype must be `int32` or `float32`."),"int32"===t.dtype&&(t=Ls(t,"float32"));const n={x:t};return wa.runKernel(He,n)}});function xi(e,t){for(let n=0;ne[t])]}function ki(e,t){return vi(e,t.map(e=>1),t)}function Ii(e,t,n){i(xi(t,n),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`)}function Ni(e,t){if(xi(e,t))return null;const n=[];for(let r=0;rn.push(e)),n}function Si(e){return e.map((e,t)=>[t,e]).sort((e,t)=>e[1]-t[1]).map(e=>e[0])}function Ti(e,t){const n=[];for(let r=t-e;r"Axis must be <= rank of the tensor");const r={input:n},a={dim:t};return wa.runKernel(Ke,r,a)}});const Bi=/* @__PURE__ */Aa({expm1_:function(e){const t={x:Ea(e,"x","expm1")};return wa.runKernel(Xe,t)}});const Vi=/* @__PURE__ */Aa({tile_:function(e,t){const n=Ea(e,"x","tile","string_or_numeric");i(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`);const r={x:n},a={reps:t};return wa.runKernel(Un,r,a)}});const Wi=/* @__PURE__ */Aa({eye_:function(e,t,n,r="float32"){null==t&&(t=e);const a=Ps([e,t],r),s=e<=t?e:t;for(let i=0;i`Error in localResponseNormalization: x must be rank 3 or 4 but got\n rank ${s.rank}.`),i(p(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let o=s,u=!1;3===s.rank&&(u=!0,o=vo(s,[1,s.shape[0],s.shape[1],s.shape[2]]));const l={x:o},c={depthRadius:t,bias:n,alpha:r,beta:a},d=wa.runKernel(wt,l,c);return u?vo(d,[d.shape[1],d.shape[2],d.shape[3]]):d}});const tu=/* @__PURE__ */Aa({log_:function(e){const t={x:Ea(e,"x","log","float32")};return wa.runKernel(gt,t)}});const nu=/* @__PURE__ */Aa({log1p_:function(e){const t={x:Ea(e,"x","log1p")};return wa.runKernel(yt,t)}});function ru(e,t){i(S(e),()=>"The f passed in variableGrads(f) must be a function"),i(null==t||Array.isArray(t)&&t.every(e=>e instanceof Zr),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");const n=null!=t;if(!n){t=[];for(const e in wa.registeredVariables)t.push(wa.registeredVariables[e])}const r=n?t.filter(e=>!e.trainable):null,a=t.length;i((t=t.filter(e=>e.trainable)).length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${a} variables is trainable.`);const{value:s,grads:o}=wa.gradients(e,t,null,!0);i(o.some(e=>null!=e),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),i(0===s.rank,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${s.rank} tensor`);const u={};return t.forEach((e,t)=>{null!=o[t]&&(u[e.name]=o[t])}),null!=r&&r.forEach(e=>u[e.name]=null),{value:s,grads:u}}function au(e){return wa.customGrad(e)}const su=/* @__PURE__ */Aa({neg_:function(e){const t={x:Ea(e,"x","neg")};return wa.runKernel(Pt,t)}});const ou=/* @__PURE__ */Aa({softplus_:function(e){const t={x:Ea(e,"x","softplus")};return wa.runKernel(kn,t)}});const iu=/* @__PURE__ */Aa({logSigmoid_:function(e){const t=Ea(e,"x","logSigmoid");return au(e=>({value:su(ou(su(e))),gradFunc:t=>Gs(t,So(su(e)))}))(t)}});const uu=/* @__PURE__ */Aa({sub_:function(e,t){let n=Ea(e,"a","sub"),r=Ea(t,"b","sub");[n,r]=fa(n,r);const a={a:n,b:r};return wa.runKernel(Vn,a)}});const lu=/* @__PURE__ */Aa({logSoftmax_:function(e,t=-1){const n=Ea(e,"logits","logSoftmax");if(-1===t&&(t=n.rank-1),t!==n.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and axis was ${t}`);return au((e,n)=>{const r=Ci(e,t,!0),a=uu(e,r),s=uu(Ls(a,"float32"),tu(Oi(Pi(a),t,!0)));n([s]);return{value:s,gradFunc:(e,n)=>{const[r]=n,a=Pi(r);return uu(e,Gs(Oi(e,t,!0),a))}}})(n)}});const cu=/* @__PURE__ */Aa({logSumExp_:function(e,t=null,n=!1){const r=Ea(e,"x","logSumExp"),a=y(t,r.shape),s=Ci(r,a,!0),o=uu(r,s),i=Pi(o),u=Oi(i,a),l=tu(u),c=Ws(vo(s,l.shape),l);if(n){const e=ki(c.shape,a);return vo(c,e)}return c}});const du=/* @__PURE__ */Aa({logicalAnd_:function(e,t){const n=Ea(e,"a","logicalAnd","bool"),r=Ea(t,"b","logicalAnd","bool");li(n.shape,r.shape);const a={a:n,b:r};return wa.runKernel(bt,a)}});const pu=/* @__PURE__ */Aa({logicalNot_:function(e){const t={x:Ea(e,"x","logicalNot","bool")};return wa.runKernel(xt,t)}});const hu=/* @__PURE__ */Aa({logicalOr_:function(e,t){const n=Ea(e,"a","logicalOr","bool"),r=Ea(t,"b","logicalOr","bool");li(n.shape,r.shape);const a={a:n,b:r};return wa.runKernel(vt,a)}});const fu=/* @__PURE__ */Aa({logicalXor_:function(e,t){const n=Ea(e,"a","logicalXor","bool"),r=Ea(t,"b","logicalXor","bool");return li(n.shape,r.shape),du(hu(e,t),pu(du(e,t)))}}),mu=2147483648;const gu=/* @__PURE__ */Aa({searchSorted_:function(e,t,n="left"){const r=Ea(e,"sortedSequence","searchSorted"),a=Ea(t,"values","searchSorted"),s=r.shape[r.shape.length-1],o=a.shape[a.shape.length-1],i=vo(r,[-1,s]),u=vo(a,[-1,o]);if(i.rank<2)throw new Error("Sorted input argument must be at least 2-dimensional");if(i.shape[0]!==u.shape[0])throw new Error("Leading dimension of 'sortedSequence' and 'values' must match.");if(c(u.shape)>=mu)throw new Error("values tensor size must less than 2147483648");if(i.shape[1]>=mu)throw new Error(`trailing dim_size must less than 2147483648 for int32 output type, was ${i.shape[1]}`);const l={sortedSequence:i,values:u},d={side:n};return wa.runKernel(fn,l,d)}});function yu(e,t){return gu(e,t,"left")}const bu=/* @__PURE__ */Aa({maxPool_:function(e,t,n,r,a){const s=Ea(e,"x","maxPool");let o=s,u=!1;3===s.rank&&(u=!0,o=vo(s,[1,s.shape[0],s.shape[1],s.shape[2]])),i(4===o.rank,()=>`Error in maxPool: input must be rank 4 but got rank ${o.rank}.`),i(go(n,1),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`),xo("maxPool",r,a);const l={x:o},c={filterSize:t,strides:n,pad:r,dimRoundingMode:a},d=wa.runKernel(St,l,c);return u?vo(d,[d.shape[1],d.shape[2],d.shape[3]]):d}});const xu=/* @__PURE__ */Aa({maxPool3d_:function(e,t=[1,1,1],n,r,a,s="NDHWC"){const o=Ea(e,"x","maxPool3d");let u=o,l=!1;4===o.rank&&(l=!0,u=vo(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),i(5===u.rank,()=>`Error in maxPool3d: x must be rank 5 but got rank ${u.rank}.`),i("NDHWC"===s,()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),xo("maxPool3d",r,a);const c={x:u},d={filterSize:t,strides:n,pad:r,dimRoundingMode:a,dataFormat:s},p=wa.runKernel(Ct,c,d);return l?vo(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}});const vu=/* @__PURE__ */Aa({maxPoolWithArgmax_:function(e,t,n,r,a=!1){const s={x:Ea(e,"x","maxPoolWithArgmax")},o={filterSize:t,strides:n,pad:r,includeBatchInIndex:a},i=wa.runKernel(Et,s,o);return{result:i[0],indexes:i[1]}}});const wu=/* @__PURE__ */Aa({maximum_:function(e,t){let n=Ea(e,"a","maximum"),r=Ea(t,"b","maximum");[n,r]=fa(n,r),"bool"===n.dtype&&(n=Ls(n,"int32"),r=Ls(r,"int32")),li(n.shape,r.shape);const a={a:n,b:r};return wa.runKernel(Nt,a)}});const ku=/* @__PURE__ */Aa({mean_:function(e,t=null,n=!1){const r={x:Ea(e,"x","mean")},a={axis:t,keepDims:n};return wa.runKernel(Rt,r,a)}});function Iu(e,t="float32"){if(O(e),"complex64"===t){const t=Iu(e,"float32"),n=Iu(e,"float32");return Oa(t,n)}const n=_(c(e),t);return wa.makeTensor(n,e,t)}function Nu(e,t="float32"){if(O(e),"complex64"===t){const t=Nu(e,"float32"),n=Iu(e,"float32");return Oa(t,n)}const n=R(c(e),t);return wa.makeTensor(n,e,t)}function Su(e,t,{indexing:n="xy"}={}){if("xy"!==n&&"ij"!==n)throw new TypeError(`${n} is not a valid third argument to meshgrid`);if(void 0===e)return[];let r=Ea(e,"x","meshgrid",e instanceof Yr?e.dtype:"float32");if(void 0===t)return[r];let a=Ea(t,"y","meshgrid",t instanceof Yr?t.dtype:"float32");const s=c(r.shape),o=c(a.shape);return"xy"===n?(r=vo(r,[1,-1]),a=vo(a,[-1,1]),[No(Nu([o,1],r.dtype),r),No(a,Nu([1,s],a.dtype))]):(r=vo(r,[-1,1]),a=vo(a,[1,-1]),[No(r,Nu([1,o],r.dtype)),No(Nu([s,1],a.dtype),a)])}const Tu=/* @__PURE__ */Aa({minimum_:function(e,t){let n=Ea(e,"a","minimum"),r=Ea(t,"b","minimum");[n,r]=fa(n,r),"bool"===n.dtype&&(n=Ls(n,"int32"),r=Ls(r,"int32")),li(n.shape,r.shape);const a={a:n,b:r};return wa.runKernel(At,a)}});const Cu=/* @__PURE__ */Aa({mirrorPad_:function(e,t,n){i("reflect"===n||"symmetric"===n,()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`);const r=Ea(e,"x","mirrorPad");if(0===r.rank)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");i(t.length===r.rank,()=>`Padding doesn't match input. Must be ${r.rank}. Got ${t.length}.`);const a="reflect"===n?1:0;for(let u=0;u"Invalid number of paddings. Must be length of 2 each."),i(t[u][0]>=0&&t[u][0]<=r.shape[u]-a&&t[u][1]>=0&&t[u][1]<=r.shape[u]-a,()=>`Padding in dimension ${u} cannot be greater than or equal to ${r.shape[u]-a} or less than 0 for input of shape ${r.shape}`);const s={paddings:t,mode:n},o={x:r};return wa.runKernel(Ot,o,s)}});const $u=/* @__PURE__ */Aa({mod_:function(e,t){let n=Ea(e,"a","mod"),r=Ea(t,"b","mod");[n,r]=fa(n,r);const a={a:n,b:r};return wa.runKernel(Ft,a)}});const Eu=/* @__PURE__ */Aa({moments_:function(e,t=null,n=!1){const r=y(t,(e=Ea(e,"x","moments")).shape),a=ku(e,r,n);let s=a.shape;n||(s=ki(a.shape,r));const o=Ai(uu(Ls(e,"float32"),vo(a,s)));return{mean:a,variance:ku(o,r,n)}}});const Ru=/* @__PURE__ */Aa({multiRNNCell_:function(e,t,n,r){const a=Ea(t,"data","multiRNNCell"),s=Ra(n,"c","multiRNNCell"),o=Ra(r,"h","multiRNNCell");let i=a;const u=[];for(let d=0;d2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${o}`);n=n||Math.random();const i={logits:1===o?vo(a,[1,-1]):a},u={numSamples:t,seed:n,normalized:r},l=wa.runKernel(Dt,i,u);return 1===o?vo(l,[l.size]):l}});const Au=/* @__PURE__ */Aa({notEqual_:function(e,t){let n=Ea(e,"a","notEqual","string_or_numeric"),r=Ea(t,"b","notEqual","string_or_numeric");[n,r]=fa(n,r),li(n.shape,r.shape);const a={a:n,b:r};return wa.runKernel(Lt,a)}});const Ou=/* @__PURE__ */Aa({oneHot_:function(e,t,n=1,r=0,a="int32"){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);const s={indices:Ea(e,"indices","oneHot","int32")},o={dtype:a,depth:t,onValue:n,offValue:r};return wa.runKernel(Ut,s,o)}});const Fu=/* @__PURE__ */Aa({onesLike_:function(e){const t={x:Ea(e,"x","onesLike")};return wa.runKernel(zt,t)}});const Du=/* @__PURE__ */Aa({outerProduct_:function(e,t){const n=Ea(e,"v1","outerProduct"),r=Ea(t,"v2","outerProduct");i(1===n.rank&&1===r.rank,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${r.rank}.`);const a=vo(n,[-1,1]),s=vo(r,[1,-1]);return No(a,s)}});const Mu=/* @__PURE__ */Aa({pad_:function(e,t,n=0){const r=Ea(e,"x","pad");if(0===r.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");const a={paddings:t,constantValue:n},s={x:r};return wa.runKernel(Ht,s,a)}});const Pu=/* @__PURE__ */Aa({pad1d_:function(e,t,n=0){return i(2===t.length,()=>"Invalid number of paddings. Must be length of 2."),Mu(e,[t],n)}});const Lu=/* @__PURE__ */Aa({pad2d_:function(e,t,n=0){return i(2===t.length&&2===t[0].length&&2===t[1].length,()=>"Invalid number of paddings. Must be length of 2 each."),Mu(e,t,n)}});const Bu=/* @__PURE__ */Aa({pad3d_:function(e,t,n=0){return i(3===t.length&&2===t[0].length&&2===t[1].length&&2===t[2].length,()=>"Invalid number of paddings. Must be length of 2 each."),Mu(e,t,n)}});const Vu=/* @__PURE__ */Aa({pad4d_:function(e,t,n=0){return i(4===t.length&&2===t[0].length&&2===t[1].length&&2===t[2].length&&2===t[3].length,()=>"Invalid number of paddings. Must be length of 2 each."),Mu(e,t,n)}});const Wu=/* @__PURE__ */Aa({spaceToBatchND_:function(e,t,n){const r=Ea(e,"x","spaceToBatchND");i(r.rank>=1+t.length,()=>`input rank ${r.rank} should be > than [blockShape] ${t.length}`),i(n.length===t.length,()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`),i(r.shape.reduce((e,r,a)=>a>0&&a<=t.length?e&&(r+n[a-1][0]+n[a-1][1])%t[a-1]===0:e,!0),()=>`input spatial dimensions ${r.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`);const a={x:r},s={blockShape:t,paddings:n};return wa.runKernel(Sn,a,s)}});const zu=/* @__PURE__ */Aa({pool_:function(e,t,n,r,a,s,o){null==a&&(a=[1,1]),null==s&&(s=1),0===r&&(r="valid");const u=Ea(e,"x","maxPool");let l=u,c=!1;3===u.rank&&(c=!0,l=vo(u,[1,u.shape[0],u.shape[1],u.shape[2]])),i(go(s,a),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${s} and dilations '${a}'`);const d=so(l.shape,t,s,a,r),p=[d.dilationHeight,d.dilationWidth];let h;h="same"===r?function(e,t){const n=e.map((e,n)=>e+(e-1)*(t[n]-1)),r=n.map(e=>e-1),a=r.map(e=>Math.floor(e/2)),s=r.map((e,t)=>e-a[t]);return r.map((e,t)=>[a[t],s[t]])}([d.filterHeight,d.filterWidth],p):[[0,0],[0,0]];const f=1===p[0]&&1===p[1],[m,g]=function(e,t,n){const r=n.map(e=>e[0]),a=n.map(e=>e[1]),s=e.concat(r,a),o=t.map((e,t)=>(e-s[t]%e)%e),i=a.map((e,t)=>e+o[t]),u=t.map((e,t)=>[r[t],i[t]]),l=t.map((e,t)=>[0,o[t]]);return[u,l]}([d.inHeight,d.inWidth],p,h),y=f?r:"valid",b=f?l:Wu(l,p,m),x=("avg"===n?()=>wo(b,t,s,y,o):()=>bu(b,t,s,y,o))(),v=f?x:Eo(x,p,g);return c?vo(v,[v.shape[1],v.shape[2],v.shape[3]]):v}});const Uu=/* @__PURE__ */Aa({prelu_:function(e,t){const n={x:Ea(e,"x","prelu"),alpha:Ea(t,"alpha","prelu")};return wa.runKernel(qt,n)}});const Gu=/* @__PURE__ */Aa({prod_:function(e,t=null,n=!1){let r=Ea(e,"x","prod");"bool"===r.dtype&&(r=Ls(r,"int32"));const a={x:r},s={axis:t,keepDims:n};return wa.runKernel(Kt,a,s)}});const Hu=/* @__PURE__ */Aa({raggedGather_:function(e,t,n,r){const a={paramsNestedSplits:e.map((e,t)=>Ea(e,`tensors${t}`,"raggedGather","int32")),paramsDenseValues:Ea(t,"paramsDenseValues","raggedGather"),indices:Ea(n,"indices","raggedGather","int32")},s={outputRaggedRank:r},o=wa.runKernel(Xt,a,s);return{outputNestedSplits:o.slice(0,o.length-1),outputDenseValues:o[o.length-1]}}});const ju=/* @__PURE__ */Aa({raggedRange_:function(e,t,n){const r=Ea(e,"starts","raggedRange"),a={starts:r,limits:Ea(t,"limits","raggedRange",r.dtype),deltas:Ea(n,"deltas","raggedRange",r.dtype)},s=wa.runKernel(Yt,a);return{rtNestedSplits:s[0],rtDenseValues:s[1]}}});const qu=/* @__PURE__ */Aa({raggedTensorToTensor_:function(e,t,n,r,a){const s=Ea(e,"shape","raggedTensorToTensor","int32"),o=Ea(t,"values","raggedTensorToTensor"),i={shape:s,values:o,defaultValue:Ea(n,"defaultValue","raggedTensorToTensor",o.dtype),rowPartitionTensors:r.map((e,t)=>Ea(e,`tensors${t}`,"raggedTensorToTensor","int32"))},u={rowPartitionTypes:a};return wa.runKernel(Qt,i,u)}});const Ku=/* @__PURE__ */Aa({rand_:function(e,t,n){O(e);const r=c(e);let a=null;if(null==n||"float32"===n)a=new Float32Array(r);else if("int32"===n)a=new Int32Array(r);else{if("bool"!==n)throw new Error(`Unknown data type ${n}`);a=new Uint8Array(r)}for(let s=0;s>>0,e=(r*=e)>>>0,e+=4294967296*(r-=e)}return 2.3283064365386963e-10*(e>>>0)};return t}();t.next=function(){var e=2091639*t.s0+2.3283064365386963e-10*t.c;return t.s0=t.s1,t.s1=t.s2,t.s2=e-(t.c=0|e)},t.c=1,t.s0=n(" "),t.s1=n(" "),t.s2=n(" "),t.s0-=n(e),t.s0<0&&(t.s0+=1),t.s1-=n(e),t.s1<0&&(t.s1+=1),t.s2-=n(e),t.s2<0&&(t.s2+=1),n=null}function r(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function a(e,t){var a=new n(e),s=t&&t.state,o=a.next;return o.int32=function(){return 4294967296*a.next()|0},o.double=function(){return o()+11102230246251565e-32*(2097152*o()|0)},o.quick=o,s&&("object"==typeof s&&r(s,a),o.state=function(){return r(a,{})}),o}t&&t.exports?t.exports=a:this.alea=a}(0,Yu)),Yu.exports}var Zu,Ju={exports:{}};var el,tl={exports:{}};var nl,rl={exports:{}};var al,sl={exports:{}};var ol,il={exports:{}};var ul={exports:{}};const ll=/* @__PURE__ */gr(/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));var cl,dl,pl,hl=ul.exports;function fl(){return cl||(cl=1,e=ul,function(t,n,r){var a,s=256,o="random",i=r.pow(s,6),u=r.pow(2,52),l=2*u,c=255;function d(e,c,d){var y=[],b=m(f((c=1==c?{entropy:!0}:c||{}).entropy?[e,g(n)]:e??function(){try{var e;return a&&(e=a.randomBytes)?e=e(s):(e=new Uint8Array(s),(t.crypto||t.msCrypto).getRandomValues(e)),g(e)}catch(i){var r=t.navigator,o=r&&r.plugins;return[+/* @__PURE__ */new Date,t,o,t.screen,g(n)]}}(),3),y),x=new p(y),v=function(){for(var e=x.g(6),t=i,n=0;e=l;)e/=2,t/=2,n>>>=1;return(e+n)/t};return v.int32=function(){return 0|x.g(4)},v.quick=function(){return x.g(4)/4294967296},v.double=v,m(g(x.S),n),(c.pass||d||function(e,t,n,a){return a&&(a.S&&h(a,x),e.state=function(){return h(x,{})}),n?(r[o]=e,t):e})(v,b,"global"in c?c.global:this==r,c.state)}function p(e){var t,n=e.length,r=this,a=0,o=r.i=r.j=0,i=r.S=[];for(n||(e=[n++]);a>>19^e^e>>>8},e===(0|e)?t.x=e:n+=e;for(var r=0;r>>0)/4294967296};return o.double=function(){do{var e=((a.next()>>>11)+(a.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=a.next,o.quick=o,s&&("object"==typeof s&&r(s,a),o.state=function(){return r(a,{})}),o}t&&t.exports?t.exports=a:this.xor128=a}(0,Ju)),Ju.exports),n=(el||(el=1,function(e,t){function n(e){var t=this,n="";t.next=function(){var e=t.x^t.x>>>2;return t.x=t.y,t.y=t.z,t.z=t.w,t.w=t.v,(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^e^e<<1)|0},t.x=0,t.y=0,t.z=0,t.w=0,t.v=0,e===(0|e)?t.x=e:n+=e;for(var r=0;r>>4),t.next()}function r(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t.v=e.v,t.d=e.d,t}function a(e,t){var a=new n(e),s=t&&t.state,o=function(){return(a.next()>>>0)/4294967296};return o.double=function(){do{var e=((a.next()>>>11)+(a.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=a.next,o.quick=o,s&&("object"==typeof s&&r(s,a),o.state=function(){return r(a,{})}),o}t&&t.exports?t.exports=a:this.xorwow=a}(0,tl)),tl.exports),r=(nl||(nl=1,function(e,t){function n(e){var t=this;t.next=function(){var e,n,r=t.x,a=t.i;return e=r[a],n=(e^=e>>>7)^e<<24,n^=(e=r[a+1&7])^e>>>10,n^=(e=r[a+3&7])^e>>>3,n^=(e=r[a+4&7])^e<<7,e=r[a+7&7],n^=(e^=e<<13)^e<<9,r[a]=n,t.i=a+1&7,n},function(e,t){var n,r=[];if(t===(0|t))r[0]=t;else for(t=""+t,n=0;n0;--n)e.next()}(t,e)}function r(e,t){return t.x=e.x.slice(),t.i=e.i,t}function a(e,t){null==e&&(e=+/* @__PURE__ */new Date);var a=new n(e),s=t&&t.state,o=function(){return(a.next()>>>0)/4294967296};return o.double=function(){do{var e=((a.next()>>>11)+(a.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=a.next,o.quick=o,s&&(s.x&&r(s,a),o.state=function(){return r(a,{})}),o}t&&t.exports?t.exports=a:this.xorshift7=a}(0,rl)),rl.exports),a=(al||(al=1,function(e,t){function n(e){var t=this;t.next=function(){var e,n,r=t.w,a=t.X,s=t.i;return t.w=r=r+1640531527|0,n=a[s+34&127],e=a[s=s+1&127],n^=n<<13,e^=e<<17,n^=n>>>15,e^=e>>>12,n=a[s]=n^e,t.i=s,n+(r^r>>>16)|0},function(e,t){var n,r,a,s,o,i=[],u=128;for(t===(0|t)?(r=t,t=null):(t+="\0",r=0,u=Math.max(u,t.length)),a=0,s=-32;s>>15,r^=r<<4,r^=r>>>13,s>=0&&(o=o+1640531527|0,a=0==(n=i[127&s]^=r+o)?a+1:0);for(a>=128&&(i[127&(t&&t.length||0)]=-1),a=127,s=512;s>0;--s)r=i[a+34&127],n=i[a=a+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,i[a]=r^n;e.w=o,e.X=i,e.i=a}(t,e)}function r(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function a(e,t){null==e&&(e=+/* @__PURE__ */new Date);var a=new n(e),s=t&&t.state,o=function(){return(a.next()>>>0)/4294967296};return o.double=function(){do{var e=((a.next()>>>11)+(a.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=a.next,o.quick=o,s&&(s.X&&r(s,a),o.state=function(){return r(a,{})}),o}t&&t.exports?t.exports=a:this.xor4096=a}(0,sl)),sl.exports),s=(ol||(ol=1,function(e,t){function n(e){var t=this,n="";t.next=function(){var e=t.b,n=t.c,r=t.d,a=t.a;return e=e<<25^e>>>7^n,n=n-r|0,r=r<<24^r>>>8^a,a=a-e|0,t.b=e=e<<20^e>>>12^n,t.c=n=n-r|0,t.d=r<<16^n>>>16^a,t.a=a-e|0},t.a=0,t.b=0,t.c=-1640531527,t.d=1367130551,e===Math.floor(e)?(t.a=e/4294967296|0,t.b=0|e):n+=e;for(var r=0;r>>0)/4294967296};return o.double=function(){do{var e=((a.next()>>>11)+(a.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=a.next,o.quick=o,s&&("object"==typeof s&&r(s,a),o.state=function(){return r(a,{})}),o}t&&t.exports?t.exports=a:this.tychei=a}(0,il)),il.exports),o=fl();return o.alea=e,o.xor128=t,o.xorwow=n,o.xorshift7=r,o.xor4096=a,o.tychei=s,dl=o}();class gl{constructor(e,t,n,r,a){this.mean=e,this.stdDev=t,this.dtype=n,this.nextVal=NaN,this.truncated=r,this.truncated&&(this.upper=this.mean+2*this.stdDev,this.lower=this.mean-2*this.stdDev);const s=a||Math.random();this.random=ml.alea(s.toString())}nextValue(){if(!isNaN(this.nextVal)){const e=this.nextVal;return this.nextVal=NaN,e}let e,t,n=!1;for(;!n;){let r,a,s;do{r=2*this.random()-1,a=2*this.random()-1,s=r*r+a*a}while(s>=1||0===s);const o=Math.sqrt(-2*Math.log(s)/s);e=this.mean+this.stdDev*r*o,t=this.mean+this.stdDev*a*o,this.truncated&&!this.isValidTruncated(e)||(n=!0)}return this.truncated&&!this.isValidTruncated(t)||(this.nextVal=this.convertValue(t)),this.convertValue(e)}convertValue(e){return null==this.dtype||"float32"===this.dtype?e:Math.round(e)}isValidTruncated(e){return e<=this.upper&&e>=this.lower}}class yl{constructor(e,t,n,r){this.alpha=e,this.beta=1/t,this.dtype=n;const a=r||Math.random();this.randu=ml.alea(a.toString()),this.randn=new gl(0,1,n,!1,this.randu()),this.d=e<1?e+2/3:e-1/3,this.c=1/Math.sqrt(9*this.d)}nextValue(){let e,t,n,r,a,s;for(;;){do{r=this.randn.nextValue(),s=1+this.c*r}while(s<=0);if(s*=s*s,e=r*r,t=1-.331*e*e,n=.5*e+this.d*(1-s+Math.log(s)),a=this.randu(),anull==this.dtype||"float32"===this.dtype,this.min=e,this.range=t-e,this.dtype=n,null==r&&(r=Math.random()),"number"===typeof r&&(r=r.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=ml.alea(r)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}const xl=/* @__PURE__ */Aa({randomGamma_:function(e,t,n=1,r="float32",a){if(O(e),null==n&&(n=1),null==r&&(r="float32"),"float32"!==r&&"int32"!==r)throw new Error(`Unsupported data type ${r}`);const s=new yl(t,n,r,a),o=Ps(e,r);for(let i=0;i`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),El(t,0)}});const _l=/* @__PURE__ */Aa({reverse2d_:function(e,t){const n=Ea(e,"x","reverse");return i(2===n.rank,()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`),El(n,t)}});const Al=/* @__PURE__ */Aa({reverse3d_:function(e,t){const n=Ea(e,"x","reverse");return i(3===n.rank,()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`),El(n,t)}});const Ol=/* @__PURE__ */Aa({reverse4d_:function(e,t){const n=Ea(e,"x","reverse");return i(4===n.rank,()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`),El(n,t)}});const Fl=/* @__PURE__ */Aa({round_:function(e){const t={x:Ea(e,"x","round")};return wa.runKernel(cn,t)}});const Dl=/* @__PURE__ */Aa({rsqrt_:function(e){const t={x:Ea(e,"x","rsqrt","float32")};return wa.runKernel(dn,t)}});const Ml=/* @__PURE__ */Aa({selu_:function(e){const t={x:Ea(e,"x","selu")};return wa.runKernel(gn,t)}});const Pl=/* @__PURE__ */Aa({separableConv2d_:function(e,t,n,r,a,s=[1,1],o="NHWC"){const u=Ea(e,"x","separableConv2d"),l=Ea(t,"depthwiseFilter","separableConv2d"),c=Ea(n,"pointwiseFilter","separableConv2d");let d=u,p=!1;if(3===u.rank&&(p=!0,d=vo(u,[1,u.shape[0],u.shape[1],u.shape[2]])),"NCHW"===o)throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");i(4===d.rank,()=>`Error in separableConv2d: input must be rank 4, but got rank ${d.rank}.`),i(4===l.rank,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),i(4===c.rank,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),i(1===c.shape[0],()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${c.shape[0]}.`),i(1===c.shape[1],()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${c.shape[1]}.`);const h=l.shape[2],f=l.shape[3];i(c.shape[2]===h*f,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${h*f}, but got ${c.shape[2]}.`);const m=ai(d,l,r,a,o,s),g=Ho(m,c,1,"valid",o);return p?vo(g,[g.shape[1],g.shape[2],g.shape[3]]):g}});const Ll=async function(e,t){const n=Ea(e,"x","setdiff1d"),r=Ea(t,"y","setdiff1d");i(n.dtype===r.dtype,()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${r.dtype}).`),i(1===n.rank,()=>`x should be 1D tensor, but got x (${n.shape}).`),i(1===r.rank,()=>`y should be 1D tensor, but got y (${r.shape}).`);const a=await n.data(),s=await r.data(),o=new Set(s);let u=0;for(let i=0;i`slice1d expects a rank-1 tensor, but got a rank-${r.rank} tensor`),To(r,[t],[n])}});const Ul=/* @__PURE__ */Aa({slice2d_:function(e,t,n){const r=Ea(e,"x","slice2d");return i(2===r.rank,()=>`slice2d expects a rank-2 tensor, but got a rank-${r.rank} tensor`),To(r,t,n)}});const Gl=/* @__PURE__ */Aa({slice3d_:function(e,t,n){const r=Ea(e,"x","slice3d");return i(3===r.rank,()=>`slice3d expects a rank-3 tensor, but got a rank-${r.rank} tensor`),To(r,t,n)}});const Hl=/* @__PURE__ */Aa({slice4d_:function(e,t,n){const r=Ea(e,"x","slice4d");return i(4===r.rank,()=>`slice4d expects a rank-4 tensor, but got a rank-${r.rank} tensor`),To(r,t,n)}});const jl=/* @__PURE__ */Aa({softmax_:function(e,t=-1){const n=Ea(e,"logits","softmax","float32");if(-1===t&&(t=n.rank-1),t!==n.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and dim was ${t}`);const r={logits:n},a={dim:t};return wa.runKernel(Cn,r,a)}});const ql=/* @__PURE__ */Aa({fft_:function(e){i("complex64"===e.dtype,()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);const t={input:e};return wa.runKernel(Ye,t)}});const Kl=/* @__PURE__ */Aa({ifft_:function(e){i("complex64"===e.dtype,()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);const t={input:e};return wa.runKernel(it,t)}});const Xl=/* @__PURE__ */Aa({irfft_:function(e){const t=e.shape[e.shape.length-1],n=e.size/t;let r;if(t<=2){const a=vo(e,[n,t]);r=Kl(a)}else{const a=[n,2*(t-1)],s=vo(Sl(e),[n,t]),o=vo(ji(e),[n,t]),i=El(To(s,[0,1],[n,t-2]),1),u=Gs(El(To(o,[0,1],[n,t-2]),1),Ri(-1)),l=Io([s,i],1),c=Io([o,u],1),d=vo(Oa(l,c),[a[0],a[1]]);r=Kl(d)}if(r=Sl(r),3===e.rank&&0!==e.shape[0]){const t=r,n=e.shape[0];r=vo(r,[n,r.shape[0]/n,r.shape[1]]),t.dispose()}return r}});const Yl=/* @__PURE__ */Aa({split_:function(e,t,n=0){const r={x:Ea(e,"x","split")},a={numOrSizeSplits:t,axis:n};return wa.runKernel(Tn,r,a)}});const Ql=/* @__PURE__ */Aa({rfft_:function(e,t){i("float32"===e.dtype,()=>`The dtype for rfft() must be real value but got ${e.dtype}`);let n=e.shape[e.shape.length-1];const r=e.size/n;let a;if(null!=t&&t0),s=e.shape.map(e=>e);s[e.shape.length-1]=t,a=To(e,r,s),n=t}else if(null!=t&&t>n){const r=e.shape.map(e=>e);r[e.shape.length-1]=t-n,a=Io([e,Iu(r)],e.shape.length-1),n=t}else a=e;const s=pi(a),o=vo(Oa(a,s),[r,n]),u=ql(o),l=Math.floor(n/2)+1,c=Sl(u),d=ji(u),p=Yl(c,[l,n-l],c.shape.length-1),h=Yl(d,[l,n-l],d.shape.length-1),f=a.shape.slice();return f[a.shape.length-1]=l,vo(Oa(p[0],h[0]),f)}});const Zl=/* @__PURE__ */Aa({squaredDifference_:function(e,t){let n=Ea(e,"a","squaredDifference"),r=Ea(t,"b","squaredDifference");[n,r]=fa(n,r),li(n.shape,r.shape);const a={a:n,b:r};return wa.runKernel(On,a,{})}});const Jl=/* @__PURE__ */Aa({squeeze_:function(e,t){const n=Ea(e,"x","squeeze","string_or_numeric");return vo(n,b(n.shape,t).newShape)}});const ec=/* @__PURE__ */Aa({stack_:function(e,t=0){const n=Ra(e,"tensors","stack","string_or_numeric");i(n.length>=1,()=>"Pass at least one tensor to tf.stack"),n.length>0&&i(t<=n[0].rank,()=>"Axis must be <= rank of the tensor");const r=n,a={axis:t};return wa.runKernel(Gt,r,a)}});const tc=/* @__PURE__ */Aa({step_:function(e,t=0){const n={x:Ea(e,"x","step")},r={alpha:t};return wa.runKernel(Qn,n,r)}});const nc=/* @__PURE__ */Aa({stridedSlice_:function(e,t,n,r,a=0,s=0,o=0,i=0,u=0){const l={x:Ea(e,"x","stridedSlice","string_or_numeric")},c={begin:t,end:n,strides:r,beginMask:a,endMask:s,ellipsisMask:o,newAxisMask:i,shrinkAxisMask:u};return wa.runKernel(Mn,l,c)}});const rc=/* @__PURE__ */Aa({tan_:function(e){const t={x:Ea(e,"x","tan","float32")};return wa.runKernel(Wn,t)}});function ac(e,t){l(e);const n=Ta(e,t);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return Fa(e,null,n,t)}function sc(e,t,n){if(l(e),null!=t&&2!==t.length)throw new Error("tensor2d() requires shape to have two numbers");const r=Ta(e,n);if(2!==r.length&&1!==r.length)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return Fa(e,t,r,n)}function oc(e,t,n){if(l(e),null!=t&&3!==t.length)throw new Error("tensor3d() requires shape to have three numbers");const r=Ta(e,n);if(3!==r.length&&1!==r.length)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return Fa(e,t,r,n)}function ic(e,t,n){if(l(e),null!=t&&4!==t.length)throw new Error("tensor4d() requires shape to have four numbers");const r=Ta(e,n);if(4!==r.length&&1!==r.length)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return Fa(e,t,r,n)}function uc(e,t,n){if(l(e),null!=t&&5!==t.length)throw new Error("tensor5d() requires shape to have five numbers");const r=Ta(e,n);if(5!==r.length&&1!==r.length)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return Fa(e,t,r,n)}function lc(e,t,n){if(l(e),null!=t&&6!==t.length)throw new Error("tensor6d() requires shape to have six numbers");const r=Ta(e,n);if(6!==r.length&&1!==r.length)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return Fa(e,t=t||r,r,n)}function cc(e,t,n){const r=t.rank>1?t.shape[t.rank-1]:1,a=t.rank>1?t.rank-1:1,s=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${n.shape}, indices.shape: ${t.shape}, shape: ${e}, sliceDim: ${r}, and batchDim: ${a}.`;if(n.rank1?t.shape[r-1]:1,s=n.length;let o=1;for(let u=a;u= 0 but got ${t}`);if(t>a)throw new Error(`'k' passed to topk() must be <= the last dimension (${a}) but got ${t}`);const s={x:r},o={k:t,sorted:n},[i,u]=wa.runKernel(Gn,s,o);return{values:i,indices:u}}});const mc=/* @__PURE__ */Aa({truncatedNormal_:function(e,t=0,n=1,r,a){if(O(e),null!=r&&"bool"===r)throw new Error("Unsupported data type $ { dtype }");const s=new gl(t,n,r,!0,a),o=Ps(e,r);for(let i=0;i0,()=>"The input tensor must be at least 1D");const r={x:n},a={axis:t},[s,o]=wa.runKernel(qn,r,a);return{values:s,indices:o}}});const yc=/* @__PURE__ */Aa({unsortedSegmentSum_:function(e,t,n){const r=Ea(e,"x","unsortedSegmentSum"),a=Ea(t,"segmentIds","unsortedSegmentSum","int32");i(p(n),()=>"numSegments must be of dtype int");const s={x:r,segmentIds:a},o={numSegments:n};return wa.runKernel(Xn,s,o)}});const bc=/* @__PURE__ */Aa({unstack_:function(e,t=0){const n=Ea(e,"x","unstack","string_or_numeric");i(t>=-n.shape.length&&t`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`);const r={value:n},a={axis:t};return wa.runKernel(Kn,r,a)}});function xc(e,t){return gu(e,t,"right")}function vc(e,t=!0,n,r){return wa.makeVariable(e,t,n,r)}function wc(e,t){const n=[];for(let s=0;s0,()=>"mask cannot be scalar"),u(l.slice(s,s+o),a.shape,"mask's shape must match the first K dimensions of tensor's shape,");let c=1;for(let i=s;it).reverse()),i(r.rank===t.length,()=>`Error in transpose: rank of input ${r.rank} must match length of perm ${t}.`),t.forEach(e=>{i(e>=0&&e`All entries in 'perm' must be between 0 and ${r.rank-1} but got ${t}`)}),r.rank<=1)return r.clone();const a={x:r},s={perm:t};return"complex64"===r.dtype?Ba(()=>{let e=Sl(r),t=ji(r);return e=wa.runKernel(jn,{x:e},s),t=wa.runKernel(jn,{x:t},s),n&&(t=su(t)),Oa(e,t)}):wa.runKernel(jn,a,s)}});const Sc=/* @__PURE__ */Aa({movingAverage_:function(e,t,n,r,a=!0){const s=Ea(e,"v","movingAverage"),o=Ea(t,"x","movingAverage"),u=Ea(n,"decay","movingAverage");var l,c;c=o,i((l=s).dtype===c.dtype,()=>`The dtypes of the first(${l.dtype}) and second(${c.dtype}) input must match`),i(d(s.shape,o.shape),()=>"Shape mismatch in v and x");const p=Ri(1),h=uu(p,u);let f=Gs(uu(o,s),h);if(a){i(null!=r,()=>"When using zeroDebias: true, step is required.");const e=Ea(r,"step","movingAverage");f=Us(f,uu(p,Ei(u,e)))}return Ws(s,f)}});const Tc=/* @__PURE__ */Aa({scatterND_:function(e,t,n){O(n);const r=Ea(e,"indices","scatterND","int32"),a=Ea(t,"updates","scatterND");dc(a,r,n);const s={indices:r,updates:a},o={shape:n};return wa.runKernel(pn,s,o)}});const Cc=/* @__PURE__ */Aa({sparseToDense_:function(e,t,n,r=0){O(n);const a=Ea(e,"sparseIndices","sparseToDense","int32"),s=Ea(t,"sparseValues","sparseToDense","string_or_numeric"),o=Ea(r,"defaultValue","sparseToDense",s.dtype);!function(e,t,n,r){if("int32"!==e.dtype)throw new Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was ${e.dtype}.`);if(e.rank>2)throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${e.shape}.`);const a=e.rank>0?e.shape[0]:1,s=e.rank>1?e.shape[1]:1;if(n.length!==s)throw new Error(`outputShape has incorrect number of elements:, ${n.length}, should be: ${s}.`);const o=t.size;if(0!==t.rank&&(1!==t.rank||o!==a))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${a}]`);if(t.dtype!==r.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(a,s,n,o);const i={sparseIndices:a,sparseValues:s,defaultValue:o},u={outputShape:n};return wa.runKernel(An,i,u)}});const $c=/* @__PURE__ */Aa({gatherND_:function(e,t){const n=Ea(t,"indices","gatherND","int32"),r={params:Ea(e,"x","gatherND","string_or_numeric"),indices:n};return wa.runKernel(rt,r)}});const Ec=/* @__PURE__ */Aa({dropout_:function(e,t,n,r){const a=Ea(e,"x","dropout");if(i("float32"===a.dtype,()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${a.dtype} tensor instead.`),i(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),0===t)return e instanceof Yr?a.clone():a;const s=function(e,t){if(null==t)return e.shape.slice();if(d(e.shape,t))return t;if(e.shape.length===t.length){const n=[];for(let r=0;r1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${r.rank}`),i(r.rank-1===a.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${r.rank} and targets rank ${a.rank}`),u(r.shape.slice(0,r.shape.length-1),a.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");const s=r.shape[r.shape.length-1];i(n>0&&n<=s,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${s}), but got ${n}`);const o=await r.data(),l=await a.data(),[c,d]=[o.length/s,s],p=x("bool",c);for(let i=0;it.value-e.value),p[i]=0;for(let a=0;a`Error in conv2dDerFilter: input must be rank 4, but got shape ${u.shape}.`),i(4===l.rank,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),i(4===n.length,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`);const c="NHWC"===s?u.shape[3]:u.shape[1],d="NHWC"===s?l.shape[3]:l.shape[1];i(c===n[2],()=>`Error in conv2dDerFilter: depth of input ${c}) must match input depth in filter (${n[2]}.`),i(d===n[3],()=>`Error in conv2dDerFilter: depth of dy (${d}) must match output depth for filter (${n[3]}).`),xo("conv2dDerFilter",a,o);const p={x:u,dy:l},h={strides:r,pad:a,dataFormat:s,dimRoundingMode:o,filterShape:n};return wa.runKernel(we,p,h)}});function Fc(e,t,n){if(null==n||"linear"===n)return e;if("relu"===n)return Gs(e,tc(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function Dc(e,t){let n=t;const r=ui(e.shape,t.shape);return r.length>0&&(n=Oi(n,r)),vo(n,e.shape)}function Mc(e,t,n,r){if("linear"===t)return e;if("relu"===t)return Cl(e);if("elu"===t)return gi(e);if("relu6"===t)return $l(e);if("prelu"===t)return Uu(e,n);if("leakyrelu"===t)return Yi(e,r);if("sigmoid"===t)return So(e);throw new Error(`Unknown fused activation ${t}.`)}const Pc=(e,t)=>!(e>0)||"linear"===t;const Lc=/* @__PURE__ */Aa({fusedConv2d_:function({x:e,filter:t,strides:n,pad:r,dataFormat:a="NHWC",dilations:s=[1,1],dimRoundingMode:o,bias:u,activation:l="linear",preluActivationWeights:c,leakyreluAlpha:d}){if(l=l||"linear",!1===Pc(wa.state.gradientDepth,l)){i("NHWC"===a,()=>`Error in fused conv2d: got dataFormat of ${a} but only NHWC is currently supported for the case of gradient depth is 0 and the activation is not linear.`);let p=Ho(e,t,n,r,a,s,o);return null!=u&&(p=Ws(p,u)),Mc(p,l,c,d)}const p=Ea(e,"x","conv2d","float32"),h=Ea(t,"filter","conv2d","float32");let f=p,m=!1;3===p.rank&&(m=!0,f=vo(p,[1,p.shape[0],p.shape[1],p.shape[2]])),i(4===f.rank,()=>`Error in fused conv2d: input must be rank 4, but got rank ${f.rank}.`),i(4===h.rank,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${h.rank}.`),xo("fused conv2d",r,o);const g="NHWC"===a?f.shape[3]:f.shape[1];i(h.shape[2]===g,()=>`Error in conv2d: depth of input (${g}) must match input depth for filter ${h.shape[2]}.`),i(go(n,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`);const y=io(f.shape,h.shape,n,s,r,o);let b,x;if(null!=u&&(b=Ea(u,"bias","fused conv2d"),[b]=fa(b,p),"NHWC"===a?li(y.outShape,b.shape):(i(b.shape.length<=1,()=>`Error in fused conv2d: only supports scalar or 1-D Tensor bias for NCHW format but got the bias of rank-${b.shape.length}.`),i(0===b.shape.length||b.shape[0]===y.outChannels||1===b.shape[0],()=>`Error in fused conv2d: bias shape (${b.shape}) is not compatible with the number of output channels (${y.outChannels})`))),null!=c){const e=c.shape;if(i(e.length<=1||3===e.length,()=>`Error in fused conv2d: only supports scalar, 1-D Tensor or 3-D Tensor PReLU activation weights but got a tensor of rank-${e.length}.`),1===e.length)i(1===e[0]||e[0]===y.outChannels,()=>`Error in fused conv2d: PReLU activation weights (${e}) is not compatible with the number of output channels (${y.outChannels}).`);else if(3===e.length)try{li(e,y.outShape)}catch(I){const t=`Error in fused conv2d: PReLU activation weights (${e}) is not compatible with the output shape of the conv2d (${y.outShape}).`;throw Error(t)}x=Ea(c,"prelu weights","fused conv2d")}const v=(e,t)=>{i("NHWC"===a,()=>`Error in gradient of fused conv2D: got dataFormat of ${a} but only NHWC is currently supported.`);const[o,u,c,d]=t,p=Fc(e,c,l);i(mo(s),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);const h=[qo(u.shape,p,o,n,r),Oc(u,p,o.shape,n,r)];if(null!=d){const e=Dc(d,p);h.push(e)}return h},w={x:f,filter:h,bias:b,preluActivationWeights:x},k={strides:n,pad:r,dataFormat:a,dilations:s,dimRoundingMode:o,activation:l,leakyreluAlpha:d};if(null==u){return au((e,t,n)=>{let r=wa.runKernel(tr,w,k);return n([t,e,r]),m&&(r=vo(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:v}})(f,h)}return au((e,t,n,r)=>{let a=wa.runKernel(tr,w,k);return r([t,e,a,n]),m&&(a=vo(a,[a.shape[1],a.shape[2],a.shape[3]])),{value:a,gradFunc:v}})(f,h,b)}});const Bc=Aa({depthwiseConv2dNativeBackpropFilter_:function(e,t,n,r,a,s=[1,1],o){let i=e;3===e.rank&&(i=vo(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let u=t;3===u.rank&&(u=vo(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const l={x:i,dy:u},c={strides:r,pad:a,dimRoundingMode:o,dilations:s,filterShape:n};return wa.runKernel(Fe,l,c)}});const Vc=Aa({depthwiseConv2dNativeBackpropInput_:function(e,t,n,r,a,s=[1,1],o){let i=t,u=!1;3===t.rank&&(u=!0,i=vo(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const l={dy:i,filter:n},c={strides:r,pad:a,dimRoundingMode:o,dilations:s,inputShape:e},d=wa.runKernel(De,l,c);return u?vo(d,[d.shape[1],d.shape[2],d.shape[3]]):d}});const Wc=/* @__PURE__ */Aa({fusedDepthwiseConv2d_:function({x:e,filter:t,strides:n,pad:r,dataFormat:a="NHWC",dilations:s=[1,1],dimRoundingMode:o,bias:u,activation:l="linear",preluActivationWeights:c,leakyreluAlpha:d}){if(!1===Pc(wa.state.gradientDepth,l)){let i=ai(e,t,n,r,a,s,o);return null!=u&&(i=Ws(i,u)),Mc(i,l,c,d)}const p=Ea(e,"x","depthwiseConv2d","float32"),h=Ea(t,"filter","depthwiseConv2d","float32");let f=p,m=!1;3===p.rank&&(m=!0,f=vo(p,[1,p.shape[0],p.shape[1],p.shape[2]])),i(4===f.rank,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${f.rank}.`),i(4===h.rank,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${h.rank}.`),i(f.shape[3]===h.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${f.shape[3]}) must match the inChannels dimension in filter ${h.shape[2]}.`),null==s&&(s=[1,1]),i(go(n,s),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`),xo("fused depthwiseConv2d",r,o);const g=io(f.shape,h.shape,n,s,r,o,!0);let y,b;null!=u&&(y=Ea(u,"bias","fused conv2d"),[y]=fa(y,p),li(g.outShape,y.shape)),null!=c&&(b=Ea(c,"prelu weights","fused depthwiseConv2d"));const x=(e,t)=>{i(mo(s),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${s}'`);const[a,u,c,d]=t,p=Fc(e,c,l),h=Vc(u.shape,p,a,n,r,s,o),f=Bc(u,p,a.shape,n,r,s,o);if(null!=d){return[h,f,Dc(y,p)]}return[h,f]},v={x:f,filter:h,bias:y,preluActivationWeights:b},w={strides:n,pad:r,dataFormat:a,dilations:s,dimRoundingMode:o,activation:l,leakyreluAlpha:d};if(null==u){return au((e,t,n)=>{let r=wa.runKernel(nr,v,w);return n([t,e,r]),m&&(r=vo(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:x}})(f,h)}return au((e,t,n,r)=>{let a=wa.runKernel(nr,v,w);return r([t,e,a,n]),m&&(a=vo(a,[a.shape[1],a.shape[2],a.shape[3]])),{value:a,gradFunc:x}})(f,h,y)}});const zc=/* @__PURE__ */Aa({fusedMatMul_:function({a:e,b:t,transposeA:n=!1,transposeB:r=!1,bias:a,activation:s="linear",preluActivationWeights:o,leakyreluAlpha:u=.2}){if(!1===Pc(wa.state.gradientDepth,s)){let i=No(e,t,n,r);return null!=a&&(i=Ws(i,a)),Mc(i,s,o,u)}let l=Ea(e,"a","fused matMul"),d=Ea(t,"b","fused matMul");[l,d]=fa(l,d);const p=n?l.shape[l.rank-2]:l.shape[l.rank-1],h=r?d.shape[d.rank-1]:d.shape[d.rank-2],f=n?l.shape[l.rank-1]:l.shape[l.rank-2],m=r?d.shape[d.rank-2]:d.shape[d.rank-1],g=l.shape.slice(0,-2),y=d.shape.slice(0,-2),b=c(g),x=c(y);i(p===h,()=>`Error in fused matMul: inner shapes (${p}) and (${h}) of Tensors with shapes ${l.shape} and ${d.shape} and transposeA=${n} and transposeB=${r} must match.`);const v=li(l.shape.slice(0,-2),d.shape.slice(0,-2)).concat([f,m]),w=vo(l,n?[b,p,f]:[b,f,p]),k=vo(d,r?[x,m,h]:[x,h,m]);let I,N;null!=a&&(I=Ea(a,"bias","fused matMul"),[I]=fa(I,l),li(v,I.shape)),null!=o&&(N=Ea(o,"prelu weights","fused matMul"));const S=(e,t)=>{const[o,i,u,l]=t,c=Fc(vo(e,u.shape),u,s);let d,p;if(n||r?!n&&r?(d=No(c,i,!1,!1),p=No(c,o,!0,!1)):n&&!r?(d=No(i,c,!1,!0),p=No(o,c,!1,!1)):(d=No(i,c,!0,!0),p=No(c,o,!0,!0)):(d=No(c,i,!1,!0),p=No(o,c,!0,!1)),null!=a){return[d,p,Dc(l,c)]}return[d,p]},T={a:w,b:k,bias:I,preluActivationWeights:N},C={transposeA:n,transposeB:r,activation:s,leakyreluAlpha:u};if(null==a){return au((e,t,n)=>{const r=wa.runKernel(er,T,C);return n([e,t,r]),{value:vo(r,v),gradFunc:S}})(w,k)}return au((e,t,n,r)=>{const a=wa.runKernel(er,T,C);return r([e,t,a,n]),{value:vo(a,v),gradFunc:S}})(w,k,I)}}),Uc=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,conv2d:Lc,depthwiseConv2d:Wc,matMul:zc},Symbol.toStringTag,{value:"Module"}));const Gc=/* @__PURE__ */Aa({hammingWindow_:function(e){return _c(e,.54,.46)}});const Hc=/* @__PURE__ */Aa({hannWindow_:function(e){return _c(e,.5,.5)}});const jc=/* @__PURE__ */Aa({frame_:function(e,t,n,r=!1,a=0){let s=0;const o=[];for(;s+t<=e.size;)o.push(To(e,s,t)),s+=n;if(r)for(;s`Error in cropAndResize: image must be rank 4,but got rank ${o.rank}.`),i(2===u.rank&&4===u.shape[1],()=>`Error in cropAndResize: boxes must be have size [${c},4] but had shape ${u.shape}.`),i(1===l.rank&&l.shape[0]===c,()=>`Error in cropAndResize: boxInd must be have size [${c}] but had shape ${u.shape}.`),i(2===r.length,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${r.length}.`),i(r[0]>=1&&r[1]>=1,()=>`cropSize must be atleast [1,1], but was ${r}`),i("bilinear"===a||"nearest"===a,()=>`method must be bilinear or nearest, but was ${a}`);const d={image:o,boxes:u,boxInd:l},p={method:a,extrapolationValue:s,cropSize:r};return wa.runKernel(Re,d,p)}});const Xc=/* @__PURE__ */Aa({flipLeftRight_:function(e){const t=Ea(e,"image","flipLeftRight","float32");i(4===t.rank,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);const n={image:t};return wa.runKernel(Ze,n,{})}});const Yc=/* @__PURE__ */Aa({grayscaleToRGB_:function(e){const t=Ea(e,"image","grayscaleToRGB"),n=t.rank-1,r=t.shape[n];i(t.rank>=2,()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`),i(1===r,()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${r}.`);const a=new Array(t.rank);return a.fill(1,0,n),a[n]=3,Vi(t,a)}});const Qc=/* @__PURE__ */Aa({rgbToGrayscale_:function(e){const t=Ea(e,"image","RGBToGrayscale"),n=t.rank-1,r=t.shape[n];i(t.rank>=2,()=>`Error in RGBToGrayscale: images must be at least rank 2, but got rank ${t.rank}.`),i(3===r,()=>`Error in RGBToGrayscale: last dimension of an RGB image should be size 3, but got size ${r}.`);const a=t.dtype,s=Ls(t,"float32"),o=ac([.2989,.587,.114]);let u;switch(t.rank){case 2:u=mi("ij,j->i",s,o);break;case 3:u=mi("ijk,k->ij",s,o);break;case 4:u=mi("ijkl,l->ijk",s,o);break;case 5:u=mi("ijklm,m->ijkl",s,o);break;case 6:u=mi("ijklmn,n->ijklm",s,o);break;default:throw new Error("Not a valid tensor rank.")}return u=Li(u,-1),Ls(u,a)}});const Zc=/* @__PURE__ */Aa({rotateWithOffset_:function(e,t,n=0,r=.5){const a=Ea(e,"image","rotateWithOffset","float32");i(4===a.rank,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${a.rank}.`);const s={image:a},o={radians:t,fillValue:n,center:r};return wa.runKernel(Jn,s,o)}});function Jc(e,t,n,r,a,s){null==r&&(r=.5),null==a&&(a=Number.NEGATIVE_INFINITY),null==s&&(s=0);const o=e.shape[0];return n=Math.min(n,o),i(0<=r&&r<=1,()=>`iouThreshold must be in [0, 1], but was '${r}'`),i(2===e.rank,()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`),i(4===e.shape[1],()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`),i(1===t.rank,()=>"scores must be a 1D tensor"),i(t.shape[0]===o,()=>`scores has incompatible shape with boxes. Expected ${o}, but was ${t.shape[0]}`),i(0<=s&&s<=1,()=>`softNmsSigma must be in [0, 1], but was '${s}'`),{maxOutputSize:n,iouThreshold:r,scoreThreshold:a,softNmsSigma:s}}const ed=/* @__PURE__ */Aa({nonMaxSuppression_:function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY){const s=Ea(e,"boxes","nonMaxSuppression","float32"),o=Ea(t,"scores","nonMaxSuppression","float32"),i=Jc(s,o,n,r,a),u={maxOutputSize:n=i.maxOutputSize,iouThreshold:r=i.iouThreshold,scoreThreshold:a=i.scoreThreshold};return wa.runKernel(Bt,{boxes:s,scores:o},u)}});function td(e,t,n){const r=function(e,t,n){return function(e,t,n){let r=0,a=e.length,s=0,o=!1;for(;r>>1);const i=n(t,e[s]);i>0?r=s+1:(a=s,o=!i)}return o?r:-r-1}(e,t,n||nd)}(e,t,n),a=r<0?-(r+1):r;e.splice(a,0,t)}function nd(e,t){return e>t?1:ea&&l.push({score:t[g],boxIndex:g,suppressBeginIndex:0});l.sort(ld);const c=s>0?-.5/s:0,d=[],p=[];for(;d.length0;){const t=l.pop(),{score:n,boxIndex:s,suppressBeginIndex:o}=t;if(n=o;--u){const n=id(e,s,d[u]);if(n>=r){i=!0;break}if(t.score=t.score*ud(r,c,n),t.score<=a)break}t.suppressBeginIndex=d.length,i||(t.score===n?(d.push(s),p.push(t.score)):t.score>a&&td(l,t,ld))}const h=d.length,f=n-h;i&&f>0&&(d.push(...new Array(f).fill(0)),p.push(...new Array(f).fill(0)));const m={selectedIndices:d};return o&&(m.selectedScores=p),u&&(m.validOutputs=h),m}function id(e,t,n){const r=e.subarray(4*t,4*t+4),a=e.subarray(4*n,4*n+4),s=Math.min(r[0],r[2]),o=Math.min(r[1],r[3]),i=Math.max(r[0],r[2]),u=Math.max(r[1],r[3]),l=Math.min(a[0],a[2]),c=Math.min(a[1],a[3]),d=Math.max(a[0],a[2]),p=Math.max(a[1],a[3]),h=(i-s)*(u-o),f=(d-l)*(p-c);if(h<=0||f<=0)return 0;const m=Math.max(s,l),g=Math.max(o,c),y=Math.min(i,d),b=Math.min(u,p),x=Math.max(y-m,0)*Math.max(b-g,0);return x/(h+f-x)}function ud(e,t,n){const r=Math.exp(t*n*n);return n<=e?r:0}function ld(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}const cd=async function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY){const s=Ea(e,"boxes","nonMaxSuppressionAsync"),o=Ea(t,"scores","nonMaxSuppressionAsync"),i=Jc(s,o,n,r,a);n=i.maxOutputSize,r=i.iouThreshold,a=i.scoreThreshold;const u=await Promise.all([s.data(),o.data()]),l=u[0],c=u[1],{selectedIndices:d}=rd(l,c,n,r,a);return s!==e&&s.dispose(),o!==t&&o.dispose(),ac(d,"int32")};const dd=/* @__PURE__ */Aa({nonMaxSuppressionWithScore_:function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY,s=0){const o=Ea(e,"boxes","nonMaxSuppression"),i=Ea(t,"scores","nonMaxSuppression"),u=Jc(o,i,n,r,a,s),l={boxes:o,scores:i},c={maxOutputSize:n=u.maxOutputSize,iouThreshold:r=u.iouThreshold,scoreThreshold:a=u.scoreThreshold,softNmsSigma:s=u.softNmsSigma},d=wa.runKernel(Wt,l,c);return{selectedIndices:d[0],selectedScores:d[1]}}});const pd=async function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY,s=0){const o=Ea(e,"boxes","nonMaxSuppressionAsync"),i=Ea(t,"scores","nonMaxSuppressionAsync"),u=Jc(o,i,n,r,a,s);n=u.maxOutputSize,r=u.iouThreshold,a=u.scoreThreshold,s=u.softNmsSigma;const l=await Promise.all([o.data(),i.data()]),c=l[0],d=l[1],{selectedIndices:p,selectedScores:h}=sd(c,d,n,r,a,s);return o!==e&&o.dispose(),i!==t&&i.dispose(),{selectedIndices:ac(p,"int32"),selectedScores:ac(h)}};const hd=/* @__PURE__ */Aa({nonMaxSuppressionPadded_:function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY,s=!1){const o=Ea(e,"boxes","nonMaxSuppression"),i=Ea(t,"scores","nonMaxSuppression"),u=Jc(o,i,n,r,a,null),l={boxes:o,scores:i},c={maxOutputSize:u.maxOutputSize,iouThreshold:u.iouThreshold,scoreThreshold:u.scoreThreshold,padToMaxOutputSize:s},d=wa.runKernel(Vt,l,c);return{selectedIndices:d[0],validOutputs:d[1]}}});const fd=async function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY,s=!1){const o=Ea(e,"boxes","nonMaxSuppressionAsync"),i=Ea(t,"scores","nonMaxSuppressionAsync"),u=Jc(o,i,n,r,a,null),l=u.maxOutputSize,c=u.iouThreshold,d=u.scoreThreshold,[p,h]=await Promise.all([o.data(),i.data()]),{selectedIndices:f,validOutputs:m}=ad(p,h,l,c,d,s);return o!==e&&o.dispose(),i!==t&&i.dispose(),{selectedIndices:ac(f,"int32"),validOutputs:Ri(m,"int32")}};const md=/* @__PURE__ */Aa({resizeBilinear_:function(e,t,n=!1,r=!1){const a=Ea(e,"images","resizeBilinear");i(3===a.rank||4===a.rank,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${a.rank}.`),i(2===t.length,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`),i(!1===r||!1===n,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let s=a,o=!1;3===a.rank&&(o=!0,s=vo(a,[1,a.shape[0],a.shape[1],a.shape[2]]));const u={images:s},l={alignCorners:n,halfPixelCenters:r,size:t},c=wa.runKernel(sn,u,l);return o?vo(c,[c.shape[1],c.shape[2],c.shape[3]]):c}});const gd=/* @__PURE__ */Aa({resizeNearestNeighbor_:function(e,t,n=!1,r=!1){const a=Ea(e,"images","resizeNearestNeighbor");i(3===a.rank||4===a.rank,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${a.rank}.`),i(2===t.length,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),i("float32"===a.dtype||"int32"===a.dtype,()=>"`images` must have `int32` or `float32` as dtype"),i(!1===r||!1===n,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let s=a,o=!1;3===a.rank&&(o=!0,s=vo(a,[1,a.shape[0],a.shape[1],a.shape[2]]));const u={images:s},l={alignCorners:n,halfPixelCenters:r,size:t},c=wa.runKernel(rn,u,l);return o?vo(c,[c.shape[1],c.shape[2],c.shape[3]]):c}});const yd=/* @__PURE__ */Aa({threshold_:function(e,t="binary",n=!1,r=.5){const a=Ea(e,"image","threshold"),s=a.shape[0]*a.shape[1];let o,u,l,c,d=Gs(ac([r]),255);if(i(3===a.rank,()=>`Error in threshold: image must be rank 3,but got rank ${a.rank}.`),i(3===a.shape[2]||1===a.shape[2],()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${a.shape[2]}.`),i("int32"===a.dtype||"float32"===a.dtype,()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${a.dtype}.`),i("otsu"===t||"binary"===t,()=>`Method must be binary or otsu, but was ${t}`),3===a.shape[2]){[o,u,l]=Yl(a,[1,1,1],-1);const e=Gs(o,.2989),t=Gs(u,.587),n=Gs(l,.114);c=Ws(Ws(e,t),n)}else c=e;if("otsu"===t){d=function(e,t){let n,r,a,s,o,i,u=ac([-1]),l=ac([0]),c=ac([0]);for(let d=0;d`Error in transform: image must be rank 4,but got rank ${o.rank}.`),i(2===u.rank&&(u.shape[0]===o.shape[0]||1===u.shape[0])&&8===u.shape[1],()=>"Error in transform: Input transform should be batch x 8 or 1 x 8"),i(null==s||2===s.length,()=>`Error in transform: outputShape must be [height, width] or null, but got ${s}.`);const l={image:o,transforms:u},c={interpolation:n,fillMode:r,fillValue:a,outputShape:s};return wa.runKernel(Hn,l,c)}});const xd=/* @__PURE__ */Aa({bandPart_:function(e,t,n){const r=Ea(e,"a","bandPart");i(r.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${r.rank}.`);const a=r.shape,[s,o]=r.shape.slice(-2);let u,l;"number"===typeof t?(i(t%1===0,()=>`bandPart(): numLower must be an integer, got ${t}.`),i(t<=s,()=>`bandPart(): numLower (${t}) must not be greater than the number of rows (${s}).`),u=Ea(t<0?s:t,"numLower","bandPart")):(i("int32"===t.dtype,()=>"bandPart(): numLower's dtype must be an int32."),u=di(Qi(t,0),s,Tu(t,s))),"number"===typeof n?(i(n%1===0,()=>`bandPart(): numUpper must be an integer, got ${n}.`),i(n<=o,()=>`bandPart(): numUpper (${n}) must not be greater than the number of columns (${o}).`),l=Ea(n<0?o:n,"numUpper","bandPart")):(i("int32"===n.dtype,()=>"bandPart(): numUpper's dtype must be an int32."),l=di(Qi(n,0),o,Tu(n,o)));const c=vo(Nl(0,s,1,"int32"),[-1,1]),d=Nl(0,o,1,"int32"),p=uu(c,d),h=du(Zi(p,u),Hi(p,su(l))),f=Iu([s,o],r.dtype);return vo(ec(bc(vo(r,[-1,s,o])).map(e=>di(h,e,f))),a)}});const vd=/* @__PURE__ */Aa({gramSchmidt_:function(e){let t;if(Array.isArray(e)){t=!1,i(null!=e&&e.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");const n=e[0].shape[0];for(let t=1;t`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[t].shape[0]} vs. ${n})`)}else t=!0,e=Yl(e,e.shape[0],0).map(e=>Jl(e,[0]));i(e.length<=e[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`);const n=[],r=e;for(let a=0;a{let e=r[a];if(a>0)for(let t=0;t{i(2===e.shape.length,()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`);const n=e.shape[0],r=e.shape[1];let a=Wi(n),s=Bs(e);const o=sc([[1]],[1,1]);let u=Bs(o);const l=n>=r?r:n;for(let e=0;e{const t=To(s,[e,e],[n-e,1]),i=Di(t),l=To(s,[e,e],[1,1]),c=di(Gi(l,0),sc([[-1]]),sc([[1]])),d=uu(l,Gs(c,i)),p=Us(t,d);u=1===p.shape[0]?Bs(o):Io([o,To(p,[1,0],[p.shape[0]-1,p.shape[1]])],0);const h=su(Us(No(c,d),i)),f=To(s,[e,0],[n-e,r]),m=Gs(h,u),g=Nc(u);if(0===e)s=uu(f,No(m,No(g,f)));else{const t=uu(f,No(m,No(g,f)));s=Io([To(s,[0,0],[e,r]),t],0)}const y=Nc(m),b=To(a,[0,e],[n,a.shape[1]-e]);if(0===e)a=uu(b,No(No(b,u),y));else{const t=uu(b,No(No(b,u),y));a=Io([To(a,[0,0],[n,e]),t],1)}return[u,s,a]}),Va([t,i,l])}return!t&&n>r&&(a=To(a,[0,0],[n,r]),s=To(s,[0,0],[r,r])),[a,s]})}const kd=/* @__PURE__ */Aa({qr_:function(e,t=!1){if(i(e.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`),2===e.rank)return wd(e,t);{const n=e.shape.slice(0,e.shape.length-2).reduce((e,t)=>e*t),r=bc(vo(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),a=[],s=[];r.forEach(e=>{const[n,r]=wd(e,t);a.push(n),s.push(r)});return[vo(ec(a,0),e.shape),vo(ec(s,0),e.shape)]}}});var Id,Nd;(Nd=Id||(Id={}))[Nd.NONE=0]="NONE",Nd[Nd.MEAN=1]="MEAN",Nd[Nd.SUM=2]="SUM",Nd[Nd.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS";const Sd=/* @__PURE__ */Aa({computeWeightedLoss_:function(e,t,n=Id.SUM_BY_NONZERO_WEIGHTS){const r=Ea(e,"losses","computeWeightedLoss");let a=null;null!=t&&(a=Ea(t,"weights","computeWeightedLoss"));const s=null==a?r:Gs(r,a);if(n===Id.NONE)return s;if(n===Id.SUM)return Oi(s);if(n===Id.MEAN){if(null==a)return ku(s);{const e=r.size/a.size,t=Us(Oi(s),Oi(a));return e>1?Us(t,Ri(e)):t}}if(n===Id.SUM_BY_NONZERO_WEIGHTS){if(null==a)return Us(Oi(s),Ri(r.size));{const e=Gs(a,Nu(r.shape)),t=Ls(Oi(Au(e,Ri(0))),"float32");return Us(Oi(s),t)}}throw Error(`Unknown reduction: ${n}`)}});const Td=/* @__PURE__ */Aa({absoluteDifference_:function(e,t,n,r=Id.SUM_BY_NONZERO_WEIGHTS){const a=Ea(e,"labels","absoluteDifference"),s=Ea(t,"predictions","absoluteDifference");let o=null;null!=n&&(o=Ea(n,"weights","absoluteDifference")),u(a.shape,s.shape,"Error in absoluteDifference: ");const i=Hs(uu(a,s));return Sd(i,o,r)}});const Cd=/* @__PURE__ */Aa({cosineDistance_:function(e,t,n,r,a=Id.SUM_BY_NONZERO_WEIGHTS){const s=Ea(e,"labels","cosineDistance"),o=Ea(t,"predictions","cosineDistance");let i=null;null!=r&&(i=Ea(r,"weights","cosineDistance")),u(s.shape,o.shape,"Error in cosineDistance: ");const l=Ri(1),c=uu(l,Oi(Gs(s,o),n,!0));return Sd(c,i,a)}});const $d=/* @__PURE__ */Aa({hingeLoss_:function(e,t,n,r=Id.SUM_BY_NONZERO_WEIGHTS){let a=Ea(e,"labels","hingeLoss");const s=Ea(t,"predictions","hingeLoss");let o=null;null!=n&&(o=Ea(n,"weights","hingeLoss")),u(a.shape,s.shape,"Error in hingeLoss: ");const i=Ri(1);a=uu(Gs(Ri(2),a),i);const l=Cl(uu(i,Gs(a,s)));return Sd(l,o,r)}});const Ed=/* @__PURE__ */Aa({huberLoss_:function(e,t,n,r=1,a=Id.SUM_BY_NONZERO_WEIGHTS){const s=Ea(e,"labels","huberLoss"),o=Ea(t,"predictions","huberLoss");let i=null;null!=n&&(i=Ea(n,"weights","huberLoss")),u(s.shape,o.shape,"Error in huberLoss: ");const l=Ri(r),c=Hs(uu(o,s)),d=Tu(c,l),p=uu(c,d),h=Ws(Gs(Ri(.5),Ai(d)),Gs(l,p));return Sd(h,i,a)}});const Rd=/* @__PURE__ */Aa({logLoss_:function(e,t,n,r=1e-7,a=Id.SUM_BY_NONZERO_WEIGHTS){const s=Ea(e,"labels","logLoss"),o=Ea(t,"predictions","logLoss");let i=null;null!=n&&(i=Ea(n,"weights","logLoss")),u(s.shape,o.shape,"Error in logLoss: ");const l=Ri(1),c=Ri(r),d=su(Gs(s,tu(Ws(o,c)))),p=Gs(uu(l,s),tu(Ws(uu(l,o),c))),h=uu(d,p);return Sd(h,i,a)}});const _d=/* @__PURE__ */Aa({meanSquaredError_:function(e,t,n,r=Id.SUM_BY_NONZERO_WEIGHTS){const a=Ea(e,"labels","meanSquaredError"),s=Ea(t,"predictions","meanSquaredError");let o=null;null!=n&&(o=Ea(n,"weights","meanSquaredError")),u(a.shape,s.shape,"Error in meanSquaredError: ");const i=Zl(a,s);return Sd(i,o,r)}});const Ad=/* @__PURE__ */Aa({sigmoidCrossEntropy_:function(e,t,n,r=0,a=Id.SUM_BY_NONZERO_WEIGHTS){let s=Ea(e,"multiClassLabels","sigmoidCrossEntropy");const o=Ea(t,"logits","sigmoidCrossEntropy");let i=null;if(null!=n&&(i=Ea(n,"weights","sigmoidCrossEntropy")),u(s.shape,o.shape,"Error in sigmoidCrossEntropy: "),r>0){const e=Ri(r),t=Ri(1),n=Ri(.5);s=Ws(Gs(s,uu(t,e)),Gs(n,e))}const l=function(e,t){const n=Ea(e,"labels","sigmoidCrossEntropyWithLogits"),r=Ea(t,"logits","sigmoidCrossEntropyWithLogits");u(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");const a=Cl(r),s=Gs(r,n),o=nu(Pi(su(Hs(r))));return Ws(uu(a,s),o)}(s,o);return Sd(l,i,a)}});const Od=/* @__PURE__ */Aa({softmaxCrossEntropy_:function(e,t,n,r=0,a=Id.SUM_BY_NONZERO_WEIGHTS){let s=Ea(e,"onehotLabels","softmaxCrossEntropy");const o=Ea(t,"logits","softmaxCrossEntropy");let i=null;if(null!=n&&(i=Ea(n,"weights","softmaxCrossEntropy")),u(s.shape,o.shape,"Error in softmaxCrossEntropy: "),r>0){const e=Ri(r),t=Ri(1),n=Ri(s.shape[1]);s=Ws(Gs(s,uu(t,e)),Us(e,n))}const l=function(e,t,n=-1){if(-1===n&&(n=t.rank-1),n!==t.rank-1)throw Error(`Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank ${t.rank} and dim was ${n}`);return au((e,t,r)=>{const a=cu(t,[n],!0),s=uu(Ls(t,"float32"),a);r([e,s]);const o=su(Gs(s,e));return{value:Oi(o,[n]),gradFunc:(e,t)=>{const[r,a]=t,s=ki(e.shape,[n]);return[Gs(vo(e,s),uu(Ls(r,"float32"),Pi(a))),Gs(vo(e,s),uu(Pi(a),Ls(r,"float32")))]}}})(e,t)}(s,o);return Sd(l,i,a)}});const Fd={fft:ql,ifft:Kl,rfft:Ql,irfft:Xl},Dd={hammingWindow:Gc,hannWindow:Hc,frame:jc,stft:qc},Md={flipLeftRight:Xc,grayscaleToRGB:Yc,resizeNearestNeighbor:gd,resizeBilinear:md,rgbToGrayscale:Qc,rotateWithOffset:Zc,cropAndResize:Kc,nonMaxSuppression:ed,nonMaxSuppressionAsync:cd,nonMaxSuppressionWithScore:dd,nonMaxSuppressionWithScoreAsync:pd,nonMaxSuppressionPadded:hd,nonMaxSuppressionPaddedAsync:fd,threshold:yd,transform:bd},Pd={bandPart:xd,gramSchmidt:vd,qr:kd},Ld={absoluteDifference:Td,computeWeightedLoss:Sd,cosineDistance:Cd,hingeLoss:$d,huberLoss:Ed,logLoss:Rd,meanSquaredError:_d,sigmoidCrossEntropy:Ad,softmaxCrossEntropy:Od},Bd={sparseFillEmptyRows:/* @__PURE__ */Aa({sparseFillEmptyRows_:function(e,t,n,r){const a=Ea(e,"indices","sparseFillEmptyRows","int32"),s=Ea(t,"values","sparseFillEmptyRows"),o=Ea(n,"denseShape","sparseFillEmptyRows","int32"),i=Ea(r,"defaultValue","sparseFillEmptyRows",s.dtype);if(2!==a.rank)throw new Error(`Indices should be Tensor2D but received shape\n ${a.shape}`);if(1!==s.rank)throw new Error(`Values should be Tensor1D but received shape ${s.shape}`);if(1!==o.rank)throw new Error(`Dense shape should be Tensor1D but received shape ${o.shape}`);if(0!==i.rank)throw new Error(`Default value should be a scalar but received shape ${i.shape}`);const u={indices:a,values:s,denseShape:o,defaultValue:i},l=wa.runKernel($n,u);return{outputIndices:l[0],outputValues:l[1],emptyRowIndicator:l[2],reverseIndexMap:l[3]}}}),sparseReshape:/* @__PURE__ */Aa({sparseReshape_:function(e,t,n){const r=Ea(e,"inputIndices","sparseReshape","int32"),a=Ea(t,"inputShape","sparseReshape","int32"),s=Ea(n,"newShape","sparseReshape","int32");if(2!==r.rank)throw new Error(`Input indices should be Tensor2D but received shape\n ${r.shape}`);if(1!==a.rank)throw new Error(`Input shape should be Tensor1D but received shape ${a.shape}`);if(1!==s.rank)throw new Error(`New shape should be Tensor1D but received shape ${s.shape}`);const o={inputIndices:r,inputShape:a,newShape:s},i=wa.runKernel(En,o);return{outputIndices:i[0],outputShape:i[1]}}}),sparseSegmentMean:/* @__PURE__ */Aa({sparseSegmentMean_:function(e,t,n){const r=Ea(e,"data","sparseSegmentMean"),a=Ea(t,"indices","sparseSegmentMean","int32"),s=Ea(n,"segmentIds","sparseSegmentMean","int32");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==a.rank)throw new Error(`Indices should be Tensor1D but received shape\n ${a.shape}`);if(1!==s.rank)throw new Error(`Segment ids should be Tensor1D but received shape\n ${s.shape}`);const o={data:r,indices:a,segmentIds:s};return wa.runKernel(Rn,o)}}),sparseSegmentSum:/* @__PURE__ */Aa({sparseSegmentSum_:function(e,t,n){const r=Ea(e,"data","sparseSegmentSum"),a=Ea(t,"indices","sparseSegmentSum","int32"),s=Ea(n,"segmentIds","sparseSegmentSum","int32");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==a.rank)throw new Error(`Indices should be Tensor1D but received shape\n ${a.shape}`);if(1!==s.rank)throw new Error(`Segment ids should be Tensor1D but received shape\n ${s.shape}`);const o={data:r,indices:a,segmentIds:s};return wa.runKernel(_n,o)}})},Vd={stringNGrams:/* @__PURE__ */Aa({stringNGrams_:function(e,t,n,r,a,s,o,i){const u=Ea(e,"data","stringNGrams","string");if("string"!==u.dtype)throw new Error("Data must be of datatype string");if(1!==u.shape.length)throw new Error(`Data must be a vector, saw: ${u.shape}`);const l=Ea(t,"dataSplits","stringNGrams");if("int32"!==l.dtype)throw new Error("Data splits must be of datatype int32");const c={separator:n,nGramWidths:r,leftPad:a,rightPad:s,padWidth:o,preserveShortSequences:i},d={data:u,dataSplits:l},p=wa.runKernel(Pn,d,c);return{nGrams:p[0],nGramsSplits:p[1]}}}),stringSplit:/* @__PURE__ */Aa({stringSplit_:function(e,t,n=!0){const r=Ea(e,"input","stringSplit","string"),a=Ea(t,"delimiter","stringSplit","string");if(1!==r.rank)throw new Error(`Input should be Tensor1D but received shape ${r.shape}`);if(0!==a.rank)throw new Error(`Delimiter should be a scalar but received shape ${a.shape}`);const s={skipEmpty:n},o={input:r,delimiter:a},i=wa.runKernel(Ln,o,s);return{indices:i[0],values:i[1],shape:i[2]}}}),stringToHashBucketFast:/* @__PURE__ */Aa({stringToHashBucketFast_:function(e,t){const n=Ea(e,"input","stringToHashBucketFast","string"),r={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");const a={input:n};return wa.runKernel(Bn,a,r)}}),staticRegexReplace:/* @__PURE__ */Aa({staticRegexReplace_:function(e,t,n,r=!0){const a=Ea(e,"input","staticRegexReplace","string"),s={pattern:t,rewrite:n,replaceGlobal:r};return wa.runKernel(Dn,{x:a},s)}})},Wd=/* @__PURE__ */new Map,zd=/* @__PURE__ */new Map;class Ud{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}}class Gd{constructor(){this.classNameMap={}}static getMap(){return null==Gd.instance&&(Gd.instance=new Gd),Gd.instance}static register(e){Gd.getMap().classNameMap[e.className]=[e,e.fromConfig]}}function Hd(e,t,n){i(null!=e.className,()=>"Class being registered does not have the static className property defined."),i("string"===typeof e.className,()=>"className is required to be a string, but got type "+typeof e.className),i(e.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),"undefined"===typeof t&&(t="Custom"),"undefined"===typeof n&&(n=e.className);const r=t+">"+n;return Gd.register(e),Wd.set(r,e),zd.set(e,r),e}class jd extends Ud{minimize(e,t=!1,n){const{value:r,grads:a}=this.computeGradients(e,n);if(null!=n){const e=n.map(e=>({name:e.name,tensor:a[e.name]}));this.applyGradients(e)}else this.applyGradients(a);return Va(a),t?r:(r.dispose(),null)}get iterations(){return null==this.iterations_&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return ru(e,t)}dispose(){null!=this.iterations_&&Va(this.iterations_)}async saveIterations(){return null==this.iterations_&&(this.iterations_=0),{name:"iter",tensor:Ri(this.iterations_,"int32")}}async getWeights(){throw new Error("getWeights() is not implemented for this optimizer yet.")}async setWeights(e){throw new Error(`setWeights() is not implemented for this optimizer class ${this.getClassName()}`)}async extractIterations(e){return this.iterations_=(await e[0].tensor.data())[0],e.slice(1)}}Object.defineProperty(jd,Symbol.hasInstance,{value:e=>null!=e.minimize&&null!=e.computeGradients&&null!=e.applyGradients});class qd extends jd{static get className(){return"Adadelta"}constructor(e,t,n=null){super(),this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],null==n&&(this.epsilon=wa.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(e=>e.name):Object.keys(e)).forEach((t,n)=>{const r=wa.registeredVariables[t],a=!1;null==this.accumulatedGrads[n]&&(this.accumulatedGrads[n]={originalName:`${t}/accum_grad`,variable:Ba(()=>pi(r).variable(a))}),null==this.accumulatedUpdates[n]&&(this.accumulatedUpdates[n]={originalName:`${t}/accum_var`,variable:Ba(()=>pi(r).variable(a))});const s=Array.isArray(e)?e[n].tensor:e[t];if(null==s)return;const o=this.accumulatedGrads[n].variable,i=this.accumulatedUpdates[n].variable;Ba(()=>{const e=Ws(Gs(o,this.rho),Gs(Ai(s),1-this.rho)),t=Gs(Us(_i(Ws(i,this.epsilon)),_i(Ws(o,this.epsilon))),s),n=Ws(Gs(i,this.rho),Gs(Ai(t),1-this.rho));o.assign(e),i.assign(n);const a=Ws(Gs(t,-this.learningRate),r);r.assign(a)})}),this.incrementIterations()}dispose(){null!=this.accumulatedUpdates&&(Va(this.accumulatedGrads.map(e=>e.variable)),Va(this.accumulatedUpdates.map(e=>e.variable)))}async getWeights(){const e=[...this.accumulatedGrads,...this.accumulatedUpdates];return[await this.saveIterations()].concat(e.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){const t=(e=await this.extractIterations(e)).length/2,n=!1;this.accumulatedGrads=e.slice(0,t).map(e=>({originalName:e.name,variable:e.tensor.variable(n)})),this.accumulatedUpdates=e.slice(t,2*t).map(e=>({originalName:e.name,variable:e.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}}class Kd extends jd{static get className(){return"Adagrad"}constructor(e,t=.1){super(),this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){(Array.isArray(e)?e.map(e=>e.name):Object.keys(e)).forEach((t,n)=>{const r=wa.registeredVariables[t];if(null==this.accumulatedGrads[n]){const e=!1;this.accumulatedGrads[n]={originalName:`${t}/accumulator`,variable:Ba(()=>Bo(r.shape,this.initialAccumulatorValue).variable(e))}}const a=Array.isArray(e)?e[n].tensor:e[t];if(null==a)return;const s=this.accumulatedGrads[n].variable;Ba(()=>{const e=Ws(s,Ai(a));s.assign(e);const t=Ws(Gs(Us(a,_i(Ws(e,wa.backend.epsilon()))),-this.learningRate),r);r.assign(t)})}),this.incrementIterations()}dispose(){null!=this.accumulatedGrads&&Va(this.accumulatedGrads.map(e=>e.variable))}async getWeights(){return[await this.saveIterations()].concat(this.accumulatedGrads.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);this.accumulatedGrads=e.map(e=>({originalName:e.name,variable:e.tensor.variable(false)}))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}}class Xd extends jd{static get className(){return"Adam"}constructor(e,t,n,r=null){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=r,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],Ba(()=>{this.accBeta1=Ri(t).variable(),this.accBeta2=Ri(n).variable()}),null==r&&(this.epsilon=wa.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(e=>e.name):Object.keys(e);Ba(()=>{const n=uu(1,this.accBeta1),r=uu(1,this.accBeta2);t.forEach((t,a)=>{const s=wa.registeredVariables[t],o=!1;null==this.accumulatedFirstMoment[a]&&(this.accumulatedFirstMoment[a]={originalName:`${t}/m`,variable:Ba(()=>pi(s).variable(o))}),null==this.accumulatedSecondMoment[a]&&(this.accumulatedSecondMoment[a]={originalName:`${t}/v`,variable:Ba(()=>pi(s).variable(o))});const i=Array.isArray(e)?e[a].tensor:e[t];if(null==i)return;const u=this.accumulatedFirstMoment[a].variable,l=this.accumulatedSecondMoment[a].variable,c=Ws(Gs(u,this.beta1),Gs(i,1-this.beta1)),d=Ws(Gs(l,this.beta2),Gs(Ai(i),1-this.beta2)),p=Us(c,n),h=Us(d,r);u.assign(c),l.assign(d);const f=Ws(Gs(Us(p,Ws(_i(h),this.epsilon)),-this.learningRate),s);s.assign(f)}),this.accBeta1.assign(Gs(this.accBeta1,this.beta1)),this.accBeta2.assign(Gs(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),null!=this.accumulatedFirstMoment&&Va(this.accumulatedFirstMoment.map(e=>e.variable)),null!=this.accumulatedSecondMoment&&Va(this.accumulatedSecondMoment.map(e=>e.variable))}async getWeights(){const e=[...this.accumulatedFirstMoment,...this.accumulatedSecondMoment];return[await this.saveIterations()].concat(e.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e),Ba(()=>{this.accBeta1.assign(Ei(this.beta1,this.iterations_+1)),this.accBeta2.assign(Ei(this.beta2,this.iterations_+1))});const t=e.length/2,n=!1;this.accumulatedFirstMoment=e.slice(0,t).map(e=>({originalName:e.name,variable:e.tensor.variable(n)})),this.accumulatedSecondMoment=e.slice(t,2*t).map(e=>({originalName:e.name,variable:e.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)}}class Yd extends jd{static get className(){return"Adamax"}constructor(e,t,n,r=null,a=0){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=r,this.decay=a,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],Ba(()=>{this.iteration=Ri(0).variable(),this.accBeta1=Ri(t).variable()}),null==r&&(this.epsilon=wa.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(e=>e.name):Object.keys(e);Ba(()=>{const n=uu(1,this.accBeta1),r=Us(-this.learningRate,Ws(Gs(this.iteration,this.decay),1));t.forEach((t,a)=>{const s=wa.registeredVariables[t],o=!1;null==this.accumulatedFirstMoment[a]&&(this.accumulatedFirstMoment[a]={originalName:`${t}/m`,variable:pi(s).variable(o)}),null==this.accumulatedWeightedInfNorm[a]&&(this.accumulatedWeightedInfNorm[a]={originalName:`${t}/v`,variable:pi(s).variable(o)});const i=Array.isArray(e)?e[a].tensor:e[t];if(null==i)return;const u=this.accumulatedFirstMoment[a].variable,l=this.accumulatedWeightedInfNorm[a].variable,c=Ws(Gs(u,this.beta1),Gs(i,1-this.beta1)),d=Gs(l,this.beta2),p=Hs(i),h=wu(d,p);u.assign(c),l.assign(h);const f=Ws(Gs(Us(r,n),Us(c,Ws(h,this.epsilon))),s);s.assign(f)}),this.iteration.assign(Ws(this.iteration,1)),this.accBeta1.assign(Gs(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),null!=this.accumulatedFirstMoment&&Va(this.accumulatedFirstMoment.map(e=>e.variable)),null!=this.accumulatedWeightedInfNorm&&Va(this.accumulatedWeightedInfNorm.map(e=>e.variable))}async getWeights(){throw new Error("getWeights() is not implemented for Adamax yet.")}async setWeights(e){throw new Error("setWeights() is not implemented for Adamax yet.")}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon,t.decay)}}class Qd extends jd{static get className(){return"SGD"}constructor(e){super(),this.learningRate=e,this.setLearningRate(e)}applyGradients(e){(Array.isArray(e)?e.map(e=>e.name):Object.keys(e)).forEach((t,n)=>{const r=Array.isArray(e)?e[n].tensor:e[t];if(null==r)return;const a=wa.registeredVariables[t];Ba(()=>{const e=Ws(Gs(this.c,r),a);a.assign(e)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,null!=this.c&&this.c.dispose(),this.c=Wa(Ri(-e))}dispose(){this.c.dispose()}async getWeights(){return[await this.saveIterations()]}async setWeights(e){if(0!==(e=await this.extractIterations(e)).length)throw new Error("SGD optimizer does not have settable weights.")}getConfig(){return{learningRate:this.learningRate}}static fromConfig(e,t){return new e(t.learningRate)}}class Zd extends Qd{static get className(){return"Momentum"}constructor(e,t,n=!1){super(e),this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=Ri(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(e=>e.name):Object.keys(e)).forEach((t,n)=>{const r=wa.registeredVariables[t];if(null==this.accumulations[n]){const e=!1;this.accumulations[n]={originalName:`${t}/momentum`,variable:Ba(()=>pi(r).variable(e))}}const a=this.accumulations[n].variable,s=Array.isArray(e)?e[n].tensor:e[t];null!=s&&Ba(()=>{let e;const t=Ws(Gs(this.m,a),s);e=this.useNesterov?Ws(Gs(this.c,Ws(s,Gs(t,this.m))),r):Ws(Gs(this.c,t),r),a.assign(t),r.assign(e)})}),this.incrementIterations()}dispose(){this.m.dispose(),null!=this.accumulations&&Va(this.accumulations.map(e=>e.variable))}setMomentum(e){this.momentum=e}async getWeights(){return[await this.saveIterations()].concat(this.accumulations.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);this.accumulations=e.map(e=>({originalName:e.name,variable:e.tensor.variable(false)}))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)}}class Jd extends jd{static get className(){return"RMSProp"}constructor(e,t=.9,n=0,r=null,a=!1){if(super(),this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=r,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=a,null==r&&(this.epsilon=wa.backend.epsilon()),null==e)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map(e=>e.name):Object.keys(e)).forEach((t,n)=>{const r=wa.registeredVariables[t],a=!1;null==this.accumulatedMeanSquares[n]&&(this.accumulatedMeanSquares[n]={originalName:`${t}/rms`,variable:Ba(()=>pi(r).variable(a))}),null==this.accumulatedMoments[n]&&(this.accumulatedMoments[n]={originalName:`${t}/momentum`,variable:Ba(()=>pi(r).variable(a))}),null==this.accumulatedMeanGrads[n]&&this.centered&&(this.accumulatedMeanGrads[n]={originalName:`${t}/mg`,variable:Ba(()=>pi(r).variable(a))});const s=Array.isArray(e)?e[n].tensor:e[t];if(null==s)return;const o=this.accumulatedMeanSquares[n].variable,i=this.accumulatedMoments[n].variable;Ba(()=>{const e=Ws(Gs(o,this.decay),Gs(Ai(s),1-this.decay));if(this.centered){const t=this.accumulatedMeanGrads[n].variable,a=Ws(Gs(t,this.decay),Gs(s,1-this.decay)),u=Us(Gs(s,this.learningRate),_i(uu(e,Ws(Ai(a),this.epsilon)))),l=Ws(Gs(i,this.momentum),u);o.assign(e),t.assign(a),i.assign(l);const c=uu(r,l);r.assign(c)}else{const e=Ws(Gs(o,this.decay),Gs(Ai(s),1-this.decay)),t=Ws(Gs(i,this.momentum),Us(Gs(s,this.learningRate),_i(Ws(e,this.epsilon))));o.assign(e),i.assign(t);const n=uu(r,t);r.assign(n)}})}),this.incrementIterations()}dispose(){null!=this.accumulatedMeanSquares&&Va(this.accumulatedMeanSquares.map(e=>e.variable)),null!=this.accumulatedMeanGrads&&this.centered&&Va(this.accumulatedMeanGrads.map(e=>e.variable)),null!=this.accumulatedMoments&&Va(this.accumulatedMoments.map(e=>e.variable))}async getWeights(){const e=[...this.accumulatedMeanSquares,...this.accumulatedMoments];return this.centered&&e.push(...this.accumulatedMeanGrads),[await this.saveIterations()].concat(e.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);const t=this.centered?e.length/3:e.length/2,n=!1;this.accumulatedMeanSquares=e.slice(0,t).map(e=>({originalName:e.name,variable:e.tensor.variable(n)})),this.accumulatedMoments=e.slice(t,2*t).map(e=>({originalName:e.name,variable:e.tensor.variable(n)})),this.centered&&(this.accumulatedMeanGrads=e.slice(2*t,3*t).map(e=>({originalName:e.name,variable:e.tensor.variable(n)})))}getConfig(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}}static fromConfig(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)}}const ep=[qd,Kd,Xd,Yd,Zd,Jd,Qd];function tp(e){return new Promise(e=>setTimeout(e)).then(e)}class np{constructor(e){if(!V().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(np.URL_SCHEME)&&(e=e.slice(np.URL_SCHEME.length)),null!=e&&0!==e.length||(e="model"),this.modelJsonFileName=e+".json",this.weightDataFileName=e+".weights.bin"}async save(e){if("undefined"===typeof document)throw new Error("Browser downloads are not supported in this environment since `document` is not present");const t=Pa.join(e.weightData),n=window.URL.createObjectURL(new Blob([t],{type:"application/octet-stream"}));if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");{const t=ns(e,[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}]),r=window.URL.createObjectURL(new Blob([JSON.stringify(t)],{type:"application/json"})),a=null==this.modelJsonAnchor?document.createElement("a"):this.modelJsonAnchor;if(a.download=this.modelJsonFileName,a.href=r,await tp(()=>a.dispatchEvent(new MouseEvent("click"))),null!=e.weightData){const e=null==this.weightDataAnchor?document.createElement("a"):this.weightDataAnchor;e.download=this.weightDataFileName,e.href=n,await tp(()=>e.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:ss(e)}}}}np.URL_SCHEME="downloads://";class rp{constructor(e){if(null==e||e.length<1)throw new Error(`When calling browserFiles, at least 1 file is required, but received ${e}`);this.jsonFile=e[0],this.weightsFiles=e.slice(1)}async load(){return new Promise((e,t)=>{const n=new FileReader;n.onload=n=>{const r=JSON.parse(n.target.result),a=r.modelTopology;if(null==a)return void t(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`));if(null==r.weightsManifest)return void t(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`));if(0===this.weightsFiles.length)return void e({modelTopology:a});const s=as(r,e=>this.loadWeights(e));e(s)},n.onerror=e=>t(`Failed to read model topology and weights manifest JSON from file '${this.jsonFile.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),n.readAsText(this.jsonFile)})}loadWeights(e){const t=[],n=[];for(const s of e)t.push(...s.weights),n.push(...s.paths);const r=this.checkManifestAndWeightFiles(e),a=n.map(e=>this.loadWeightsFile(e,r[e]));return Promise.all(a).then(e=>[t,e])}loadWeightsFile(e,t){return new Promise((n,r)=>{const a=new FileReader;a.onload=e=>{const t=e.target.result;n(t)},a.onerror=t=>r(`Failed to weights data from file of path '${e}'.`),a.readAsArrayBuffer(t)})}checkManifestAndWeightFiles(e){const t=[],n=this.weightsFiles.map(e=>ts(e.name)),r={};for(const a of e)a.paths.forEach(e=>{const a=ts(e);if(-1!==t.indexOf(a))throw new Error(`Duplicate file basename found in weights manifest: '${a}'`);if(t.push(a),-1===n.indexOf(a))throw new Error(`Weight file with basename '${a}' is not provided.`);r[e]=this.weightsFiles[n.indexOf(a)]});if(t.length!==this.weightsFiles.length)throw new Error(`Mismatch in the number of files in weights manifest (${t.length}) and the number of weight files provided (${this.weightsFiles.length}).`);return r}}function ap(e,t,n,r){var a,s,o;i(null!=(a=e)&&Array.isArray(a)&&a.length>0,()=>"promises must be a none empty array"),o=r=r??1,i((s=n=n??0)>=0&&s<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${s}`),i(o>=0&&o<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${o}`),i(o>=s,()=>`startFraction must be no more than endFraction, but got startFraction ${s} and endFraction ${o}`);let u=0;return Promise.all(e.map(a=>(a.then(a=>{const s=n+ ++u/e.length*(r-n);return t(s),a}),a)))}async function sp(e,t){null==t&&(t={});const n=null==t.fetchFunc?V().platform.fetch:t.fetchFunc,r=e.map(e=>n(e,t.requestInit,{isBinary:!0})),a=(null==t.onProgress?await Promise.all(r):await ap(r,t.onProgress,0,.5)).map(e=>e.arrayBuffer());return null==t.onProgress?await Promise.all(a):await ap(a,t.onProgress,.5,1)}function op(e){return async(t,n="",r)=>{const a=t.map(()=>!1),s={},o=null!=r?r.map(()=>!1):[],i=[];if(t.forEach((e,t)=>{let n=0;e.weights.forEach(e=>{const u="quantization"in e?e.quantization.dtype:e.dtype,l=Ma[u]*c(e.shape),d=()=>{a[t]=!0,null==s[t]&&(s[t]=[]),s[t].push({manifestEntry:e,groupOffset:n,sizeBytes:l})};null!=r?r.forEach((t,n)=>{t===e.name&&(d(),o[n]=!0)}):d(),i.push(e.name),n+=l})}),!o.every(e=>e)){const e=r.filter((e,t)=>!o[t]);throw new Error(`Could not find weights in manifest with names: ${e.join(", ")}. \nManifest JSON has weights with names: ${i.join(", ")}.`)}const u=a.reduce((e,t,n)=>(t&&e.push(n),e),[]),l=[];u.forEach(e=>{t[e].paths.forEach(e=>{const t=n+(n.endsWith("/")?"":"/")+e;l.push(t)})});const d=await e(l),p={};let h=0;return u.forEach(e=>{const n=t[e].paths.length,r=new Pa(d.slice(h,h+n));s[e].forEach(e=>{const t=ja(r.slice(e.groupOffset,e.groupOffset+e.sizeBytes),[e.manifestEntry]);for(const n in t)p[n]=t[n]}),h+=n}),p}}is.registerSaveRouter(e=>V().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(np.URL_SCHEME)?function(e="model"){return new np(e)}(e.slice(np.URL_SCHEME.length)):null);class ip{constructor(e,t){if(this.DEFAULT_METHOD="POST",null==t&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.weightUrlConverter=t.weightUrlConverter,null!=t.fetchFunc?(i("function"===typeof t.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=t.fetchFunc):this.fetch=V().platform.fetch,i(null!=e&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&i(2===e.length,()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`),this.path=e,null!=t.requestInit&&null!=t.requestInit.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{},this.loadOptions=t}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");const t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;const n=ns(e,[{paths:["./model.weights.bin"],weights:e.weightSpecs}]);if(t.body.append("model.json",new Blob([JSON.stringify(n)],{type:"application/json"}),"model.json"),null!=e.weightData){const n=Pa.join(e.weightData);t.body.append("model.weights.bin",new Blob([n],{type:"application/octet-stream"}),"model.weights.bin")}const r=await this.fetch(this.path,t);if(r.ok)return{modelArtifactsInfo:ss(e),responses:[r]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${r.status}.`)}async loadModelJSON(){const e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new Error(`Request to ${this.path} failed with status code ${e.status}. Please verify this URL points to the model JSON of the model to load.`);let t;try{t=await e.json()}catch(a){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=t.modelTopology,r=t.weightsManifest;if(null==n&&null==r)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);return t}async load(){if(this.loadOptions.streamWeights)return this.loadStream();return as(await this.loadModelJSON(),e=>this.loadWeights(e))}async loadStream(){const e=await this.loadModelJSON(),t=await this.getWeightUrls(e.weightsManifest),n=os(e.weightsManifest);return Object.assign(Object.assign({},e),{weightSpecs:n,getWeightStream:()=>function(e,t){var n;const r=null==t.fetchFunc?V().platform.fetch:t.fetchFunc;let a,s=0;return null===(n=t.onProgress)||void 0===n||n.call(t,0),new ReadableStream({pull:async n=>{for(var o;st?e.substring(n):"";return[r+"/",a]}(t),a=this.weightPathPrefix||n,s=[],o=[];for(const i of e)for(const e of i.paths)null!=this.weightUrlConverter?o.push(this.weightUrlConverter(e)):s.push(a+e+r);return this.weightUrlConverter&&s.push(...await Promise.all(o)),s}async loadWeights(e){const t=await this.getWeightUrls(e);return[os(e),await sp(t,this.loadOptions)]}}function up(e){return null!=e.match(ip.URL_SCHEME_REGEX)}ip.URL_SCHEME_REGEX=/^https?:\/\//;const lp=(e,t)=>{if("undefined"===typeof fetch&&(null==t||null==t.fetchFunc))return null;{let n=!0;if(n=Array.isArray(e)?e.every(e=>up(e)):up(e),n)return cp(e,t)}return null};function cp(e,t){return new ip(e,t)}is.registerSaveRouter(lp),is.registerLoadRouter(lp);class dp{constructor(e){this.modelArtifacts=e}load(){return this.modelArtifacts}}class pp{constructor(e){this.saveHandler=e}save(e){return this.saveHandler(e)}}class hp{constructor(e){e.load&&(this.load=()=>Promise.resolve(e.load())),e.save&&(this.save=t=>Promise.resolve(e.save(t)))}}function fp(e,t,n,r){if(1===arguments.length){return null!=e.modelTopology||null!=e.weightSpecs?new dp(e):(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 dp({modelTopology:e}))}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 dp({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:r})}const mp=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,CompositeArrayBuffer:Pa,browserFiles:function(e){return new rp(e)},browserHTTPRequest:function(e,t){return cp(e,t)},concatenateArrayBuffers:function(e){return Pa.join(e)},copyModel:async function(e,t){return As(e,t,!1)},decodeWeights:ja,decodeWeightsStream:Qa,encodeWeights:async function(e,t){const n=[],r=[],a=Array.isArray(e)?e.map(e=>e.name):Object.keys(e);for(let s=0;s{const t=await i.bytes(),n=t.reduce((e,t)=>e+t.length,0)+4*t.length,r=new Uint8Array(n);let a=0;for(let s=0;sis.getLoadHandlers(e,t),getModelArtifactsForJSON:as,getModelArtifactsForJSONSync:rs,getModelArtifactsInfoForJSON:ss,getSaveHandlers:e=>is.getSaveHandlers(e),getWeightSpecs:os,http:cp,isHTTPScheme:up,listModels:async function(){const e=Rs.getSchemes(),t={};for(const n of e){const e=await Rs.getManager(n).listModels();for(const r in e){t[n+Es+r]=e[r]}}return t},loadWeights:async function(e,t="",n,r){return op(e=>sp(e,{requestInit:r}))(e,t,n)},moveModel:async function(e,t){return As(e,t,!0)},registerLoadRouter:e=>is.registerLoadRouter(e),registerSaveRouter:e=>is.registerSaveRouter(e),removeModel:async function(e){const t=_s(e);return Rs.getManager(t.scheme).removeModel(t.path)},weightsLoaderFactory:op,withSaveHandler:function(e){return new pp(e)},withSaveHandlerSync:function(e){return new pp(e)}},Symbol.toStringTag,{value:"Module"}));let gp,yp=!1;async function bp(e,t){let n=Ea(e,"img","toPixels");if(!(e instanceof Yr)){const e=n;n=Ls(e,"int32"),e.dispose()}!function(e){if(2!==e.rank&&3!==e.rank)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${e.rank}.`);const t=2===e.rank?1:e.shape[2];if(t>4||2===t)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${t}`);if("float32"!==e.dtype&&"int32"!==e.dtype)throw new Error(`Unsupported type for toPixels: ${e.dtype}. Please use float32 or int32 tensors.`)}(n);const[r,a]=n.shape.slice(0,2),s=2===n.rank?1:n.shape[2],o=await n.data(),i="float32"===n.dtype?255:1,u=new Uint8ClampedArray(a*r*4);for(let l=0;l1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${t}.`)}else if("int32"===n.dtype&&(t<0||t>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${t}.`);1===s?(e[0]=t*i,e[1]=t*i,e[2]=t*i):e[r]=t*i}const t=4*l;u[t+0]=Math.round(e[0]),u[t+1]=Math.round(e[1]),u[t+2]=Math.round(e[2]),u[t+3]=Math.round(e[3])}if(null!=t){if(!yp){null!=or(Ve,wa.backendName)&&(console.warn("tf.browser.toPixels is not efficient to draw tensor on canvas. Please try tf.browser.draw instead."),yp=!0)}t.width=a,t.height=r;const e=t.getContext("2d"),n=new ImageData(u,a,r);e.putImageData(n,0,0)}return n!==e&&n.dispose(),u}const xp=/* @__PURE__ */Aa({fromPixels_:function(e,t=3){if(t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(null==e)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let n=!1,r=!1,a=!1,s=!1,o=!1,i=!1;if(e.data instanceof Uint8Array)n=!0;else if("undefined"!==typeof ImageData&&e instanceof ImageData)r=!0;else if("undefined"!==typeof HTMLVideoElement&&e instanceof HTMLVideoElement)a=!0;else if("undefined"!==typeof HTMLImageElement&&e instanceof HTMLImageElement)s=!0;else if(null!=e.getContext)o=!0;else{if(!("undefined"!==typeof ImageBitmap&&e instanceof ImageBitmap))throw new Error(`pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was ${e.constructor.name}`);i=!0}if(null!=or(Zn,wa.backendName)){const n={pixels:e},r={numChannels:t};return wa.runKernel(Zn,n,r)}const[u,l]=a?[e.videoWidth,e.videoHeight]:[e.width,e.height];let c,d;if(o)c=e.getContext("2d").getImageData(0,0,u,l).data;else if(r||n)c=e.data;else if(s||a||i){if(null==gp)if("undefined"===typeof document){if("undefined"===typeof OffscreenCanvas||"undefined"===typeof OffscreenCanvasRenderingContext2D)throw new Error("Cannot parse input in current context. Reason: OffscreenCanvas Context2D rendering is not supported.");gp=new OffscreenCanvas(1,1).getContext("2d")}else gp=document.createElement("canvas").getContext("2d",{willReadFrequently:!0});gp.canvas.width=u,gp.canvas.height=l,gp.drawImage(e,0,0,u,l),c=gp.getImageData(0,0,u,l).data}if(4===t)d=new Int32Array(c);else{const e=u*l;d=new Int32Array(e*t);for(let n=0;nn)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[r-1]} vs. ${n}`);if(0===c(e.shape))throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);const a=t.shape,s=a[a.length-1];let o=1;for(let c=0;ce/l),1].slice(0,s);return[u,o,l,d]}function wp(e,t,n){const r=e.shape.length;i(r===t.length,()=>`Error in slice${r}D: Length of begin ${t} must match the rank of the array (${r}).`),i(r===n.length,()=>`Error in slice${r}D: Length of size ${n} must match the rank of the array (${r}).`);for(let a=0;a`Error in slice${r}D: begin[${a}] + size[${a}] (${t[a]+n[a]}) would overflow input.shape[${a}] (${e.shape[a]})`)}function kp(e,t,n){const r=[];for(let a=0;a1){r=a;break}for(let a=r+1;a0||n[a]!==e[a])return!1;return!0}function Np(e,t){let n=e.length>0?e[e.length-1]:1;for(let r=0;r{i(-1!==e,()=>"slice() does not support negative begin indexing.")}),s=null==n?new Array(a).fill(-1):"number"===typeof n?[n,...new Array(a-1).fill(-1)]:n.lengtht>=0?t:(i(-1===t,()=>`Negative size values should be exactly -1 but got ${t} for the slice() size at index ${n}.`),e.shape[n]-r[n])),[r,s]}function Tp(e,t,n,r,a,s,o,i,u){let l;if(null==r?(l=new Array(t.length),l.fill(1)):l=r,null!=o&&0!==(o&o-1))throw new Error("Multiple ellipses in slice is not allowed.");let c=!1;const d={dims:l.length,numAddAxisAfterEllipsis:0,begin:t.slice(),end:n.slice(),strides:l.slice(),beginMask:a,endMask:s,ellipsisMask:o,newAxisMask:i,shrinkAxisMask:u};for(let b=0;b0?0:-1,p.strides[b]>0?n:n-1];if(t&&p.strides[b]<=0)throw Error("only stride 1 allowed on non-range indexing.");m=m&&1===p.strides[b];const s=!!(p.beginMask&1<=n)throw Error(`slice index ${p.begin[b]} of dimension ${b} out of bounds.`)}else p.begin[b]=Cp(p.begin[b],0,p.strides[b],n,r,a),p.end[b]=Cp(p.end[b],1,p.strides[b],n,r,a);const e=1===p.strides[b]&&0===p.begin[b]&&p.end[b]===n;h=h&&e,f=f&&(0===b&&1===p.strides[b]||e)}else h=h&&1===p.strides[b]&&s,f=f&&(0===b&&1===p.strides[b]||s);let o,i=!1;if(p.beginValid&&p.endValid?(o=p.end[b]-p.begin[b],i=!0):t?(o=1,i=!0):s&&n>=0&&(o=p.strides[b]<0?-n:n,i=!0),i){let e;e=0===o||o<0!==p.strides[b]<0?0:Math.trunc(o/p.strides[b])+(o%p.strides[b]!==0?1:0),g.push(e)}else g.push(-1)}for(let b=0;b=0?y.push(g[e]):-2===e&&y.push(1)}return{finalShapeSparse:y.filter((e,t)=>-2!==p.finalShapeGatherIndices[t]),finalShape:y,isIdentity:h,sliceDim0:f,isSimpleSlice:m,begin:p.begin,end:p.end,strides:p.strides}}function Cp(e,t,n,r,a,s){if(a[t])return n>0?s[t]:s[t+1&1];{const t=e<0?r+e:e;return ts[1]?s[1]:t}}const $p="undefined"!==typeof requestAnimationFrame?requestAnimationFrame:"undefined"!==typeof setImmediate?setImmediate:e=>e();function Ep(){return new Promise(e=>$p(()=>e()))}function Rp(e,t){const n=e[0].length;e.forEach((e,t)=>{i(e.length===n,()=>`Error in concat${n}D: rank of tensors[${t}] must be the same as the rank of the rest (${n})`)}),i(t>=0&&t`Error in concat${n}D: axis must be between 0 and ${n-1}.`);const r=e[0];e.forEach((e,a)=>{for(let s=0;s`Error in concat${n}D: Shape of tensors[${a}] (${e}) does not match the shape of the rest (${r}) along the non-concatenated axis ${a}.`)})}function _p(e,t){const n=e[0].slice();for(let r=1;r=0)if(i>=0){if(i!==s)throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.shape[${a+e}] = ${s} but shape[${a+e}] = ${i}`)}else r[o]=s}return r}function Dp(e){const t={FIRST_DIM_SIZE:Ap.FIRST_DIM_SIZE,VALUE_ROWIDS:Ap.VALUE_ROWIDS,ROW_LENGTHS:Ap.ROW_LENGTHS,ROW_SPLITS:Ap.ROW_SPLITS,ROW_LIMITS:Ap.ROW_LIMITS,ROW_STARTS:Ap.ROW_STARTS},n=[];for(const r of e){if(!(r in t))break;n.push(t[r])}return n}function Mp(e){return 0===e.length?0:e[0]===Ap.FIRST_DIM_SIZE?e.length-1:e.length}function Pp(e,t){if(null==e||null==t)return;const n=e.length,r=t.length;if(n>=r)throw new Error(`defaultValue.shape=${e} and ragged tensor flatValues.shape=${t}, are incompatible: defaultValue.rank = ${n} must be less than ragged tensor input flatValues.rank = ${r})`);for(let a=0;a=0&&r>=0&&1!==n&&n!==r)throw new Error(`defaultValue.shape=${e}, and ragged tensor input flatValues.shape=${t} are incompatible: defaultValue.shape[${a-e.length}] = ${n} but ragged tensor input.flatValues.shape[${a-e.length}] = ${r}`)}}(Op=Ap||(Ap={}))[Op.FIRST_DIM_SIZE=0]="FIRST_DIM_SIZE",Op[Op.VALUE_ROWIDS=1]="VALUE_ROWIDS",Op[Op.ROW_LENGTHS=2]="ROW_LENGTHS",Op[Op.ROW_SPLITS=3]="ROW_SPLITS",Op[Op.ROW_LIMITS=4]="ROW_LIMITS",Op[Op.ROW_STARTS=5]="ROW_STARTS";function Lp(e){return e<=30?e:T(e,Math.floor(Math.sqrt(e)))}function Bp(e,t,n){return[n*("number"===typeof e?e:e[0]),t*("number"===typeof e?e:e[1])]}function Vp(e,t,n,r=!0){let a=[];if(r)a=a.concat(t.slice(0)),a.push(e[0]/n),a=a.concat(e.slice(1));else{a=a.concat(e[0]);const n=t.length;for(let r=0;r=2*t+1||r%2===1?a.push(r):n.push(r);r.push(...n),r.push(0),r.push(...a)}return r}function zp(e,t,n,r=!0){const a=[];r?a.push(e[0]/n):a.push(e[0]*n);for(let s=1;s/g;function lh(e,t){const n=((e=e.replace(/\s/g,"")).length-e.replace(uh,"").length)/2;if(n<1)throw new Error("Equations without an arrow are not supported.");if(n>1)throw new Error(`Equation must contain exactly one arrow ("${ih}").`);const[r,a]=e.split(ih);i(-1===r.indexOf("..."),()=>'The ellipsis notation ("...") is not supported yet.');const s=r.split(","),o=s.length;if(t!==o)throw new Error(`Expected ${o} input tensors, received ${t}`);if(o>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");const u=[];for(let i=0;i-1!==t.indexOf(e)))throw new Error(`Output subscripts contain the label ${e} not present in the input subscripts.`);-1===u.indexOf(e)&&u.push(e)}for(let i=0;i-1!==e),{permutationIndices:n,expandDims:r}}function dh(e,t,n){const r=new Array(e);for(let a=0;a`Expected dimension ${r[t[a][n]]} at axis ${n} of input shaped ${JSON.stringify(e)}, but got dimension ${e[n]}`)}}function ph(e,t){const n=e,r=[];let a=0;0===e.length&&n.push(-1),a=e.length+1;for(let o=0;oe===t)}function fh(e,t){const n=[];for(let r=0;r"Number of splits must evenly divide the axis."),r=new Array(t).fill(e.shape[n]/t);else{i(t.reduce((e,t)=>(-1===t&&(e+=1),e),0)<=1,()=>"There should be only one negative value in split array.");const a=t.indexOf(-1);if(-1!==a){const r=t.reduce((e,t)=>t>0?e+t:e);t[a]=e.shape[n]-r}i(e.shape[n]===t.reduce((e,t)=>e+t),()=>"The sum of sizes must match the size of the axis dimension."),r=t}return r}function gh(e){return`Received SparseTensor with denseShape[0] = 0 but\n indices.shape[0] = ${e}`}function yh(e,t){return`indices(${e}, 0) is invalid: ${t} < 0`}function bh(e,t,n){return`indices(${e}, 0) is invalid: ${t} >= ${n}`}function xh(e,t){return`only one output dimension may be -1, not both ${e} and ${t}`}function vh(e,t){return`size ${e} must be non-negative, not ${t}`}function wh(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function kh(e,t){return`Input to reshape is a SparseTensor with ${c(e)}\n dense values, but the requested shape requires a multiple of ${c(t)}. inputShape=${e} outputShape= ${t}`}function Ih(e,t){return`Input to reshape is a tensor with ${c(e)} dense values, but the requested shape has ${c(t)}. inputShape=${e} outputShape=${t}`}function Nh(){return"segment ids must be >= 0"}function Sh(){return"segment ids are not increasing"}function Th(e,t){return`Segment id ${e} out of range [0, ${t}), possibly because segmentIds input is not sorted.`}function Ch(e,t,n){return`Bad: indices[${e}] == ${t} out of range [0, ${n})`}function $h(e,t,n,r){const a=t.shape.length,s=e.shape.length;if(0!==r&&(r<-a||r>a))throw new Error(`Expect batchDims in the range of [-${a}, ${a}], but got ${r}`);if(r<0&&(r+=a),r>s)throw new Error(`batchDims (${r}) must be less than rank(x) (\n ${s}).`);if(nMr(e))}catch(fO){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${fO}`)}}function Rh(e){return e.map(e=>Dr(e))}const _h=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,ERF_A1:Kp,ERF_A2:Xp,ERF_A3:Yp,ERF_A4:Qp,ERF_A5:Zp,ERF_P:qp,PARALLELIZE_THRESHOLD:30,get RowPartitionType(){return Ap},SELU_SCALE:jp,SELU_SCALEALPHA:Hp,applyActivation:Mc,assertAndGetBroadcastShape:li,assertAxesAreInnerMostDims:Ii,assertParamsConsistent:Rp,assignToTypedArray:ah,axesAreInnerMostDims:xi,calculateShapes:pc,checkEinsumDimSizes:dh,checkPadOnDimRoundingMode:xo,combineLocations:vi,combineRaggedTensorToTensorShapes:Fp,complexWithEvenIndex:th,complexWithOddIndex:nh,computeConv2DInfo:io,computeConv3DInfo:uo,computeDefaultPad:lo,computeDilation2DInfo:ao,computeOptimalWindowSize:Lp,computeOutAndReduceShapes:wi,computeOutShape:_p,computePool2DInfo:so,computePool3DInfo:oo,convertConv2DDataFormat:bo,decodeEinsumEquation:lh,eitherStridesOrDilationsAreOne:go,expandShapeToKeepDim:ki,exponent:oh,exponents:sh,fromStringArrayToUint8:Rh,fromUint8ToStringArray:Eh,getAxesPermutation:Ni,getBroadcastDims:ii,getComplexWithIndex:rh,getEinsumComputePath:ph,getEinsumPermutation:ch,getFusedBiasGradient:Dc,getFusedDyActivation:Fc,getImageCenter:Bp,getInnerMostAxes:Ti,getPermuted:Wp,getRaggedRank:Mp,getReductionAxes:ui,getReshaped:Vp,getReshapedPermuted:zp,getRowPartitionTypesHelper:Dp,getSliceBeginCoords:Up,getSliceSize:Gp,getSparseFillEmptyRowsIndicesDenseShapeMismatch:gh,getSparseFillEmptyRowsNegativeIndexErrorMessage:yh,getSparseFillEmptyRowsOutOfRangeIndexErrorMessage:bh,getSparseReshapeEmptyTensorZeroOutputDimErrorMessage:wh,getSparseReshapeInputOutputMismatchErrorMessage:Ih,getSparseReshapeInputOutputMultipleErrorMessage:kh,getSparseReshapeMultipleNegativeOneOutputDimErrorMessage:xh,getSparseReshapeNegativeOutputDimErrorMessage:vh,getSparseSegmentReductionIndicesOutOfRangeErrorMessage:Ch,getSparseSegmentReductionNegativeSegmentIdsErrorMessage:Nh,getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage:Sh,getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage:Th,getUndoAxesPermutation:Si,isIdentityPermutation:hh,mergeRealAndImagArrays:Jp,prepareAndValidate:vp,prepareSplitSize:mh,shouldFuse:Pc,splitRealAndImagArrays:eh,stridesOrDilationsArePositive:yo,tupleValuesAreOne:mo,upcastType:ca,validateDefaultValueShape:Pp,validateInput:dc,validateUpdateShape:cc,warn:rr},Symbol.toStringTag,{value:"Module"}));!function(){for(const e of ep)Hd(e)}();const Ah=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,Abs:H,Acos:j,Acosh:q,AdadeltaOptimizer:qd,AdagradOptimizer:Kd,AdamOptimizer:Xd,AdamaxOptimizer:Yd,Add:K,AddN:X,All:Y,Any:Q,ArgMax:Z,ArgMin:J,Asin:ee,Asinh:te,Atan:ne,Atan2:ae,Atanh:re,AvgPool:se,AvgPool3D:ie,AvgPool3DGrad:ue,AvgPoolGrad:oe,BatchMatMul:le,BatchToSpaceND:ce,Bincount:de,BitwiseAnd:pe,BroadcastArgs:he,Cast:fe,Ceil:me,ClipByValue:ge,Complex:ye,ComplexAbs:be,Concat:xe,Conv2D:ve,Conv2DBackpropFilter:we,Conv2DBackpropInput:ke,Conv3D:Ie,Conv3DBackpropFilterV2:Ne,Conv3DBackpropInputV2:Se,Cos:Te,Cosh:Ce,CropAndResize:Re,Cumprod:$e,Cumsum:Ee,DataStorage:t,DenseBincount:_e,DepthToSpace:Ae,DepthwiseConv2dNative:Oe,DepthwiseConv2dNativeBackpropFilter:Fe,DepthwiseConv2dNativeBackpropInput:De,Diag:Me,Dilation2D:Pe,Dilation2DBackpropFilter:Be,Dilation2DBackpropInput:Le,Draw:Ve,get ENV(){return z},Einsum:ze,Elu:Ue,EluGrad:Ge,Environment:L,Equal:je,Erf:He,Exp:qe,ExpandDims:Ke,Expm1:Xe,FFT:Ye,Fill:Qe,FlipLeftRight:Ze,Floor:Je,FloorDiv:et,FromPixels:Zn,FusedBatchNorm:tt,FusedConv2D:tr,FusedDepthwiseConv2D:nr,GatherNd:rt,GatherV2:nt,Greater:at,GreaterEqual:st,IFFT:it,Identity:ot,Imag:ut,IsFinite:lt,IsInf:ct,IsNan:dt,KernelBackend:n,LRN:wt,LRNGrad:kt,LeakyRelu:pt,Less:ht,LessEqual:ft,LinSpace:mt,Log:gt,Log1p:yt,LogicalAnd:bt,LogicalNot:xt,LogicalOr:vt,Max:It,MaxPool:St,MaxPool3D:Ct,MaxPool3DGrad:$t,MaxPoolGrad:Tt,MaxPoolWithArgmax:Et,Maximum:Nt,Mean:Rt,Min:_t,Minimum:At,MirrorPad:Ot,Mod:Ft,MomentumOptimizer:Zd,Multinomial:Dt,Multiply:Mt,Neg:Pt,NonMaxSuppressionV3:Bt,NonMaxSuppressionV4:Vt,NonMaxSuppressionV5:Wt,NotEqual:Lt,OP_SCOPE_SUFFIX:_a,OneHot:Ut,OnesLike:zt,Optimizer:jd,Pack:Gt,PadV2:Ht,Pow:jt,Prelu:qt,Prod:Kt,RMSPropOptimizer:Jd,RaggedGather:Xt,RaggedRange:Yt,RaggedTensorToTensor:Qt,Range:Zt,get Rank(){return Jr},Real:Jt,RealDiv:We,Reciprocal:en,get Reduction(){return Id},Relu:tn,Relu6:un,Reshape:nn,ResizeBilinear:sn,ResizeBilinearGrad:on,ResizeNearestNeighbor:rn,ResizeNearestNeighborGrad:an,Reverse:ln,RotateWithOffset:Jn,Round:cn,Rsqrt:dn,SGDOptimizer:Qd,ScatterNd:pn,SearchSorted:fn,Select:mn,Selu:gn,Sigmoid:wn,Sign:vn,Sin:bn,Sinh:xn,Slice:yn,Softmax:Cn,Softplus:kn,SpaceToBatchND:Sn,SparseFillEmptyRows:$n,SparseReshape:En,SparseSegmentMean:Rn,SparseSegmentSum:_n,SparseToDense:An,SplitV:Tn,Sqrt:In,Square:Fn,SquaredDifference:On,StaticRegexReplace:Dn,Step:Qn,StridedSlice:Mn,StringNGrams:Pn,StringSplit:Ln,StringToHashBucketFast:Bn,Sub:Vn,Sum:Nn,Tan:Wn,Tanh:zn,Tensor:Yr,TensorBuffer:qr,TensorScatterUpdate:hn,Tile:Un,TopK:Gn,Transform:Hn,Transpose:jn,Unique:qn,Unpack:Kn,UnsortedSegmentSum:Xn,Variable:Zr,ZerosLike:Yn,_FusedMatMul:er,abs:Hs,acos:js,acosh:qs,add:Ws,addN:Ks,all:Xs,any:Ys,argMax:Qs,argMin:Zs,asin:Js,asinh:eo,atan:to,atan2:no,atanh:ro,avgPool:wo,avgPool3d:ko,backend:Ha,backend_util:_h,basicLSTMCell:$o,batchNorm:Ro,batchNorm2d:_o,batchNorm3d:Ao,batchNorm4d:Oo,batchToSpaceND:Eo,bincount:Fo,bitwiseAnd:Do,booleanMaskAsync:Ic,broadcastArgs:Mo,broadcastTo:Po,buffer:Ps,cast:Ls,ceil:Lo,clipByValue:Vo,clone:Bs,complex:Oa,concat:Io,concat1d:Wo,concat2d:zo,concat3d:Uo,concat4d:Go,conv1d:jo,conv2d:Ho,conv2dTranspose:Ko,conv3d:Xo,conv3dTranspose:Qo,cos:Zo,cosh:Jo,cosineWindow:_c,cumprod:ei,cumsum:ti,customGrad:au,denseBincount:ni,depthToSpace:ri,depthwiseConv2d:ai,diag:si,dilation2d:oi,dispose:Va,div:Us,divNoNan:hi,dot:fi,dropout:Ec,einsum:mi,elu:gi,enclosingPowerOfTwo:Rc,engine:La,ensureShape:yi,env:V,equal:ci,erf:bi,euclideanNorm:Mi,exp:Pi,expandDims:Li,expm1:Bi,eye:Wi,fft:ql,fill:Bo,floor:zi,floorDiv:zs,fused:Uc,gather:Ui,gatherND:$c,getBackend:Ua,getGradient:ir,getKernel:or,getKernelsForBackend:ur,greater:Gi,greaterEqual:Hi,ifft:Kl,imag:ji,image:Md,inTopKAsync:Ac,io:mp,irfft:Xl,isFinite:qi,isInf:Ki,isNaN:Xi,keep:Wa,leakyRelu:Yi,less:Qi,lessEqual:Zi,linalg:Pd,linspace:Ji,localResponseNormalization:eu,log:tu,log1p:nu,logSigmoid:iu,logSoftmax:lu,logSumExp:cu,logicalAnd:du,logicalNot:pu,logicalOr:hu,logicalXor:fu,losses:Ld,lowerBound:yu,matMul:No,max:Ci,maxPool:bu,maxPool3d:xu,maxPoolWithArgmax:vu,maximum:wu,mean:ku,meshgrid:Su,min:$i,minimum:Tu,mirrorPad:Cu,mod:$u,moments:Eu,movingAverage:Sc,mul:Gs,multiRNNCell:Ru,multinomial:_u,neg:su,nextFrame:Ep,norm:Di,notEqual:Au,oneHot:Ou,ones:Nu,onesLike:Fu,op:Aa,outerProduct:Du,pad:Mu,pad1d:Pu,pad2d:Lu,pad3d:Bu,pad4d:Vu,pool:zu,pow:Ei,prelu:Uu,print:Vs,prod:Gu,raggedGather:Hu,raggedRange:ju,raggedTensorToTensor:qu,rand:Ku,randomGamma:xl,randomNormal:vl,randomStandardNormal:wl,randomUniform:kl,randomUniformInt:Il,range:Nl,real:Sl,reciprocal:Tl,registerBackend:Ga,registerKernel:lr,relu:Cl,relu6:$l,reshape:vo,reverse:El,reverse1d:Rl,reverse2d:_l,reverse3d:Al,reverse4d:Ol,rfft:Ql,round:Fl,rsqrt:Dl,scalar:Ri,scatterND:Tc,searchSorted:gu,selu:Ml,separableConv2d:Pl,setBackend:za,setdiff1dAsync:Ll,sigmoid:So,sign:Bl,signal:Dd,sin:Vl,sinh:Wl,slice:To,slice1d:zl,slice2d:Ul,slice3d:Gl,slice4d:Hl,softmax:jl,softplus:ou,spaceToBatchND:Wu,sparse:Bd,sparseToDense:Cc,spectral:Fd,split:Yl,sqrt:_i,square:Ai,squaredDifference:Zl,squeeze:Jl,stack:ec,step:tc,stridedSlice:nc,string:Vd,sub:uu,sum:Oi,sumOutType:da,tan:rc,tanh:Co,tensor:Da,tensor1d:ac,tensor2d:sc,tensor3d:oc,tensor4d:ic,tensor5d:uc,tensor6d:lc,tensorScatterUpdate:hc,tidy:Ba,tile:Vi,topk:fc,transpose:Nc,truncatedNormal:mc,unique:gc,unsortedSegmentSum:yc,unstack:bc,upcastType:ca,upperBound:xc,variable:vc,variableGrads:ru,where:di,whereAsync:kc,zeros:Iu,zerosLike:pi},Symbol.toStringTag,{value:"Module"}));var Oh,Fh,Dh;V().registerFlag("KEEP_INTERMEDIATE_TENSORS",()=>!1,e=>{e&&console.warn("Keep intermediate tensors is ON. This will print the values of all intermediate tensors during model inference. Not all models support this mode. For details, check e2e/benchmarks/ model_config.js. This significantly impacts performance.")}),(Fh=Oh||(Oh={}))[Fh.DT_INVALID=0]="DT_INVALID",Fh[Fh.DT_FLOAT=1]="DT_FLOAT",Fh[Fh.DT_DOUBLE=2]="DT_DOUBLE",Fh[Fh.DT_INT32=3]="DT_INT32",Fh[Fh.DT_UINT8=4]="DT_UINT8",Fh[Fh.DT_INT16=5]="DT_INT16",Fh[Fh.DT_INT8=6]="DT_INT8",Fh[Fh.DT_STRING=7]="DT_STRING",Fh[Fh.DT_COMPLEX64=8]="DT_COMPLEX64",Fh[Fh.DT_INT64=9]="DT_INT64",Fh[Fh.DT_BOOL=10]="DT_BOOL",Fh[Fh.DT_QINT8=11]="DT_QINT8",Fh[Fh.DT_QUINT8=12]="DT_QUINT8",Fh[Fh.DT_QINT32=13]="DT_QINT32",Fh[Fh.DT_BFLOAT16=14]="DT_BFLOAT16",Fh[Fh.DT_QINT16=15]="DT_QINT16",Fh[Fh.DT_QUINT16=16]="DT_QUINT16",Fh[Fh.DT_UINT16=17]="DT_UINT16",Fh[Fh.DT_COMPLEX128=18]="DT_COMPLEX128",Fh[Fh.DT_HALF=19]="DT_HALF",Fh[Fh.DT_RESOURCE=20]="DT_RESOURCE",Fh[Fh.DT_VARIANT=21]="DT_VARIANT",Fh[Fh.DT_UINT32=22]="DT_UINT32",Fh[Fh.DT_UINT64=23]="DT_UINT64",Fh[Fh.DT_FLOAT_REF=101]="DT_FLOAT_REF",Fh[Fh.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",Fh[Fh.DT_INT32_REF=103]="DT_INT32_REF",Fh[Fh.DT_UINT8_REF=104]="DT_UINT8_REF",Fh[Fh.DT_INT16_REF=105]="DT_INT16_REF",Fh[Fh.DT_INT8_REF=106]="DT_INT8_REF",Fh[Fh.DT_STRING_REF=107]="DT_STRING_REF",Fh[Fh.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",Fh[Fh.DT_INT64_REF=109]="DT_INT64_REF",Fh[Fh.DT_BOOL_REF=110]="DT_BOOL_REF",Fh[Fh.DT_QINT8_REF=111]="DT_QINT8_REF",Fh[Fh.DT_QUINT8_REF=112]="DT_QUINT8_REF",Fh[Fh.DT_QINT32_REF=113]="DT_QINT32_REF",Fh[Fh.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF",Fh[Fh.DT_QINT16_REF=115]="DT_QINT16_REF",Fh[Fh.DT_QUINT16_REF=116]="DT_QUINT16_REF",Fh[Fh.DT_UINT16_REF=117]="DT_UINT16_REF",Fh[Fh.DT_COMPLEX128_REF=118]="DT_COMPLEX128_REF",Fh[Fh.DT_HALF_REF=119]="DT_HALF_REF",Fh[Fh.DT_RESOURCE_REF=120]="DT_RESOURCE_REF",Fh[Fh.DT_VARIANT_REF=121]="DT_VARIANT_REF",Fh[Fh.DT_UINT32_REF=122]="DT_UINT32_REF",Fh[Fh.DT_UINT64_REF=123]="DT_UINT64_REF",function(e){var t;(t=e.CheckpointFormatVersion||(e.CheckpointFormatVersion={}))[t.LEGACY=0]="LEGACY",t[t.V1=1]="V1",t[t.V2=2]="V2"}(Dh||(Dh={}));const Mh={};function Ph(e){return Mh[e]}function Lh(e,t,n,r,a){const s=t.inputParams[e];if(s&&void 0!==s.inputIndexStart){const e=s.inputIndexStart,o=0===s.inputIndexEnd?void 0:void 0===s.inputIndexEnd?e+1:s.inputIndexEnd,i=e<0?t.inputNames.length+e:e;if("tensor"===s.type)return Bh(t.inputNames[i],n,r,a);if("tensors"===s.type){const s=t.inputs.slice(e,o);return t.inputNames.slice(e,o).filter((e,t)=>{var n;return"NoOp"!==(null===(n=s[t])||void 0===n?void 0:n.op)}).map(e=>Bh(e,n,r,a))}const u=Bh(t.inputNames[i],n,r,a),l=u.dataSync();return"number"===s.type?l[0]:E(u.shape,l)}const o=t.attrParams[e];return o&&o.value}function Bh(e,t,n,r){const[a,s]=Uh(e,n);if(null!=r){const e=r.getHashTableHandleByName(a);if(null!=e)return e}const o=n.currentContextIds.find(e=>!!t[zh(a,e)]);return void 0!==o?t[zh(a,o)][s]:void 0}function Vh(e,t,n){return t[zh(e,n.currentContextId)]}function Wh(e,t){const[n,r,a]=Uh(e,t);return[zh(n,t&&t.currentContextId),r,a]}function zh(e,t){return t?`${e}-${t}`:e}function Uh(e,t){if(""===e)return["",0,void 0];const n=null!=t&&null!=t.parseNodeNameCache;if(n){const n=t.parseNodeNameCache.get(e);if(null!=n)return n}const r=e.split(":");let a;if(1===r.length)a=[e,0,void 0];else{const e=r[0],t=3===r.length?r[1]:void 0;a=[e,Number(r[r.length-1]),t]}return n&&t.parseNodeNameCache.set(e,a),a}function Gh(e,t,n){let r=Lh("pad",e,t,n);if("explicit"===r){r=Lh("explicitPaddings",e,t,n);const a=[[0,0],[0,0],[0,0],[0,0]];for(let e=0;e<4;e++)a[e][0]=r[2*e],a[e][1]=r[2*e+1];return a}return r}function Hh(e){return e.kept?e:Bs(e)}const jh=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"Add",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddV2",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddN",category:"arithmetic",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"BiasAdd",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"Sub",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"RealDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Div",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"DivNoNan",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mul",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Maximum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Minimum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Pow",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SquaredDifference",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorMod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]},Symbol.toStringTag,{value:"Module"})),qh=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"Abs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan2",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ceil",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ClipByValue",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"clipValueMin",type:"number"},{start:2,name:"clipValueMax",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Complex",category:"basic_math",inputs:[{start:0,name:"real",type:"tensor"},{start:1,name:"imag",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ComplexAbs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Elu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Exp",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Floor",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Imag",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Neg",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Real",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Prelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"alpha",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu6",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Selu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sigmoid",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Rsqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Square",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sign",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Round",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Expm1",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log1p",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Reciprocal",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Softplus",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Erf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LeakyRelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"alpha",name:"alpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsNan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsFinite",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsInf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]},Symbol.toStringTag,{value:"Module"})),Kh=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"EmptyTensorList",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"maxNumElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"LoopCond",category:"control",inputs:[{start:0,name:"pred",type:"tensor"}]},{tfOpName:"Switch",category:"control",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"pred",type:"tensor"}]},{tfOpName:"Merge",category:"control",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"Enter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"frame_name",name:"frameName",type:"string"},{tfName:"is_constant",name:"isConstant",type:"bool"}]},{tfOpName:"Exit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NextIteration",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayV3",category:"control",inputs:[{start:0,name:"size",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"dynamic_size",name:"dynamicSize",type:"bool"},{tfName:"clear_after_read",name:"clearAfterRead",type:"bool"},{tfName:"identical_element_shapes",name:"identicalElementShapes",type:"bool"},{tfName:"tensor_array_name",name:"name",type:"string"}]},{tfOpName:"TensorArrayWriteV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayReadV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayGatherV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"}]},{tfOpName:"TensorArrayScatterV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArrayConcatV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape_except0",name:"elementShapeExcept0",type:"shape",notSupported:!0}]},{tfOpName:"TensorArraySplitV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"tensor",type:"tensor"},{start:2,name:"lengths",type:"number[]"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArraySizeV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}]},{tfOpName:"TensorArrayCloseV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"}]},{tfOpName:"StatelessIf",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"If",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"StatelessWhile",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"While",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"TensorListScatter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListScatterV2",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"},{start:3,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGather",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListSetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListReserve",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListFromTensor",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListStack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"},{tfName:"num_elements",name:"numElements",type:"dtype"}]},{tfOpName:"TensorListSplit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"},{start:2,name:"lengths",type:"number[]"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcat",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcatV2",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPopBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPushBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListLength",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}]},{tfOpName:"TensorListResize",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"size",type:"number"}]}]},Symbol.toStringTag,{value:"Module"})),Xh=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"AvgPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[],notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPoolWithArgmax",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"include_batch_in_index",name:"includeBatchInIndex",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AvgPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Conv1D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"stride",name:"stride",type:"number"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NWC"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"dilation",name:"dilation",type:"number",defaultValue:1}]},{tfOpName:"Conv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"useCudnnOnGpu",name:"useCudnnOnGpu",type:"bool"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"_FusedConv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"use_cudnn_on_gpu",name:"useCudnnOnGpu",type:"bool",defaultValue:!0},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number",defaultValue:.2}]},{tfOpName:"Conv2DBackpropInput",category:"convolution",inputs:[{start:2,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:0,name:"outputShape",type:"number[]"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]",notSupported:!0}]},{tfOpName:"DepthwiseConv2d",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"DepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"FusedDepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]}]},{tfOpName:"Conv3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"Dilation2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"rates",name:"dilations",type:"number[]"},{tfName:"padding",name:"pad",type:"string"}]}]},Symbol.toStringTag,{value:"Module"})),Yh=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"Fill",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"},{start:1,name:"value",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"LinSpace",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"num",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"OneHot",category:"creation",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"depth",type:"number"},{start:2,name:"onValue",type:"number",defaultValue:1},{start:3,name:"offValue",type:"number",defaultValue:0}],attrs:[{tfName:"axis",name:"axis",type:"number",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Ones",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"OnesLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"RandomStandardNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"RandomUniform",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number",defaultValue:0},{tfName:"maxval",name:"maxval",type:"number",defaultValue:1},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"RandomUniformInt",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number"},{tfName:"maxval",name:"maxval",type:"number"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Range",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"step",type:"number",defaultValue:0}],attrs:[{tfName:"Tidx",name:"dtype",type:"dtype"}]},{tfOpName:"TruncatedNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"means",name:"mean",type:"number",defaultValue:0},{tfName:"stddev",name:"stdDev",type:"number",defaultValue:1},{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Zeros",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"ZerosLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Multinomial",category:"creation",inputs:[{start:0,name:"logits",type:"tensor"},{start:1,name:"numSamples",type:"number"}],attrs:[{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number"},{tfName:"T",name:"dtype",type:"dtype"},{tfName:"output_dtype",name:"output_dtype",type:"dtype"}]}]},Symbol.toStringTag,{value:"Module"})),Qh=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"NonMaxSuppressionV2",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV3",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV4",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"T_threshold",name:"threshold",type:"dtype",notSupported:!0},{tfName:"pad_to_max_output_size",name:"padToMaxOutputSize",type:"bool"}]},{tfOpName:"NonMaxSuppressionV5",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"},{start:5,name:"softNmsSigma",type:"number"}]},{tfOpName:"Where",category:"dynamic",inputs:[{start:0,name:"condition",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ListDiff",category:"dynamic",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]},Symbol.toStringTag,{value:"Module"})),Zh=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"LowerBound",category:"evaluation",inputs:[{start:0,name:"sortedSequence",type:"tensor"},{start:1,name:"values",type:"tensor"}]},{tfOpName:"TopKV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"k",type:"number"}],attrs:[{tfName:"sorted",name:"sorted",type:"bool"}]},{tfOpName:"UpperBound",category:"evaluation",inputs:[{start:0,name:"sortedSequence",type:"tensor"},{start:1,name:"values",type:"tensor"}]},{tfOpName:"Unique",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"UniqueV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]}]},Symbol.toStringTag,{value:"Module"})),Jh=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"PlaceholderWithDefault",category:"graph",inputs:[{start:0,name:"default",type:"tensor"}],attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Placeholder",category:"graph",attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Const",category:"graph"},{tfOpName:"Identity",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IdentityN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Snapshot",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Rank",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Size",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Shape",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"ShapeN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Print",category:"graph",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"data",type:"tensors"}],attrs:[{tfName:"message",name:"message",type:"string"},{tfName:"first_n",name:"firstN",type:"number",notSupported:!0},{tfName:"summarize",name:"summarize",type:"number",defaultValue:3}]},{tfOpName:"NoOp",category:"graph",inputs:[]},{tfOpName:"StopGradient",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"FakeQuantWithMinMaxVars",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"min",name:"min",type:"number"},{tfName:"max",name:"max",type:"number"}]}]},Symbol.toStringTag,{value:"Module"})),ef=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"HashTable",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"HashTableV2",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"LookupTableImport",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableImportV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFind",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFindV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableSize",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]},{tfOpName:"LookupTableSizeV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]},{tfOpName:"InitializeTable",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}]},{tfOpName:"InitializeTableV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}]}]},Symbol.toStringTag,{value:"Module"})),tf=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"ResizeBilinear",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ResizeNearestNeighbor",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"CropAndResize",category:"image",inputs:[{start:0,name:"image",type:"tensor"},{start:1,name:"boxes",type:"tensor"},{start:2,name:"boxInd",type:"tensor"},{start:3,name:"cropSize",type:"number[]"}],attrs:[{tfName:"method",name:"method",type:"string"},{tfName:"extrapolation_value",name:"extrapolationValue",type:"number"}]},{tfOpName:"ImageProjectiveTransformV3",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"transforms",type:"tensor"},{start:2,name:"outputShape",type:"number[]"},{start:3,name:"fillValue",type:"number"}],attrs:[{tfName:"interpolation",name:"interpolation",type:"string"},{tfName:"fill_mode",name:"fillMode",type:"string"}]}]},Symbol.toStringTag,{value:"Module"})),nf=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"Equal",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NotEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Greater",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"GreaterEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Less",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LessEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalAnd",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalNot",category:"logical",inputs:[{start:0,name:"a",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalOr",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Select",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SelectV2",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BitwiseAnd",category:"logical",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}]}]},Symbol.toStringTag,{value:"Module"})),rf=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"_FusedMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMulV2",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Transpose",category:"matrices",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"perm",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Einsum",category:"matrices",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"equation",name:"equation",type:"string"},{tfName:"N",name:"n",type:"number",defaultValue:2},{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"MatrixBandPart",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"numLower",type:"tensor"},{start:1,name:"numUpper",type:"tensor"}]}]},Symbol.toStringTag,{value:"Module"})),af=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"EuclideanNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",defaultValue:!1}]},{tfOpName:"FusedBatchNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV2",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV3",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"LRN",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"depth_radius",name:"radius",type:"number",defaultValue:5},{tfName:"bias",name:"bias",type:"number",defaultValue:1},{tfName:"alpha",name:"alpha",type:"number",defaultValue:1},{tfName:"beta",name:"beta",type:"number",defaultValue:.5}]},{tfOpName:"Softmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"LogSoftmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]}]},Symbol.toStringTag,{value:"Module"})),sf=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"Bincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}]},{tfOpName:"DenseBincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}],attrs:[{tfName:"binary_output",name:"binaryOutput",type:"bool"}]},{tfOpName:"Max",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Mean",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Min",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Sum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"All",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Any",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"ArgMax",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"ArgMin",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Prod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cumprod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]},{tfOpName:"Cumsum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]}]},Symbol.toStringTag,{value:"Module"})),of=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"ConcatV2",category:"slice_join",inputs:[{start:0,end:-1,name:"tensors",type:"tensors"},{start:-1,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"Concat",category:"slice_join",inputs:[{start:1,end:0,name:"tensors",type:"tensors"},{start:0,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"GatherV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"axis",type:"number",defaultValue:0}],attrs:[{tfName:"batch_dims",name:"batchDims",type:"number",defaultValue:0}]},{tfOpName:"Gather",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",notSupported:!0}]},{tfOpName:"Reverse",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"dims",type:"bool[]"}]},{tfOpName:"ReverseV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}]},{tfOpName:"Slice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"size",type:"number[]"}]},{tfOpName:"StridedSlice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"end",type:"number[]"},{start:3,name:"strides",type:"number[]"}],attrs:[{tfName:"begin_mask",name:"beginMask",type:"number",defaultValue:0},{tfName:"end_mask",name:"endMask",type:"number",defaultValue:0},{tfName:"new_axis_mask",name:"newAxisMask",type:"number",defaultValue:0},{tfName:"ellipsis_mask",name:"ellipsisMask",type:"number",defaultValue:0},{tfName:"shrink_axis_mask",name:"shrinkAxisMask",type:"number",defaultValue:0}]},{tfOpName:"Pack",category:"slice_join",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Unpack",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"num",name:"num",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Tile",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"reps",type:"number[]"}]},{tfOpName:"Split",category:"slice_join",inputs:[{start:0,name:"axis",type:"number",defaultValue:0},{start:1,name:"x",type:"tensor"}],attrs:[{tfName:"num_split",name:"numOrSizeSplits",type:"number",defaultValue:1}]},{tfOpName:"SplitV",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"numOrSizeSplits",type:"number[]"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"ScatterNd",category:"slice_join",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"shape",type:"number[]"}]},{tfOpName:"GatherNd",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}]},{tfOpName:"SparseToDense",category:"slice_join",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!1,notSupported:!0}]},{tfOpName:"TensorScatterUpdate",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"values",type:"tensor"}]}]},Symbol.toStringTag,{value:"Module"})),uf=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"SparseFillEmptyRows",category:"sparse",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"denseShape",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}]},{tfOpName:"SparseReshape",category:"sparse",inputs:[{start:0,name:"inputIndices",type:"tensor"},{start:1,name:"inputShape",type:"tensor"},{start:2,name:"newShape",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SparseSegmentMean",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]},{tfOpName:"SparseSegmentSum",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]}]},Symbol.toStringTag,{value:"Module"})),lf=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"FFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"RFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]},{tfOpName:"IRFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]}]},Symbol.toStringTag,{value:"Module"})),cf=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"StaticRegexReplace",category:"string",inputs:[{start:0,name:"input",type:"tensor"}],attrs:[{tfName:"pattern",name:"pattern",type:"string"},{tfName:"rewrite",name:"rewrite",type:"string"},{tfName:"replace_global",name:"replaceGlobal",type:"bool"}]},{tfOpName:"StringNGrams",category:"string",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"dataSplits",type:"tensor"}],attrs:[{tfName:"separator",name:"separator",type:"string"},{tfName:"ngram_widths",name:"nGramWidths",type:"number[]"},{tfName:"left_pad",name:"leftPad",type:"string"},{tfName:"right_pad",name:"rightPad",type:"string"},{tfName:"pad_width",name:"padWidth",type:"number"},{tfName:"preserve_short_sequences",name:"preserveShortSequences",type:"bool"}],outputs:["ngrams","ngrams_splits"]},{tfOpName:"StringSplit",category:"string",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"delimiter",type:"tensor"}],attrs:[{tfName:"skip_empty",name:"skipEmpty",type:"bool"}],outputs:["indices","values","shape"]},{tfOpName:"StringToHashBucketFast",category:"string",inputs:[{start:0,name:"input",type:"tensor"}],attrs:[{tfName:"num_buckets",name:"numBuckets",type:"number"}]}]},Symbol.toStringTag,{value:"Module"})),df=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"Cast",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"SrcT",name:"sdtype",type:"dtype",notSupported:!0},{tfName:"DstT",name:"dtype",type:"dtype"}]},{tfOpName:"ExpandDims",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"MirrorPad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"mode",name:"mode",type:"string"}]},{tfOpName:"Pad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"constant_value",name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"PadV2",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"},{start:2,name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"Reshape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"EnsureShape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"Squeeze",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"axis",tfDeprecatedName:"squeeze_dims",name:"axis",type:"number[]"}]},{tfOpName:"SpaceToBatchND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"paddings",type:"number[]"}]},{tfOpName:"BatchToSpaceND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"crops",type:"number[]"}]},{tfOpName:"DepthToSpace",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"block_size",name:"blockSize",type:"number"},{tfName:"data_format",name:"dataFormat",type:"string"}]},{tfOpName:"BroadcastTo",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}],attrs:[]},{tfOpName:"BroadcastArgs",category:"transformation",inputs:[{start:0,name:"s0",type:"tensor"},{start:1,name:"s1",type:"tensor"}],attrs:[]}]},Symbol.toStringTag,{value:"Module"}));class pf{static get Instance(){return this._instance||(this._instance=new this)}constructor(){const e=[].concat(...[jh,qh,Kh,Xh,Yh,Qh,Zh,Jh,ef,tf,nf,rf,af,sf,of,uf,lf,cf,df].map(e=>e.json));this.opMappers=e.reduce((e,t)=>(e[t.tfOpName]=t,e),{})}transformGraph(e,t={}){const n=e.node,r=[],a=[],s=[],o=n.reduce((e,t)=>(e[t.name]=this.mapNode(t),t.op.startsWith("Placeholder")?r.push(e[t.name]):"Const"===t.op?a.push(e[t.name]):null!=t.input&&0!==t.input.length||s.push(e[t.name]),e),{});let i=[];const u=[];let l={},c={};null!=t&&(l=this.mapSignatureEntries(t.inputs),c=this.mapSignatureEntries(t.outputs));const d=Object.keys(o);d.forEach(e=>{const t=o[e];t.inputNames.forEach((e,n)=>{const[r,,a]=Wh(e),s=o[r];if(null!=s.outputs){const e=s.outputs.indexOf(a);if(-1!==e){const a=`${r}:${e}`;t.inputNames[n]=a}}t.inputs.push(s),s.children.push(t)})}),0===Object.keys(c).length?d.forEach(e=>{const t=o[e];0===t.children.length&&u.push(t)}):Object.keys(c).forEach(e=>{const[t]=Wh(e),n=o[t];null!=n&&(n.signatureKey=c[e],u.push(n))}),Object.keys(l).length>0?Object.keys(l).forEach(e=>{const[t]=Wh(e),n=o[t];n&&(n.signatureKey=l[e],i.push(n))}):i=r;let p={};null!=e.library&&null!=e.library.function&&(p=e.library.function.reduce((e,t)=>(e[t.signature.name]=this.mapFunction(t),e),{}));const h={nodes:o,inputs:i,outputs:u,weights:a,placeholders:r,signature:t,functions:p};return s.length>0&&(h.initNodes=s),h}mapSignatureEntries(e){return Object.keys(e||{}).reduce((t,n)=>(t[e[n].name]=n,t),{})}mapNode(e){const t=Ph(e.op)||this.opMappers[e.op]||{};null==e.attr&&(e.attr={});const n={name:e.name,op:e.op,category:t.category,inputNames:(e.input||[]).map(e=>e.startsWith("^")?e.slice(1):e),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:e.attr,outputs:t.outputs};return null!=t.inputs&&(n.inputParams=t.inputs.reduce((e,t)=>(e[t.name]={type:t.type,inputIndexStart:t.start,inputIndexEnd:t.end},e),{})),null!=t.attrs&&(n.attrParams=t.attrs.reduce((t,n)=>{const r=n.type;let a;switch(n.type){case"string":a=ff(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=ff(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"string[]":a=Nf(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Nf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number":a=gf(e.attr,n.tfName,n.defaultValue||0),void 0===a&&n.tfDeprecatedName&&(a=gf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number[]":a=If(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=If(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool":a=mf(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=mf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool[]":a=Tf(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Tf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape":a=kf(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=kf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape[]":a=Sf(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Sf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype":a=xf(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=xf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype[]":a=vf(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=vf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"func":a=bf(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=bf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error(`Unsupported param type: ${n.type} for op: ${e.op}`)}return t[n.name]={value:a,type:r},t},{})),n}mapFunction(e){const t=e.nodeDef,n=[];let r={};null!=t&&(r=t.reduce((e,t)=>(e[t.name]=this.mapNode(t),"Const"===t.op&&n.push(e[t.name]),e),{}));const a=[],s=[];e.signature.inputArg.forEach(e=>{const[t]=Wh(e.name),n={name:t,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:yf(e.type),type:"dtype"}},children:[]};n.signatureKey=e.name,a.push(n),r[t]=n});Object.keys(r).forEach(e=>{const t=r[e];t.inputNames.forEach((e,n)=>{const[a,,s]=Wh(e),o=r[a];if(null!=o.outputs){const e=o.outputs.indexOf(s);if(-1!==e){const r=`${a}:${e}`;t.inputNames[n]=r}}t.inputs.push(o),o.children.push(t)})});const o=e.ret;e.signature.outputArg.forEach(e=>{const[t,n]=Wh(o[e.name]),a=r[t];null!=a&&(a.defaultOutput=n,s.push(a))});const i=this.mapArgsToSignature(e);return{nodes:r,inputs:a,outputs:s,weights:n,placeholders:[],signature:i}}mapArgsToSignature(e){return{methodName:e.signature.name,inputs:e.signature.inputArg.reduce((e,t)=>(e[t.name]=this.mapArgToTensorInfo(t),e),{}),outputs:e.signature.outputArg.reduce((t,n)=>(t[n.name]=this.mapArgToTensorInfo(n,e.ret),t),{})}}mapArgToTensorInfo(e,t){let n=e.name;return null!=t&&(n=t[n]),{name:n,dtype:e.type}}}function hf(e,t){const n=Array.isArray(e)?String.fromCharCode.apply(null,e):function(e){const t=V().global;if("undefined"!==typeof t.atob)return t.atob(e);if("undefined"!==typeof Buffer)return new Buffer(e,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}(e);return t?n:n.toLowerCase()}function ff(e,t,n,r=!1){const a=e[t];return null!=a?hf(a.s,r):n}function mf(e,t,n){const r=e[t];return r?r.b:n}function gf(e,t,n){const r=e[t]||{},a=null!=r.i?r.i:null!=r.f?r.f:n;return"number"===typeof a?a:parseInt(a,10)}function yf(e){switch("string"===typeof e&&(e=Oh[e]),e){case Oh.DT_FLOAT:case Oh.DT_HALF:return"float32";case Oh.DT_INT32:case Oh.DT_INT64:case Oh.DT_INT8:case Oh.DT_UINT8:return"int32";case Oh.DT_BOOL:return"bool";case Oh.DT_DOUBLE:return"float32";case Oh.DT_STRING:return"string";case Oh.DT_COMPLEX64:case Oh.DT_COMPLEX128:return"complex64";default:return null}}function bf(e,t,n){const r=e[t];return r&&r.func?r.func.name:n}function xf(e,t,n){const r=e[t];return r&&r.type?yf(r.type):n}function vf(e,t,n){const r=e[t];return r&&r.list&&r.list.type?r.list.type.map(e=>yf(e)):n}function wf(e){if(!e.unknownRank)return null!=e.dim?e.dim.map(e=>"number"===typeof e.size?e.size:parseInt(e.size,10)):[]}function kf(e,t,n){const r=e[t];return r&&r.shape?wf(r.shape):n}function If(e,t,n){const r=e[t];return r?((r.list.f&&r.list.f.length?r.list.f:r.list.i)||[]).map(e=>"number"===typeof e?e:parseInt(e,10)):n}function Nf(e,t,n,r=!1){const a=e[t];return a&&a.list&&a.list.s?a.list.s.map(e=>hf(e,r)):n}function Sf(e,t,n){const r=e[t];return r&&r.list&&r.list.shape?r.list.shape.map(e=>wf(e)):n}function Tf(e,t,n){const r=e[t];return r&&r.list&&r.list.b?r.list.b:n}class Cf{constructor(e,t,n){this.node=e,this.tensorMap=t,this.context=n,this.inputs=[],this.attrs={},this.inputs=e.inputNames.map(e=>this.getInput(e)),null!=e.rawAttrs&&(this.attrs=Object.keys(e.rawAttrs).reduce((e,t)=>(e[t]=this.getAttr(t),e),{}))}getInput(e){return Bh(e,this.tensorMap,this.context)}getAttr(e,t){const n=this.node.rawAttrs[e];if(null!=n.tensor)return Bh(e,this.tensorMap,this.context);if(null!=n.i||null!=n.f)return gf(this.node.rawAttrs,e,t);if(null!=n.s)return ff(this.node.rawAttrs,e,t);if(null!=n.b)return mf(this.node.rawAttrs,e,t);if(null!=n.shape)return kf(this.node.rawAttrs,e,t);if(null!=n.type)return xf(this.node.rawAttrs,e,t);if(null!=n.list){if(null!=n.list.i||null!=n.list.f)return If(this.node.rawAttrs,e,t);if(null!=n.list.s)return Nf(this.node.rawAttrs,e,t);if(null!=n.list.shape)return Sf(this.node.rawAttrs,e,t);if(null!=n.list.b)return Tf(this.node.rawAttrs,e,t);if(null!=n.list.type)return vf(this.node.rawAttrs,e,t)}return t}}const $f=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,OP_SCOPE_SUFFIX:_a,abs:Hs,acos:js,acosh:qs,add:Ws,addN:Ks,all:Xs,any:Ys,argMax:Qs,argMin:Zs,asin:Js,asinh:eo,atan:to,atan2:no,atanh:ro,avgPool:wo,avgPool3d:ko,basicLSTMCell:$o,batchNorm:Ro,batchNorm2d:_o,batchNorm3d:Ao,batchNorm4d:Oo,batchToSpaceND:Eo,bincount:Fo,bitwiseAnd:Do,booleanMaskAsync:Ic,broadcastArgs:Mo,broadcastTo:Po,buffer:Ps,cast:Ls,ceil:Lo,clipByValue:Vo,clone:Bs,complex:Oa,concat:Io,concat1d:Wo,concat2d:zo,concat3d:Uo,concat4d:Go,conv1d:jo,conv2d:Ho,conv2dTranspose:Ko,conv3d:Xo,conv3dTranspose:Qo,cos:Zo,cosh:Jo,cosineWindow:_c,cumprod:ei,cumsum:ti,denseBincount:ni,depthToSpace:ri,depthwiseConv2d:ai,diag:si,dilation2d:oi,div:Us,divNoNan:hi,dot:fi,dropout:Ec,einsum:mi,elu:gi,enclosingPowerOfTwo:Rc,ensureShape:yi,equal:ci,erf:bi,euclideanNorm:Mi,exp:Pi,expandDims:Li,expm1:Bi,eye:Wi,fft:ql,fill:Bo,floor:zi,floorDiv:zs,fused:Uc,gather:Ui,gatherND:$c,greater:Gi,greaterEqual:Hi,ifft:Kl,imag:ji,image:Md,inTopKAsync:Ac,irfft:Xl,isFinite:qi,isInf:Ki,isNaN:Xi,leakyRelu:Yi,less:Qi,lessEqual:Zi,linalg:Pd,linspace:Ji,localResponseNormalization:eu,log:tu,log1p:nu,logSigmoid:iu,logSoftmax:lu,logSumExp:cu,logicalAnd:du,logicalNot:pu,logicalOr:hu,logicalXor:fu,losses:Ld,lowerBound:yu,matMul:No,max:Ci,maxPool:bu,maxPool3d:xu,maxPoolWithArgmax:vu,maximum:wu,mean:ku,meshgrid:Su,min:$i,minimum:Tu,mirrorPad:Cu,mod:$u,moments:Eu,movingAverage:Sc,mul:Gs,multiRNNCell:Ru,multinomial:_u,neg:su,norm:Di,notEqual:Au,oneHot:Ou,ones:Nu,onesLike:Fu,op:Aa,outerProduct:Du,pad:Mu,pad1d:Pu,pad2d:Lu,pad3d:Bu,pad4d:Vu,pool:zu,pow:Ei,prelu:Uu,print:Vs,prod:Gu,raggedGather:Hu,raggedRange:ju,raggedTensorToTensor:qu,rand:Ku,randomGamma:xl,randomNormal:vl,randomStandardNormal:wl,randomUniform:kl,randomUniformInt:Il,range:Nl,real:Sl,reciprocal:Tl,relu:Cl,relu6:$l,reshape:vo,reverse:El,reverse1d:Rl,reverse2d:_l,reverse3d:Al,reverse4d:Ol,rfft:Ql,round:Fl,rsqrt:Dl,scalar:Ri,scatterND:Tc,searchSorted:gu,selu:Ml,separableConv2d:Pl,setdiff1dAsync:Ll,sigmoid:So,sign:Bl,signal:Dd,sin:Vl,sinh:Wl,slice:To,slice1d:zl,slice2d:Ul,slice3d:Gl,slice4d:Hl,softmax:jl,softplus:ou,spaceToBatchND:Wu,sparse:Bd,sparseToDense:Cc,spectral:Fd,split:Yl,sqrt:_i,square:Ai,squaredDifference:Zl,squeeze:Jl,stack:ec,step:tc,stridedSlice:nc,string:Vd,sub:uu,sum:Oi,tan:rc,tanh:Co,tensor:Da,tensor1d:ac,tensor2d:sc,tensor3d:oc,tensor4d:ic,tensor5d:uc,tensor6d:lc,tensorScatterUpdate:hc,tile:Vi,topk:fc,transpose:Nc,truncatedNormal:mc,unique:gc,unsortedSegmentSum:yc,unstack:bc,upperBound:xc,variable:vc,where:di,whereAsync:kc,zeros:Iu,zerosLike:pi},Symbol.toStringTag,{value:"Module"}));function Ef(e,t,n=""){if("number"!==typeof e&&"number"!==typeof t){i(e.length===t.length,()=>n+` Shapes ${e} and ${t} must match`);for(let r=0;rn+` Shapes ${e} and ${t} must match`)}}}function Rf(e){return"number"!==typeof e&&!e.some(e=>e<0)}function _f(e,t,n){let r=Af(e,n);const a=!Rf(r);if(a&&0===t.length)throw new Error(`Tried to calculate elements of an empty list with non-fully-defined elementShape: ${r}`);if(a&&t.forEach(e=>{r=Af(e.shape,r)}),!Rf(r))throw new Error(`Non-fully-defined elementShape: ${r}`);return r}function Af(e,t){if("number"===typeof e)return t;if("number"===typeof t)return e;if(e.length!==t.length)throw new Error(`Incompatible ranks during merge: ${e} vs. ${t}`);const n=[];for(let r=0;r=0&&s>=0&&a!==s)throw new Error(`Incompatible shape during merge: ${e} vs. ${t}`);n[r]=a>=0?a:s}return n}class Of{constructor(e,t,n,r,a,s,o){this.name=e,this.dtype=t,this.maxSize=n,this.elementShape=r,this.identicalElementShapes=a,this.dynamicSize=s,this.clearAfterRead=o,this.tensors=[],this.closed_=!1,this.idTensor=Ri(0),Wa(this.idTensor)}get id(){return this.idTensor.id}get closed(){return this.closed_}clearAndClose(e){this.tensors.forEach(t=>{null!=e&&e.has(t.tensor.id)||t.tensor.dispose()}),this.tensors=[],this.closed_=!0,this.idTensor.dispose()}size(){return this.tensors.length}read(e){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||e>=this.size())throw new Error(`Tried to read from index ${e}, but array size is: ${this.size()}`);const t=this.tensors[e];if(t.cleared)throw new Error(`TensorArray ${this.name}: Could not read index ${e} twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).`);return this.clearAfterRead&&(t.cleared=!0),t.read=!0,t.tensor}readMany(e){return e.map(e=>this.read(e))}write(e,t){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||!this.dynamicSize&&e>=this.maxSize)throw new Error(`Tried to write to index ${e}, but array is not resizeable and size is: ${this.maxSize}`);const n=this.tensors[e]||{};if(t.dtype!==this.dtype)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e},\n because the value dtype is ${t.dtype}, but TensorArray dtype is ${this.dtype}.`);if(0!==this.size()||null!=this.elementShape&&0!==this.elementShape.length||(this.elementShape=t.shape),Ef(this.elementShape,t.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${e}.`),n.read)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`);if(n.written)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`);n.tensor=t,Wa(t),n.written=!0,this.tensors[e]=n}writeMany(e,t){if(e.length!==t.length)throw new Error(`TensorArray ${this.name}: could not write multiple tensors,because the index size: ${e.length} is not the same as tensors size: ${t.length}.`);e.forEach((e,n)=>this.write(e,t[n]))}gather(e,t){if(t&&t!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${t}`);if(e)e=e.slice(0,this.size());else{e=[];for(let t=0;t=this.maxSize)throw new Error(`Max index must be < array size (${n} vs. ${this.maxSize})`);this.writeMany(e,bc(t,0))}split(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);let n=0;const r=e.map(e=>(n+=e,n));if(n!==t.shape[0])throw new Error(`Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n ${n}, and tensor's shape is: ${t.shape}`);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${e.length}), and the TensorArray is not marked as dynamically resizeable`);const a=0===n?0:t.size/n,s=[];Ba(()=>{t=vo(t,[1,n,a]);for(let n=0;n{if(n!==e.dtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${e.dtype}`);Ef(t,e.shape,"TensorList shape mismatch: "),Wa(e)}),this.idTensor=Ri(0),this.maxNumElements=r,Wa(this.idTensor)}copy(){return new Ff([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(e){this.tensors.forEach(t=>{null!=e&&e.has(t.id)||t.dispose()}),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(e,t,n=-1){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(-1!==n&&this.tensors.length!==n)throw new Error(`Operation expected a list with ${n} elements but got a list with ${this.tensors.length} elements.`);Ef(e,this.elementShape,"TensorList shape mismatch: ");const r=_f(this.elementShape,this.tensors,e);return Ba(()=>{const e=this.tensors.map(e=>vo(e,r));return ec(e,0)})}popBack(e,t){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(0===this.size())throw new Error("Trying to pop from an empty list.");const n=_f(this.elementShape,this.tensors,e),r=this.tensors.pop();return r.kept=!1,Ef(r.shape,e,"TensorList shape mismatch: "),vo(r,n)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(Ef(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");Wa(e),this.tensors.push(e)}resize(e){if(e<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${e}`);if(-1!==this.maxNumElements&&e>this.maxNumElements)throw new Error(`TensorListResize input size ${e} is greater maxNumElement ${this.maxNumElements}.`);const t=new Ff([],this.elementShape,this.elementDtype,this.maxNumElements);t.tensors.length=e;for(let n=0;nthis.tensors.length)throw new Error(`Trying to access element ${e} in a list with ${this.tensors.length} elements.`);if(null==this.tensors[e])throw new Error(`element at index ${e} is null.`);Ef(this.tensors[e].shape,t,"TensorList shape mismatch: ");const r=_f(this.elementShape,this.tensors,t);return vo(this.tensors[e],r)}setItem(e,t){if(t.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);if(e<0||-1!==this.maxNumElements&&e>=this.maxNumElements)throw new Error(`Trying to set element ${e} in a list with max ${this.maxNumElements} elements.`);Ef(this.elementShape,t.shape,"TensorList shape mismatch: "),Wa(t),null!=this.tensors[e]&&(this.tensors[e].kept=!1),this.tensors[e]=t}gather(e,t,n){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);Ef(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size());const r=_f(this.elementShape,this.tensors,n);return 0===e.length?Da([],[0].concat(r)):Ba(()=>{const t=e.map(e=>vo(this.tensors[e],r));return ec(t,0)})}concat(e,t){if(e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);Ef(this.elementShape,t,"TensorList shape mismatch: ");const n=_f(this.elementShape,this.tensors,t);return 0===this.size()?Da([],[0].concat(n)):Ba(()=>{const e=this.tensors.map(e=>vo(e,n));return Io(e,0)})}}const Df=async(e,t,n)=>{switch(e.op){case"If":case"StatelessIf":{const r=Lh("thenBranch",e,t,n),a=Lh("elseBranch",e,t,n),s=Lh("cond",e,t,n),o=Lh("args",e,t,n);return(await s.data())[0]?n.functionMap[r].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap):n.functionMap[a].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap)}case"While":case"StatelessWhile":{const r=Lh("body",e,t,n),a=Lh("cond",e,t,n),s=Lh("args",e,t,n),o=await n.functionMap[a].executeFunctionAsync(s,n.tensorArrayMap,n.tensorListMap),i=s.map(e=>e.id);let u=await o[0].data();o.forEach(e=>{e.kept||-1!==i.indexOf(e.id)||e.dispose()});let l=s;for(;u[0];){const e=l;l=await n.functionMap[r].executeFunctionAsync(l,n.tensorArrayMap,n.tensorListMap);const t=l.map(e=>e.id);e.forEach(e=>{e.kept||-1!==i.indexOf(e.id)||-1!==t.indexOf(e.id)||e.dispose()});const s=await n.functionMap[a].executeFunctionAsync(l,n.tensorArrayMap,n.tensorListMap);u=await s[0].data(),s.forEach(e=>{e.kept||-1!==i.indexOf(e.id)||-1!==t.indexOf(e.id)||e.dispose()})}return l}case"LoopCond":return[Hh(Lh("pred",e,t,n))];case"Switch":{const r=Lh("pred",e,t,n);let a=Lh("data",e,t,n);return a.kept||(a=Hh(a)),(await r.data())[0]?[void 0,a]:[a,void 0]}case"Merge":{const r=e.inputNames.find(e=>void 0!==Bh(e,t,n));if(r){return[Hh(Bh(r,t,n))]}return}case"Enter":{const r=Lh("frameName",e,t,n),a=Lh("tensor",e,t,n);return n.enterFrame(r),[Hh(a)]}case"Exit":{const r=Lh("tensor",e,t,n);return n.exitFrame(),[Hh(r)]}case"NextIteration":{const r=Lh("tensor",e,t,n);return n.nextIteration(),[Hh(r)]}case"TensorArrayV3":{const r=Lh("size",e,t,n),a=Lh("dtype",e,t,n),s=Lh("elementShape",e,t,n),o=Lh("dynamicSize",e,t,n),i=Lh("clearAfterRead",e,t,n),u=Lh("identicalElementShapes",e,t,n),l=Lh("name",e,t,n),c=new Of(l,a,r,s,u,o,i);return n.addTensorArray(c),[c.idTensor,Ri(1)]}case"TensorArrayWriteV3":{const r=Lh("tensorArrayId",e,t,n),a=Lh("index",e,t,n),s=Lh("tensor",e,t,n),o=n.getTensorArray(r.id);return o.write(a,s),[o.idTensor]}case"TensorArrayReadV3":{const r=Lh("tensorArrayId",e,t,n),a=Lh("index",e,t,n);return[n.getTensorArray(r.id).read(a)]}case"TensorArrayGatherV3":{const r=Lh("tensorArrayId",e,t,n),a=Lh("indices",e,t,n),s=Lh("dtype",e,t,n);return[n.getTensorArray(r.id).gather(a,s)]}case"TensorArrayScatterV3":{const r=Lh("tensorArrayId",e,t,n),a=Lh("indices",e,t,n),s=Lh("tensor",e,t,n),o=n.getTensorArray(r.id);return o.scatter(a,s),[o.idTensor]}case"TensorArrayConcatV3":{const r=Lh("tensorArrayId",e,t,n),a=n.getTensorArray(r.id),s=Lh("dtype",e,t,n);return[a.concat(s)]}case"TensorArraySplitV3":{const r=Lh("tensorArrayId",e,t,n),a=Lh("tensor",e,t,n),s=Lh("lengths",e,t,n),o=n.getTensorArray(r.id);return o.split(s,a),[o.idTensor]}case"TensorArraySizeV3":{const r=Lh("tensorArrayId",e,t,n);return[Ri(n.getTensorArray(r.id).size(),"int32")]}case"TensorArrayCloseV3":{const r=Lh("tensorArrayId",e,t,n),a=n.getTensorArray(r.id);return a.clearAndClose(),[a.idTensor]}case"TensorListSetItem":{const r=Lh("tensorListId",e,t,n),a=Lh("index",e,t,n),s=Lh("tensor",e,t,n),o=n.getTensorList(r.id);return o.setItem(a,s),[o.idTensor]}case"TensorListGetItem":{const r=Lh("tensorListId",e,t,n),a=Lh("index",e,t,n),s=Lh("elementShape",e,t,n),o=Lh("elementDType",e,t,n);return[n.getTensorList(r.id).getItem(a,s,o)]}case"TensorListScatterV2":case"TensorListScatter":{const r=Lh("indices",e,t,n),a=function(e,t,n,r){if(t.length!==e.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${t.length} vs. ${e.shape[0]}`);const a=Math.max(...t);if(null!=r&&-1!==r&&a>=r)throw new Error(`Max index must be < array size (${a} vs. ${r})`);const s=new Ff([],n,e.dtype,r),o=bc(e,0);return t.forEach((e,t)=>{s.setItem(e,o[t])}),s}(Lh("tensor",e,t,n),r,Lh("elementShape",e,t,n),Lh("numElements",e,t,n));return n.addTensorList(a),[a.idTensor]}case"TensorListReserve":case"EmptyTensorList":{const r=Lh("elementShape",e,t,n),a=Lh("elementDType",e,t,n);let s;s="TensorListReserve"===e.op?"numElements":"maxNumElements";const o=Lh(s,e,t,n),i=function(e,t,n,r){return new Ff([],e,t,r)}(r,a,0,"TensorListReserve"===e.op?-1:o);return n.addTensorList(i),[i.idTensor]}case"TensorListGather":{const r=Lh("tensorListId",e,t,n),a=Lh("indices",e,t,n),s=Lh("elementShape",e,t,n),o=Lh("elementDType",e,t,n);return[n.getTensorList(r.id).gather(a,o,s)]}case"TensorListStack":{const r=Lh("tensorListId",e,t,n),a=Lh("elementShape",e,t,n),s=Lh("elementDType",e,t,n),o=Lh("numElements",e,t,n);return[n.getTensorList(r.id).stack(a,s,o)]}case"TensorListFromTensor":{const r=function(e,t,n){const r=e.dtype;if(e.shape.length<1)throw new Error(`Tensor must be at least a vector, but saw shape: ${e.shape}`);if(e.dtype!==n)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${n}`);Ef(e.shape.slice(1),t,"TensorList shape mismatch: ");const a=bc(e);return new Ff(a,t,r)}(Lh("tensor",e,t,n),Lh("elementShape",e,t,n),Lh("elementDType",e,t,n));return n.addTensorList(r),[r.idTensor]}case"TensorListConcat":case"TensorListConcatV2":{const r=Lh("tensorListId",e,t,n),a=n.getTensorList(r.id),s=Lh("dtype",e,t,n),o=Lh("elementShape",e,t,n);return[a.concat(s,o)]}case"TensorListPushBack":{const r=Lh("tensorListId",e,t,n),a=Lh("tensor",e,t,n),s=n.getTensorList(r.id);return s.pushBack(a),[s.idTensor]}case"TensorListPopBack":{const r=Lh("tensorListId",e,t,n),a=Lh("elementShape",e,t,n),s=Lh("elementDType",e,t,n);return[n.getTensorList(r.id).popBack(a,s)]}case"TensorListSplit":{const r=Lh("tensor",e,t,n),a=Lh("elementShape",e,t,n),s=function(e,t,n){let r=0;const a=t.map(e=>(r+=e,r));if(r!==e.shape[0])throw new Error(`Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n ${r}, and tensor's shape is: ${e.shape}`);const s=Af(e.shape.slice(1),n),o=0===r?0:e.size/r,i=Ba(()=>{const n=[];e=vo(e,[1,r,o]);for(let r=0;re.dispose()),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}tensorSize(){return Ri(this.size(),"int32")}async import(e,t){this.checkKeyAndValueTensor(e,t);const n=await e.data();return this.tensorMap.forEach(e=>e.dispose()),this.tensorMap.clear(),Ba(()=>{const e=bc(t),r=n.length,a=e.length;i(r===a,()=>`The number of elements doesn't match, keys has ${r} elements, the values has ${a} elements.`);for(let t=0;t{const e=[];for(let r=0;r{switch(e.category){case"arithmetic":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[r.add(Lh("a",e,t,n),Lh("b",e,t,n))];case"AddN":return[r.addN(Lh("tensors",e,t,n))];case"FloorMod":case"Mod":return[r.mod(Lh("a",e,t,n),Lh("b",e,t,n))];case"Mul":return[r.mul(Lh("a",e,t,n),Lh("b",e,t,n))];case"RealDiv":case"Div":return[r.div(Lh("a",e,t,n),Lh("b",e,t,n))];case"DivNoNan":return[r.divNoNan(Lh("a",e,t,n),Lh("b",e,t,n))];case"FloorDiv":return[r.floorDiv(Lh("a",e,t,n),Lh("b",e,t,n))];case"Sub":return[r.sub(Lh("a",e,t,n),Lh("b",e,t,n))];case"Minimum":return[r.minimum(Lh("a",e,t,n),Lh("b",e,t,n))];case"Maximum":return[r.maximum(Lh("a",e,t,n),Lh("b",e,t,n))];case"Pow":return[r.pow(Lh("a",e,t,n),Lh("b",e,t,n))];case"SquaredDifference":return[r.squaredDifference(Lh("a",e,t,n),Lh("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"basic_math":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"Abs":case"ComplexAbs":return[r.abs(Lh("x",e,t,n))];case"Acos":return[r.acos(Lh("x",e,t,n))];case"Acosh":return[r.acosh(Lh("x",e,t,n))];case"Asin":return[r.asin(Lh("x",e,t,n))];case"Asinh":return[r.asinh(Lh("x",e,t,n))];case"Atan":return[r.atan(Lh("x",e,t,n))];case"Atan2":return[r.atan2(Lh("x",e,t,n),Lh("y",e,t,n))];case"Atanh":return[r.atanh(Lh("x",e,t,n))];case"Ceil":return[r.ceil(Lh("x",e,t,n))];case"Complex":return[r.complex(Lh("real",e,t,n),Lh("imag",e,t,n))];case"Cos":return[r.cos(Lh("x",e,t,n))];case"Cosh":return[r.cosh(Lh("x",e,t,n))];case"Elu":return[r.elu(Lh("x",e,t,n))];case"Erf":return[r.erf(Lh("x",e,t,n))];case"Exp":return[r.exp(Lh("x",e,t,n))];case"Expm1":return[r.expm1(Lh("x",e,t,n))];case"Floor":return[r.floor(Lh("x",e,t,n))];case"Log":return[r.log(Lh("x",e,t,n))];case"Log1p":return[r.log1p(Lh("x",e,t,n))];case"Imag":return[r.imag(Lh("x",e,t,n))];case"Neg":return[r.neg(Lh("x",e,t,n))];case"Reciprocal":return[r.reciprocal(Lh("x",e,t,n))];case"Real":return[r.real(Lh("x",e,t,n))];case"Relu":return[r.relu(Lh("x",e,t,n))];case"Round":return[r.round(Lh("x",e,t,n))];case"Selu":return[r.selu(Lh("x",e,t,n))];case"Sigmoid":return[r.sigmoid(Lh("x",e,t,n))];case"Sin":return[r.sin(Lh("x",e,t,n))];case"Sign":return[r.sign(Lh("x",e,t,n))];case"Sinh":return[r.sinh(Lh("x",e,t,n))];case"Softplus":return[r.softplus(Lh("x",e,t,n))];case"Sqrt":return[r.sqrt(Lh("x",e,t,n))];case"Square":return[r.square(Lh("x",e,t,n))];case"Tanh":return[r.tanh(Lh("x",e,t,n))];case"Tan":return[r.tan(Lh("x",e,t,n))];case"ClipByValue":return[r.clipByValue(Lh("x",e,t,n),Lh("clipValueMin",e,t,n),Lh("clipValueMax",e,t,n))];case"Relu6":return[r.relu6(Lh("x",e,t,n))];case"Rsqrt":return[r.rsqrt(Bh(e.inputNames[0],t,n))];case"LeakyRelu":return[r.leakyRelu(Lh("x",e,t,n),Lh("alpha",e,t,n))];case"Prelu":return[r.prelu(Lh("x",e,t,n),Lh("alpha",e,t,n))];case"IsNan":return[r.isNaN(Bh(e.inputNames[0],t,n))];case"IsInf":return[r.isInf(Bh(e.inputNames[0],t,n))];case"IsFinite":return[r.isFinite(Bh(e.inputNames[0],t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"control":return Df(e,t,n);case"convolution":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"Conv1D":{const a=Lh("stride",e,t,n),s=Lh("pad",e,t,n),o=Lh("dataFormat",e,t,n).toUpperCase(),i=Lh("dilation",e,t,n);return[r.conv1d(Lh("x",e,t,n),Lh("filter",e,t,n),a,s,o,i)]}case"Conv2D":{const a=Lh("strides",e,t,n),s=Gh(e,t,n),o=Lh("dataFormat",e,t,n).toUpperCase(),i=Lh("dilations",e,t,n);return[r.conv2d(Lh("x",e,t,n),Lh("filter",e,t,n),[a[1],a[2]],s,o,[i[1],i[2]])]}case"_FusedConv2D":{const{stride:a,pad:s,dataFormat:o,dilations:i,biasArg:u,preluArg:l,activationFunc:c,leakyreluAlpha:d}=Mf(e,t,n);return[r.fused.conv2d({x:Lh("x",e,t,n),filter:Lh("filter",e,t,n),strides:[a[1],a[2]],pad:s,dataFormat:o,dilations:[i[1],i[2]],bias:u,activation:c,preluActivationWeights:l,leakyreluAlpha:d})]}case"FusedDepthwiseConv2dNative":{const{stride:a,pad:s,dataFormat:o,dilations:i,biasArg:u,preluArg:l,activationFunc:c,leakyreluAlpha:d}=Mf(e,t,n);return[r.fused.depthwiseConv2d({x:Lh("x",e,t,n),filter:Lh("filter",e,t,n),strides:[a[1],a[2]],pad:s,dataFormat:o,dilations:[i[1],i[2]],bias:u,activation:c,preluActivationWeights:l,leakyreluAlpha:d})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{const a=Lh("outputShape",e,t,n),s=Lh("strides",e,t,n),o=Gh(e,t,n);return[r.conv2dTranspose(Lh("x",e,t,n),Lh("filter",e,t,n),a,[s[1],s[2]],o)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{const a=Lh("strides",e,t,n),s=Gh(e,t,n),o=Lh("dilations",e,t,n),i=Lh("dataFormat",e,t,n).toUpperCase();return[r.depthwiseConv2d(Lh("input",e,t,n),Lh("filter",e,t,n),[a[1],a[2]],s,i,[o[1],o[2]])]}case"Conv3D":{const a=Lh("strides",e,t,n),s=Lh("pad",e,t,n),o=Lh("dataFormat",e,t,n).toUpperCase(),i=Lh("dilations",e,t,n);return[r.conv3d(Lh("x",e,t,n),Lh("filter",e,t,n),[a[1],a[2],a[3]],s,o,[i[1],i[2],i[3]])]}case"AvgPool":{const a=Lh("strides",e,t,n),s=Lh("pad",e,t,n),o=Lh("kernelSize",e,t,n);return[r.avgPool(Lh("x",e,t,n),[o[1],o[2]],[a[1],a[2]],s)]}case"MaxPool":{const a=Lh("strides",e,t,n),s=Lh("pad",e,t,n),o=Lh("kernelSize",e,t,n);return[r.maxPool(Lh("x",e,t,n),[o[1],o[2]],[a[1],a[2]],s)]}case"MaxPoolWithArgmax":{const a=Lh("strides",e,t,n),s=Lh("pad",e,t,n),o=Lh("kernelSize",e,t,n),i=Lh("includeBatchInIndex",e,t,n),{result:u,indexes:l}=r.maxPoolWithArgmax(Lh("x",e,t,n),[o[1],o[2]],[a[1],a[2]],s,i);return[u,l]}case"AvgPool3D":{const a=Lh("strides",e,t,n),s=Lh("pad",e,t,n),o=Lh("kernelSize",e,t,n);return[r.avgPool3d(Lh("x",e,t,n),[o[1],o[2],o[3]],[a[1],a[2],a[3]],s)]}case"MaxPool3D":{const a=Lh("strides",e,t,n),s=Lh("pad",e,t,n),o=Lh("kernelSize",e,t,n);return[r.maxPool3d(Lh("x",e,t,n),[o[1],o[2],o[3]],[a[1],a[2],a[3]],s)]}case"Dilation2D":{const a=Lh("strides",e,t,n),s=Lh("pad",e,t,n),o=Lh("dilations",e,t,n),i=a[1],u=a[2],l=o[1],c=o[2];return[r.dilation2d(Lh("x",e,t,n),Lh("filter",e,t,n),[i,u],s,[l,c],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"creation":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"Fill":{const a=Lh("shape",e,t,n),s=Lh("dtype",e,t,n),o=Lh("value",e,t,n);return[r.fill(a,o,s)]}case"LinSpace":{const a=Lh("start",e,t,n),s=Lh("stop",e,t,n),o=Lh("num",e,t,n);return[r.linspace(a,s,o)]}case"Multinomial":{const a=Lh("logits",e,t,n),s=Lh("numSamples",e,t,n),o=Lh("seed",e,t,n);return[r.multinomial(a,s,o)]}case"OneHot":{const a=Lh("indices",e,t,n),s=Lh("depth",e,t,n),o=Lh("onValue",e,t,n),i=Lh("offValue",e,t,n),u=Lh("dtype",e,t,n);return[r.oneHot(a,s,o,i,u)]}case"Ones":return[r.ones(Lh("shape",e,t,n),Lh("dtype",e,t,n))];case"OnesLike":return[r.onesLike(Lh("x",e,t,n))];case"RandomStandardNormal":return[r.randomStandardNormal(Lh("shape",e,t,n),Lh("dtype",e,t,n),Lh("seed",e,t,n))];case"RandomUniform":return[r.randomUniform(Lh("shape",e,t,n),Lh("minval",e,t,n),Lh("maxval",e,t,n),Lh("dtype",e,t,n))];case"RandomUniformInt":return[r.randomUniformInt(Lh("shape",e,t,n),Lh("minval",e,t,n),Lh("maxval",e,t,n),Lh("seed",e,t,n))];case"Range":{const a=Lh("start",e,t,n),s=Lh("stop",e,t,n),o=Lh("step",e,t,n);return[r.range(a,s,o,Lh("dtype",e,t,n))]}case"TruncatedNormal":{const a=Lh("shape",e,t,n),s=Lh("mean",e,t,n),o=Lh("stdDev",e,t,n),i=Lh("seed",e,t,n);return[r.truncatedNormal(a,s,o,Lh("dtype",e,t,n),i)]}case"Zeros":return[r.zeros(Lh("shape",e,t,n),Lh("dtype",e,t,n))];case"ZerosLike":return[r.zerosLike(Lh("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"dynamic":return(async(e,t,n,r,a=$f)=>{switch(e.op){case"NonMaxSuppressionV5":{const{boxes:r,scores:s,maxOutputSize:o,iouThreshold:i,scoreThreshold:u,softNmsSigma:l}=Pf(e,t,n),c=await a.image.nonMaxSuppressionWithScoreAsync(r,s,o,i,u,l);return[c.selectedIndices,c.selectedScores]}case"NonMaxSuppressionV4":{const{boxes:r,scores:s,maxOutputSize:o,iouThreshold:i,scoreThreshold:u}=Pf(e,t,n),l=Lh("padToMaxOutputSize",e,t,n),c=await a.image.nonMaxSuppressionPaddedAsync(r,s,o,i,u,l);return[c.selectedIndices,c.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{const{boxes:r,scores:s,maxOutputSize:o,iouThreshold:i,scoreThreshold:u}=Pf(e,t,n);return[await a.image.nonMaxSuppressionAsync(r,s,o,i,u)]}case"Where":{const r=a.cast(Lh("condition",e,t,n),"bool"),s=[await a.whereAsync(r)];return r.dispose(),s}case"ListDiff":return a.setdiff1dAsync(Lh("x",e,t,n),Lh("y",e,t,n));default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n);case"evaluation":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"LowerBound":{const a=Lh("sortedSequence",e,t,n),s=Lh("values",e,t,n);return[r.lowerBound(a,s)]}case"TopKV2":{const a=Lh("x",e,t,n),s=Lh("k",e,t,n),o=Lh("sorted",e,t,n),i=r.topk(a,s,o);return[i.values,i.indices]}case"UpperBound":{const a=Lh("sortedSequence",e,t,n),s=Lh("values",e,t,n);return[r.upperBound(a,s)]}case"Unique":{const a=Lh("x",e,t,n),s=r.unique(a);return[s.values,s.indices]}case"UniqueV2":{const a=Lh("x",e,t,n),s=Lh("axis",e,t,n),o=r.unique(a,s);return[o.values,o.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"image":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"ResizeBilinear":{const a=Lh("images",e,t,n),s=Lh("size",e,t,n),o=Lh("alignCorners",e,t,n),i=Lh("halfPixelCenters",e,t,n);return[r.image.resizeBilinear(a,[s[0],s[1]],o,i)]}case"ResizeNearestNeighbor":{const a=Lh("images",e,t,n),s=Lh("size",e,t,n),o=Lh("alignCorners",e,t,n),i=Lh("halfPixelCenters",e,t,n);return[r.image.resizeNearestNeighbor(a,[s[0],s[1]],o,i)]}case"CropAndResize":{const a=Lh("image",e,t,n),s=Lh("boxes",e,t,n),o=Lh("boxInd",e,t,n),i=Lh("cropSize",e,t,n),u=Lh("method",e,t,n),l=Lh("extrapolationValue",e,t,n);return[r.image.cropAndResize(a,s,o,i,u,l)]}case"ImageProjectiveTransformV3":{const a=Lh("images",e,t,n),s=Lh("transforms",e,t,n),o=Lh("outputShape",e,t,n),i=Lh("fillValue",e,t,n),u=Lh("interpolation",e,t,n),l=Lh("fillMode",e,t,n);return[r.image.transform(a,s,u.toLowerCase(),l.toLowerCase(),i,o)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"graph":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":const a=Lh("default",e,t,n);return[Bh(e.name,t,n)||a];case"Placeholder":return[Bh(e.name,t,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":case"Snapshot":return[Hh(Lh("x",e,t,n))];case"IdentityN":return Lh("x",e,t,n).map(e=>Hh(e));case"Shape":return[r.tensor1d(Lh("x",e,t,n).shape,"int32")];case"ShapeN":return Lh("x",e,t,n).map(e=>r.tensor1d(e.shape));case"Size":return[r.scalar(Lh("x",e,t,n).size,"int32")];case"Rank":return[r.scalar(Lh("x",e,t,n).rank,"int32")];case"NoOp":return[r.scalar(1)];case"Print":const s=Lh("x",e,t,n),o=Lh("data",e,t,n),i=Lh("message",e,t,n),u=Lh("summarize",e,t,n);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(i);for(let e=0;e((e,t,n,r=$f)=>{switch(e.op){case"Equal":return[r.equal(Lh("a",e,t,n),Lh("b",e,t,n))];case"NotEqual":return[r.notEqual(Lh("a",e,t,n),Lh("b",e,t,n))];case"Greater":return[r.greater(Lh("a",e,t,n),Lh("b",e,t,n))];case"GreaterEqual":return[r.greaterEqual(Lh("a",e,t,n),Lh("b",e,t,n))];case"Less":return[r.less(Lh("a",e,t,n),Lh("b",e,t,n))];case"LessEqual":return[r.lessEqual(Lh("a",e,t,n),Lh("b",e,t,n))];case"LogicalAnd":return[r.logicalAnd(Lh("a",e,t,n),Lh("b",e,t,n))];case"LogicalNot":return[r.logicalNot(Lh("a",e,t,n))];case"LogicalOr":return[r.logicalOr(Lh("a",e,t,n),Lh("b",e,t,n))];case"Select":case"SelectV2":return[r.where(Lh("condition",e,t,n),Lh("a",e,t,n),Lh("b",e,t,n))];case"BitwiseAnd":return[r.bitwiseAnd(Lh("a",e,t,n),Lh("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"matrices":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[r.matMul(Lh("a",e,t,n),Lh("b",e,t,n),Lh("transposeA",e,t,n),Lh("transposeB",e,t,n))];case"Einsum":return[r.einsum(Lh("equation",e,t,n),...Lh("tensors",e,t,n))];case"Transpose":return[r.transpose(Lh("x",e,t,n),Lh("perm",e,t,n))];case"_FusedMatMul":const[a,s]=Lh("fusedOps",e,t,n),o="biasadd"===a,i="prelu"===s,u=Lh("numArgs",e,t,n),l=Lh("leakyreluAlpha",e,t,n);if(o){if(i&&2!==u)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!i&&1!==u)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}const[c,d]=Lh("args",e,t,n);return[r.fused.matMul({a:Lh("a",e,t,n),b:Lh("b",e,t,n),transposeA:Lh("transposeA",e,t,n),transposeB:Lh("transposeB",e,t,n),bias:c,activation:s,preluActivationWeights:d,leakyreluAlpha:l})];case"MatrixBandPart":return[r.linalg.bandPart(Lh("a",e,t,n),Lh("numLower",e,t,n),Lh("numUpper",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"normalization":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"EuclideanNorm":return[r.euclideanNorm(Lh("x",e,t,n),Lh("axis",e,t,n),Lh("keepDims",e,t,n))];case"FusedBatchNorm":case"FusedBatchNormV2":case"FusedBatchNormV3":return[r.batchNorm(Lh("x",e,t,n),Lh("mean",e,t,n),Lh("variance",e,t,n),Lh("offset",e,t,n),Lh("scale",e,t,n),Lh("epsilon",e,t,n))];case"LRN":return[r.localResponseNormalization(Lh("x",e,t,n),Lh("radius",e,t,n),Lh("bias",e,t,n),Lh("alpha",e,t,n),Lh("beta",e,t,n))];case"Softmax":return[r.softmax(Lh("x",e,t,n))];case"LogSoftmax":return[r.logSoftmax(Lh("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"ragged":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"RaggedGather":{const{outputNestedSplits:a,outputDenseValues:s}=r.raggedGather(Lh("paramsNestedSplits",e,t,n),Lh("paramsDenseValues",e,t,n),Lh("indices",e,t,n),Lh("outputRaggedRank",e,t,n));return a.concat(s)}case"RaggedRange":{const{rtNestedSplits:a,rtDenseValues:s}=r.raggedRange(Lh("starts",e,t,n),Lh("limits",e,t,n),Lh("splits",e,t,n));return[a,s]}case"RaggedTensorToTensor":return[r.raggedTensorToTensor(Lh("shape",e,t,n),Lh("values",e,t,n),Lh("defaultValue",e,t,n),Lh("rowPartitionTensors",e,t,n),Lh("rowPartitionTypes",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"reduction":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"Max":{const a=Lh("axis",e,t,n),s=Lh("keepDims",e,t,n);return[r.max(Lh("x",e,t,n),a,s)]}case"Mean":{const a=Lh("axis",e,t,n),s=Lh("keepDims",e,t,n);return[r.mean(Lh("x",e,t,n),a,s)]}case"Min":{const a=Lh("axis",e,t,n),s=Lh("keepDims",e,t,n);return[r.min(Lh("x",e,t,n),a,s)]}case"Sum":{const a=Lh("axis",e,t,n),s=Lh("keepDims",e,t,n);return[r.sum(Lh("x",e,t,n),a,s)]}case"All":{const a=Lh("axis",e,t,n),s=Lh("keepDims",e,t,n);return[r.all(Lh("x",e,t,n),a,s)]}case"Any":{const a=Lh("axis",e,t,n),s=Lh("keepDims",e,t,n);return[r.any(Lh("x",e,t,n),a,s)]}case"ArgMax":{const a=Lh("axis",e,t,n);return[r.argMax(Lh("x",e,t,n),a)]}case"ArgMin":{const a=Lh("axis",e,t,n);return[r.argMin(Lh("x",e,t,n),a)]}case"Prod":{const a=Lh("axis",e,t,n),s=Lh("keepDims",e,t,n);return[r.prod(Lh("x",e,t,n),a,s)]}case"Cumprod":{const a=Lh("axis",e,t,n),s=Lh("exclusive",e,t,n),o=Lh("reverse",e,t,n);return[r.cumprod(Lh("x",e,t,n),a,s,o)]}case"Cumsum":{const a=Lh("axis",e,t,n),s=Lh("exclusive",e,t,n),o=Lh("reverse",e,t,n);return[r.cumsum(Lh("x",e,t,n),a,s,o)]}case"Bincount":const a=Lh("x",e,t,n),s=Lh("weights",e,t,n),o=Lh("size",e,t,n);return[r.bincount(a,s,o)];case"DenseBincount":{const a=Lh("x",e,t,n),s=Lh("weights",e,t,n),o=Lh("size",e,t,n),i=Lh("binaryOutput",e,t,n);return[r.denseBincount(a,s,o,i)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"slice_join":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"ConcatV2":case"Concat":{const a=Lh("n",e,t,n),s=Lh("axis",e,t,n);let o=Lh("tensors",e,t,n);return o=o.slice(0,a),[r.concat(o,s)]}case"Gather":{const a=Lh("x",e,t,n),s=Lh("indices",e,t,n);return[r.gather(a,r.cast(s,"int32"),0)]}case"GatherV2":{const a=Lh("axis",e,t,n),s=Lh("batchDims",e,t,n),o=Lh("x",e,t,n),i=Lh("indices",e,t,n);return[r.gather(o,r.cast(i,"int32"),a,s)]}case"Reverse":{const a=Lh("dims",e,t,n),s=[];for(let e=0;e{const a=Lh("axis",e,t,n),s=Lh("tensors",e,t,n),o=s[0].shape,i=r.squeeze(s[0]).shape,u=s.map(e=>{const t=d(e.shape,o);if(!t&&!d(r.squeeze(e).shape,i))throw new Error("the input tensors shape does not match");return t?e:r.reshape(e,o)});return[r.stack(u,a)]});case"Unpack":{const a=Lh("axis",e,t,n),s=Lh("tensor",e,t,n);return r.unstack(s,a)}case"Tile":{const a=Lh("reps",e,t,n);return[r.tile(Lh("x",e,t,n),a)]}case"Split":case"SplitV":{const a=Lh("axis",e,t,n),s=Lh("numOrSizeSplits",e,t,n),o=Lh("x",e,t,n);return r.split(o,s,a)}case"ScatterNd":{const a=Lh("indices",e,t,n),s=Lh("values",e,t,n),o=Lh("shape",e,t,n);return[r.scatterND(a,s,o)]}case"GatherNd":{const a=Lh("x",e,t,n),s=Lh("indices",e,t,n);return[r.gatherND(a,s)]}case"SparseToDense":{const a=Lh("sparseIndices",e,t,n),s=Lh("outputShape",e,t,n),o=Lh("sparseValues",e,t,n),i=Lh("defaultValue",e,t,n);return[r.sparseToDense(a,o,s,o.dtype===i.dtype?i:r.cast(i,o.dtype))]}case"TensorScatterUpdate":{const a=Lh("indices",e,t,n),s=Lh("values",e,t,n),o=Lh("tensor",e,t,n);return[r.tensorScatterUpdate(o,a,s)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"sparse":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"SparseFillEmptyRows":{const{outputIndices:a,outputValues:s,emptyRowIndicator:o,reverseIndexMap:i}=r.sparse.sparseFillEmptyRows(Lh("indices",e,t,n),Lh("values",e,t,n),Lh("denseShape",e,t,n),Lh("defaultValue",e,t,n));return[a,s,o,i]}case"SparseReshape":{const{outputIndices:a,outputShape:s}=r.sparse.sparseReshape(Lh("inputIndices",e,t,n),Lh("inputShape",e,t,n),Lh("newShape",e,t,n));return[a,s]}case"SparseSegmentMean":return[r.sparse.sparseSegmentMean(Lh("data",e,t,n),Lh("indices",e,t,n),Lh("segmentIds",e,t,n))];case"SparseSegmentSum":return[r.sparse.sparseSegmentSum(Lh("data",e,t,n),Lh("indices",e,t,n),Lh("segmentIds",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"spectral":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"FFT":return[r.fft(Lh("x",e,t,n))];case"IFFT":return[r.ifft(Lh("x",e,t,n))];case"RFFT":return[r.rfft(Lh("x",e,t,n))];case"IRFFT":return[r.irfft(Lh("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"string":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"StaticRegexReplace":return[r.string.staticRegexReplace(Lh("input",e,t,n),Lh("pattern",e,t,n),Lh("rewrite",e,t,n),Lh("replaceGlobal",e,t,n))];case"StringNGrams":{const{nGrams:a,nGramsSplits:s}=r.string.stringNGrams(Lh("data",e,t,n),Lh("dataSplits",e,t,n),Lh("separator",e,t,n),Lh("nGramWidths",e,t,n),Lh("leftPad",e,t,n),Lh("rightPad",e,t,n),Lh("padWidth",e,t,n),Lh("preserveShortSequences",e,t,n));return[a,s]}case"StringSplit":{const{indices:a,values:s,shape:o}=r.string.stringSplit(Lh("input",e,t,n),Lh("delimiter",e,t,n),Lh("skipEmpty",e,t,n));return[a,s,o]}case"StringToHashBucketFast":return[r.string.stringToHashBucketFast(Lh("input",e,t,n),Lh("numBuckets",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"transformation":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"Cast":return[r.cast(Lh("x",e,t,n),Lh("dtype",e,t,n))];case"ExpandDims":{const a=Lh("axis",e,t,n);return[r.expandDims(Lh("x",e,t,n),a)]}case"Squeeze":{const a=Lh("axis",e,t,n);return[r.squeeze(Lh("x",e,t,n),a)]}case"Reshape":return[r.reshape(Lh("x",e,t,n),Lh("shape",e,t,n))];case"EnsureShape":return[r.ensureShape(Lh("x",e,t,n),Lh("shape",e,t,n))];case"MirrorPad":return[r.mirrorPad(Lh("x",e,t,n),Lh("padding",e,t,n),Lh("mode",e,t,n))];case"PadV2":case"Pad":return[r.pad(Lh("x",e,t,n),Lh("padding",e,t,n),Lh("constantValue",e,t,n))];case"SpaceToBatchND":{const a=Lh("blockShape",e,t,n),s=Lh("paddings",e,t,n);return[r.spaceToBatchND(Lh("x",e,t,n),a,s)]}case"BatchToSpaceND":{const a=Lh("blockShape",e,t,n),s=Lh("crops",e,t,n);return[r.batchToSpaceND(Lh("x",e,t,n),a,s)]}case"DepthToSpace":{const a=Lh("blockSize",e,t,n),s=Lh("dataFormat",e,t,n).toUpperCase();return[r.depthToSpace(Lh("x",e,t,n),a,s)]}case"BroadcastTo":return[r.broadcastTo(Lh("x",e,t,n),Lh("shape",e,t,n))];case"BroadcastArgs":return[r.broadcastArgs(Lh("s0",e,t,n),Lh("s1",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"hash_table":return(async(e,t,n,r)=>{switch(e.op){case"HashTable":case"HashTableV2":{const a=r.getHashTableHandleByName(e.name);if(null!=a)return[a];{const a=Lh("keyDType",e,t,n),s=Lh("valueDType",e,t,n),o=new Lf(a,s);return r.addHashTable(e.name,o),[o.handle]}}case"InitializeTable":case"InitializeTableV2":case"LookupTableImport":case"LookupTableImportV2":{const a=Lh("tableHandle",e,t,n,r),s=Lh("keys",e,t,n),o=Lh("values",e,t,n),i=r.getHashTableById(a.id);return[await i.import(s,o)]}case"LookupTableFind":case"LookupTableFindV2":{const a=Lh("tableHandle",e,t,n,r),s=Lh("keys",e,t,n),o=Lh("defaultValue",e,t,n),i=r.getHashTableById(a.id);return[await i.find(s,o)]}case"LookupTableSize":case"LookupTableSizeV2":{const a=Lh("tableHandle",e,t,n,r);return[r.getHashTableById(a.id).tensorSize()]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n,r);case"custom":const s=Ph(e.op);if(s&&s.customExecutor)return s.customExecutor(new Cf(e,t,n));throw TypeError(`Custom op ${e.op} is not registered.`);default:throw TypeError(`Unknown op '${e.op}'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()`)}})(e,t,n);return M(s)?s.then(e=>[].concat(e)):[].concat(s)}class Vf{constructor(e={},t={},n={},r={},a){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=n,this.functionMap=r,this.parseNodeNameCache=a,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds()}newFrame(e,t){return{id:e,frameName:t,iterationId:0}}set currentContext(e){this.contexts!==e&&(this.contexts=e,this.generateCurrentContextIds())}get currentContext(){return this.contexts}get currentContextId(){return this._currentContextIds[0]}get currentContextIds(){return this._currentContextIds}generateCurrentContextIds(){const e=[];for(let t=0;t0===e.id&&0===e.iterationId?"":`${e.frameName}-${e.iterationId}`).join("/"):""}enterFrame(e){this.contexts&&(this.lastId++,this.contexts=this.contexts.slice(),this.contexts.push(this.newFrame(this.lastId,e)),this._currentContextIds.unshift(this.contextIdforContexts(this.contexts)))}exitFrame(){if(!(this.contexts&&this.contexts.length>1))throw new Error("Cannot exit frame, the context is empty");this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift()}nextIteration(){if(!(this.contexts&&this.contexts.length>0))throw new Error("Cannot increase frame iteration, the context is empty");{this.contexts=this.contexts.slice(),this.lastId++;const e=Object.assign({},this.contexts[this.contexts.length-1]);e.iterationId+=1,e.id=this.lastId,this.contexts.splice(-1,1,e),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))}}getWeight(e){return this.weightMap[e]}addTensorArray(e){this.tensorArrayMap[e.id]=e}getTensorArray(e){return this.tensorArrayMap[e]}addTensorList(e){this.tensorListMap[e.id]=e}getTensorList(e){return this.tensorListMap[e]}dispose(e){for(const t in this.tensorArrayMap)this.tensorArrayMap[t].clearAndClose(e);for(const t in this.tensorListMap)this.tensorListMap[t].clearAndClose(e)}}function Wf(e,t,n,r){const a=/* @__PURE__ */new Set,s=[];let o=null,i=null;const u=/* @__PURE__ */new Set,l=new Set(Object.keys(e).map(e=>Uh(e)[0]));r=r||[];const c=new Set(r.map(e=>Uh(e.name)[0])),d=[...t];for(;d.length>0;){const e=d.pop();(qf(e)||Kf(e)||Xf(e))&&null==o&&(o=e,i=o.children.map(e=>e.name).filter(e=>a.has(e))),a.add(e.name),null==n[e.name]&&(l.has(e.name)||c.has(e.name)||(0!==e.inputs.length?e.inputs.forEach(e=>{u.has(e.name)||(u.add(e.name),d.push(e))}):s.push(e.name)))}return{inputs:e,outputs:t,usedNodes:a,missingInputs:s,dynamicNode:o,syncInputs:i}}function zf(e,t){const{usedNodes:n,inputs:r}=t,a=Object.keys(r).map(e=>Uh(e)[0]).map(t=>e.nodes[t]),s=e.initNodes||[],o=e=>n.has("string"===typeof e?e:e.name);function i(e){return[...new Map(e.map(e=>[e.name,e])).values()]}const u=i([...a,...e.weights,...s]).filter(o),l=i([...u,...Object.values(e.nodes)]).filter(o),c=new Map(l.map(e=>[e.name,e])),d={};for(const m of l){d[m.name]=d[m.name]||0;for(const e of m.children)o(e)||(d[e.name]=Number.POSITIVE_INFINITY),d[e.name]=(d[e.name]||0)+1}const p=Object.entries(d).filter(([,e])=>0===e).map(([e])=>e),h=[...p];for(;p.length>0;){const e=p.pop(),t=c.get(e);for(const n of t.children.filter(o))0===--d[n.name]&&(h.push(n.name),p.push(n.name))}const f=function(e,t){const n=new Map(e.map(e=>[e.name,e])),r=t.map(e=>e.name),a=new Set(r);for(;r.length>0;){const e=r.pop(),t=n.get(e);for(const s of t.children)n.has(s.name)&&!a.has(s.name)&&(a.add(s.name),r.push(s.name))}const s=e.filter(e=>a.has(e.name));return s}(h.map(e=>c.get(e)),u);return function(e,t){const n=new Map(e.map((e,t)=>[e.name,t])),r=new Set(t.map(e=>e.name)),a=e=>r.has("string"===typeof e?e:e.name),s=new Set(e.map(e=>e.name)),o=e=>s.has("string"===typeof e?e:e.name);for(const i of e){for(const e of i.children.filter(o)){if(!n.has(e.name))throw new Uf(`Child ${e.name} of node ${i.name} is unreachable.`);if(n.get(i.name)>n.get(e.name))throw new Uf(`Node ${i.name} is scheduled to run after its child ${e.name}.`)}if(!a(i))for(const e of i.inputs){if(!n.has(e.name))throw new Uf(`Input ${e.name} of node ${i.name} is unreachable.`);if(n.get(e.name)>n.get(i.name))throw new Uf(`Node ${i.name} is scheduled to run before its input ${e.name}.`)}}}(f,u),f}class Uf extends Error{constructor(e){super(`NodesExecutionOrderError: ${e}`)}}const Gf=/* @__PURE__ */new Set(["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"]),Hf=/* @__PURE__ */new Set(["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"]),jf=/* @__PURE__ */new Set(["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"]);function qf(e){return Gf.has(e.op)}function Kf(e){return Hf.has(e.op)}function Xf(e){return jf.has(e.op)}class Yf{get weightIds(){return this.parent?this.parent.weightIds:this._weightIds}get functionExecutorMap(){return this.parent?this.parent.functionExecutorMap:this._functionExecutorMap}get weightMap(){return this.parent?this.parent.weightMap:this._weightMap}set weightMap(e){const t=Object.keys(e).map(t=>e[t].map(e=>e.id));this._weightIds=[].concat(...t),this._weightMap=e}set resourceManager(e){this._resourceManager=e}get inputs(){return this._inputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get outputs(){return this._outputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get inputNodes(){return this._inputs.map(e=>e.signatureKey||e.name)}get outputNodes(){return this._outputs.map(e=>{const t=e.signatureKey||e.name;return e.defaultOutput?`${t}:${e.defaultOutput}`:t})}get functions(){return Object.keys(this._functions).reduce((e,t)=>(e[t]=this._functions[t].signature,e),{})}constructor(e,t){this.graph=e,this.parent=t,this.compiledMap=/* @__PURE__ */new Map,this.parseNodeNameCache=/* @__PURE__ */new Map,this._weightMap={},this.SEPARATOR=",",this._functions={},this._functionExecutorMap={},this.keepIntermediateTensors=!1,this._outputs=e.outputs,this._inputs=e.inputs,this._initNodes=e.initNodes,this._signature=e.signature,this._functions=e.functions,null!=e.functions&&Object.keys(e.functions).forEach(t=>{this._functionExecutorMap[t]=new Yf(e.functions[t],this)})}getCompilationKey(e,t){const n=e.map(e=>e.name).sort(),r=t.map(e=>e.name).sort();return n.join(this.SEPARATOR)+"--"+r.join(this.SEPARATOR)}compile(e,t){const n=Wf(e,t,this.weightMap,this._initNodes),{missingInputs:r,dynamicNode:a,syncInputs:s}=n;if(null!=a)throw new Error(`This execution contains the node '${a.name}', which has the dynamic op '${a.op}'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs [${s}]`);if(r.length>0){const n=t.map(e=>e.name),a=Object.keys(e);throw new Error(`Cannot compute the outputs [${n}] from the provided inputs [${a}]. Missing the following inputs: [${r}]`)}const o=zf(this.graph,n),i=function(e){const t=new Map(e.map((e,t)=>[e.name,t])),n=Number.MAX_SAFE_INTEGER,r=e.map((e,t)=>qf(e)?n:t),a=e=>r[t.get(e.name)]??-1,s=e.map((e,t)=>e.children.map(a).reduce((e,t)=>Math.max(e,t),r[t])),o=/* @__PURE__ */new Map;for(let i=0;ithis.cloneAndKeepTensor(e))}cloneTensorMap(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,this.cloneTensorList(t)]))}execute(e,t){this.disposeIntermediateTensors(),e=this.mapInputs(e);const n=Object.keys(e).sort();this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t);const r=n.map(e=>this.graph.nodes[Uh(e)[0]]),a=t.map(e=>Uh(e)[0]),s=new Set(a);let o=a.map(e=>this.graph.nodes[e]);0===o.length&&(o=this._outputs);const i=this.getCompilationKey(r,o);let u=this.compiledMap.get(i);null==u&&(u=this.compile(e,o),this.compiledMap.set(i,u));try{this.keepIntermediateTensors=V().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(d){this.keepIntermediateTensors=!1,console.warn(d.message)}const l={},c={};return Ba(()=>{const n=new Vf(this.weightMap,l,c,this.functionExecutorMap,this.parseNodeNameCache),r=Object.assign({},this.weightMap);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap)),Object.keys(e).forEach(t=>{const[a,s]=Uh(t,n),o=[];o[s]=e[t],r[a]=o,this.keepIntermediateTensors&&(this.clonedTensorsMap[a]=this.cloneTensorList(o))});const a=this.getFrozenTensorIds(r),{orderedNodes:o,nodeLiveUntilMap:i}=u;for(const e of o){if(r[e.name])continue;const t=Bf(e,r,n,this._resourceManager);if(M(t))throw new Error(`The execution of the op '${e.op}' returned a promise. Please use model.executeAsync() instead.`);r[e.name]=t,this.keepIntermediateTensors&&(this.clonedTensorsMap[e.name]=this.cloneTensorList(t)),this.checkTensorForDisposalWithNodeLiveUntilInfo(e,r,n,a,s,i.get(e.name))}return null==this.parent&&n.dispose(a),t.map(e=>Bh(e,r,n))})}getFrozenTensorIds(e){const t=[].concat.apply([],Object.keys(e).map(t=>e[t]).map(e=>e.map(e=>e.id)));return new Set(t)}checkTensorForDisposal(e,t,n,r,a,s,o){if(!qf(t)&&!s.has(e)){for(const r of n[e])null!=r&&(o[r.id]=(o[r.id]||0)+t.children.length);for(const e of t.inputs){if(qf(e))continue;const t=Vh(e.name,n,r);if(null!=t)for(const e of t){if(!e||e.kept||a.has(e.id))continue;const t=o[e.id];1===t?(e.dispose(),delete o[e.id]):null!=t&&o[e.id]--}}}}checkTensorForDisposalWithNodeLiveUntilInfo(e,t,n,r,a,s){function o(e){return qf(e)||a.has(e.name)}if(!qf(e)&&null!=s)for(const i of s){if(o(i))continue;const e=Vh(i.name,t,n);for(const t of e)!t||t.kept||r.has(t.id)||t.dispose()}}async executeAsync(e,t){return this._executeAsync(e,t)}disposeIntermediateTensors(){this.clonedTensorsMap&&(Object.values(this.clonedTensorsMap).forEach(e=>{for(const t of e)t&&!t.isDisposed&&t.dispose()}),this.clonedTensorsMap=null)}getIntermediateTensors(){return this.clonedTensorsMap}async _executeAsync(e,t,n=!1,r={},a={}){this.disposeIntermediateTensors(),n||(e=this.mapInputs(e),this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t));try{this.keepIntermediateTensors=V().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(d){this.keepIntermediateTensors=!1,console.warn(d.message)}const s=new Vf(this.weightMap,r,a,this.functionExecutorMap,this.parseNodeNameCache);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap));const o=await this.executeWithControlFlow(e,s,t,n),i=t.map(e=>Bh(e,o,s)),u=i.map(e=>e.id),l=Object.keys(e).map(t=>e[t].id),c=/* @__PURE__ */new Set([...u,...l,...this.weightIds]);return Object.values(o).forEach(e=>{e.forEach(e=>{!e||e.isDisposed||c.has(e.id)||e.dispose()})}),null==this.parent&&s.dispose(c),i}async executeFunctionAsync(e,t,n){const r=e.reduce((e,t,n)=>(e[this.inputs[n].name]=t,e),{});return this._executeAsync(r,this.outputNodes,!0,t,n)}async executeWithControlFlow(e,t,n,r){const a=Object.keys(e),s=a.map(e=>this.graph.nodes[Uh(e)[0]]),o=n.map(e=>Uh(e)[0]),i=new Set(o);let u=o.map(e=>this.graph.nodes[e]);0===u.length&&(u=this._outputs);const{usedNodes:l,missingInputs:c,dynamicNode:d,syncInputs:p}=Wf(e,u,this.weightMap,this._initNodes),h=[...s,...this.graph.weights,...this._initNodes||[]].map(e=>({node:e,contexts:t.currentContext})),f=Object.assign({},this.weightMap);Object.keys(e).forEach(t=>{const[n,r]=Uh(t),a=[];a[r]=e[t],f[n]=a});const m={},g=this.getFrozenTensorIds(f),y={};for(;h.length>0;){const e=this.processStack(s,h,t,f,y,g,i,m,l);await Promise.all(e)}null!=d||r||console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");const b=u.filter(e=>!qf(e)&&!Bh(e.name,f,t)).map(e=>e.name);if(b.length>0){let e="";throw null!=d&&(e=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${p}]`),new Error(`Cannot compute the outputs [${b}] from the provided inputs [${a}]. Consider providing the following inputs: [${c}]. ${e}`)}return f}processStack(e,t,n,r,a,s,o,i,u){const l=[];for(;t.length>0;){const e=t.pop();n.currentContext=e.contexts;let c="";if("Enter"===e.node.op&&Lh("isConstant",e.node,r,n)&&([c]=Wh(e.node.name,n)),null==r[e.node.name]){const d=Bf(e.node,r,n,this._resourceManager);c||([c]=Wh(e.node.name,n));const p=n.currentContext;M(d)?l.push(d.then(l=>(r[c]=l,this.keepIntermediateTensors&&(this.clonedTensorsMap[c]=this.cloneTensorList(l)),n.currentContext=p,this.checkTensorForDisposal(c,e.node,r,n,s,o,i),this.processChildNodes(e.node,t,n,r,a,u),l))):(r[c]=d,this.keepIntermediateTensors&&(this.clonedTensorsMap[c]=this.cloneTensorList(d)),this.checkTensorForDisposal(c,e.node,r,n,s,o,i),this.processChildNodes(e.node,t,n,r,a,u))}else this.processChildNodes(e.node,t,n,r,a,u)}return l}processChildNodes(e,t,n,r,a,s){e.children.forEach(e=>{const[o]=Wh(e.name,n);!a[o]&&s.has(e.name)&&("Merge"===e.op?e.inputNames.some(e=>!!Bh(e,r,n))&&(a[o]=!0,t.push({contexts:n.currentContext,node:e})):e.inputNames.every(e=>!!Bh(e,r,n))&&(a[o]=!0,t.push({contexts:n.currentContext,node:e})))})}dispose(){Object.keys(this.weightMap).forEach(e=>this.weightMap[e].forEach(e=>e.dispose()))}checkInputShapeAndType(e){Object.keys(e).forEach(t=>{const n=e[t],[r]=Uh(t),a=this.graph.nodes[r];if(a.attrParams.shape&&a.attrParams.shape.value){const e=a.attrParams.shape.value;i(e.length===n.shape.length&&n.shape.every((t,n)=>-1===e[n]||e[n]===t),()=>`The shape of dict['${a.name}'] provided in model.execute(dict) must be [${e}], but was [${n.shape}]`)}a.attrParams.dtype&&a.attrParams.dtype.value&&i(n.dtype===a.attrParams.dtype.value,()=>`The dtype of dict['${a.name}'] provided in model.execute(dict) must be ${a.attrParams.dtype.value}, but was ${n.dtype}`)})}mapInputs(e){var t,n;const r={};for(const a in e){const s=null===(n=null===(t=this._signature)||void 0===t?void 0:t.inputs)||void 0===n?void 0:n[a];null!=s?r[s.name]=e[a]:r[a]=e[a]}return r}checkInputs(e){const t=Object.keys(e).filter(e=>{const[t]=Uh(e);return null==this.graph.nodes[t]});if(t.length>0)throw new Error(`The dict provided in model.execute(dict) has keys: [${t}] that are not part of graph`)}mapOutputs(e){return e.map(e=>{var t,n;const r=null===(n=null===(t=this._signature)||void 0===t?void 0:t.outputs)||void 0===n?void 0:n[e];return null!=r?r.name:e},{})}checkOutputs(e){e.forEach(e=>{const[t]=Uh(e);if(!this.graph.nodes[t])throw new Error(`The output '${e}' is not found in the graph`)})}}class Qf{constructor(e={},t={}){this.hashTableNameToHandle=e,this.hashTableMap=t}addHashTable(e,t){this.hashTableNameToHandle[e]=t.handle,this.hashTableMap[t.id]=t}getHashTableHandleByName(e){return this.hashTableNameToHandle[e]}getHashTableById(e){return this.hashTableMap[e]}dispose(){for(const e in this.hashTableMap)this.hashTableMap[e].clearAndClose(),delete this.hashTableMap[e];for(const e in this.hashTableNameToHandle)this.hashTableNameToHandle[e].dispose(),delete this.hashTableNameToHandle[e]}}const Zf="?tfjs-format=file",Jf="model.json";class em{get modelVersion(){return this.version}get inputNodes(){return this.executor.inputNodes}get outputNodes(){return this.executor.outputNodes}get inputs(){return this.executor.inputs}get outputs(){return this.executor.outputs}get weights(){return this.executor.weightMap}get metadata(){return this.artifacts.userDefinedMetadata}get modelSignature(){return this.signature}get modelStructuredOutputKeys(){return this.structuredOutputKeys}constructor(e,t={},n=mp){this.modelUrl=e,this.loadOptions=t,this.version="n/a",this.io=n,null==t&&(this.loadOptions={}),this.resourceManager=new Qf}findIOHandler(){const e=this.modelUrl;if(null!=e.load)this.handler=e;else if(null!=this.loadOptions.requestInit)this.handler=this.io.browserHTTPRequest(e,this.loadOptions);else{const t=this.io.getLoadHandlers(e,this.loadOptions);if(0===t.length)t.push(this.io.browserHTTPRequest(e,this.loadOptions));else if(t.length>1)throw new Error(`Found more than one (${t.length}) load handlers for URL '${[e]}'`);this.handler=t[0]}}load(){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.");const e=this.handler.load();return M(e)?e.then(e=>null==e.getWeightStream?this.loadSync(e):this.loadStreaming(e)):this.loadSync(e)}loadSync(e){const t=this.io.decodeWeights(e.weightData,e.weightSpecs);return this.loadWithWeightMap(e,t)}async loadStreaming(e){if(null==e.getWeightStream)throw new Error("Model artifacts missing streamWeights function");const t=await Qa(e.getWeightStream(),e.weightSpecs);return this.loadWithWeightMap(e,t)}loadWithWeightMap(e,t){this.artifacts=e;const n=this.artifacts.modelTopology;let r=this.artifacts.signature;if(null!=this.artifacts.userDefinedMetadata){const e=this.artifacts.userDefinedMetadata;null!=e.signature&&(r=e.signature),null!=e.structuredOutputKeys&&(this.structuredOutputKeys=e.structuredOutputKeys)}if(this.signature=r,this.version=`${n.versions.producer}.${n.versions.minConsumer}`,this.executor=new Yf(pf.Instance.transformGraph(n,this.signature)),this.executor.weightMap=this.convertTensorMapToTensorsMap(t),this.executor.resourceManager=this.resourceManager,null!=e.modelInitializer&&null!=e.modelInitializer.node){const t=pf.Instance.transformGraph(e.modelInitializer);this.initializer=new Yf(t),this.initializer.weightMap=this.executor.weightMap,this.initializer.resourceManager=this.resourceManager,this.initializerSignature=e.initializerSignature}return!0}async save(e,t){if("string"===typeof e){const t=this.io.getSaveHandlers(e);if(0===t.length)throw new Error(`Cannot find any save handlers for URL '${e}'`);if(t.length>1)throw new Error(`Found more than one (${t.length}) save handlers for URL '${e}'`);e=t[0]}if(null==e.save)throw new Error("GraphModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return e.save(this.artifacts)}addStructuredOutputNames(e){if(this.structuredOutputKeys){const t={};return(e instanceof Yr?[e]:e).forEach((e,n)=>t[this.structuredOutputKeys[n]]=e),t}return e}predict(e,t){const n=this.execute(e,this.outputNodes);return this.addStructuredOutputNames(n)}async predictAsync(e,t){const n=await this.executeAsync(e,this.outputNodes);return this.addStructuredOutputNames(n)}normalizeInputs(e){var t;if(!(e instanceof Yr)&&!Array.isArray(e)){const n=null===(t=this.signature)||void 0===t?void 0:t.inputs;if(null!=n)for(const t in n){const r=n[t];null!=r.resourceId&&(e[t]=this.resourceIdToCapturedInput[r.resourceId])}return e}e=Array.isArray(e)?e:[e];const n=Object.keys(this.resourceIdToCapturedInput).length;if(e.length+n!==this.inputNodes.length)throw new Error(`Input tensor count mismatch, the graph model has ${this.inputNodes.length-n} non-resource placeholders, while there are ${e.length} input tensors provided.`);let r=0;return this.inputNodes.reduce((t,n)=>{var a,s,o;const i=null===(o=null===(s=null===(a=this.signature)||void 0===a?void 0:a.inputs)||void 0===s?void 0:s[n])||void 0===o?void 0:o.resourceId;return t[n]=null!=i?this.resourceIdToCapturedInput[i]:e[r++],t},{})}normalizeOutputs(e){return e=e||this.outputNodes,Array.isArray(e)?e:[e]}executeInitializerGraph(){return null==this.initializer?[]:null==this.initializerSignature?this.initializer.execute({},[]):this.initializer.execute({},Object.keys(this.initializerSignature.outputs))}async executeInitializerGraphAsync(){return null==this.initializer?[]:null==this.initializerSignature?this.initializer.executeAsync({},[]):this.initializer.executeAsync({},Object.keys(this.initializerSignature.outputs))}setResourceIdToCapturedInput(e){if(this.resourceIdToCapturedInput={},this.initializerSignature){const t=this.initializerSignature.outputs,n=Object.keys(t);for(let r=0;r1?n:n[0]}async executeAsync(e,t){null==this.resourceIdToCapturedInput&&this.setResourceIdToCapturedInput(await this.executeInitializerGraphAsync()),e=this.normalizeInputs(e),t=this.normalizeOutputs(t);const n=await this.executor.executeAsync(e,t);return n.length>1?n:n[0]}getIntermediateTensors(){return this.executor.getIntermediateTensors()}disposeIntermediateTensors(){this.executor.disposeIntermediateTensors()}convertTensorMapToTensorsMap(e){return Object.keys(e).reduce((t,n)=>(t[n]=[e[n]],t),{})}dispose(){this.executor.dispose(),this.initializer&&(this.initializer.dispose(),this.resourceIdToCapturedInput&&Va(this.resourceIdToCapturedInput)),this.resourceManager.dispose()}}async function tm(e,t={},n=mp){if(null==e)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");null==t&&(t={}),t.fromTFHub&&"string"===typeof e&&(e=function(e){e.endsWith("/")||(e+="/");return`${e}${Jf}${Zf}`}(e));const r=new em(e,t,n);return await r.load(),r}var nm,rm={};function am(){return nm||(nm=1,function(){var e;function t(e){var t=0;return function(){return t>>0)+"_",a=0;return function e(n){if(this instanceof e)throw new TypeError("Symbol is not a constructor");return new t(r+(n||"")+"_"+a++,n)}}),a("Symbol.iterator",function(e){if(e)return e;e=/* @__PURE__ */Symbol("Symbol.iterator");for(var a="Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".split(" "),o=0;ot&&(t=Math.max(0,r+t)),(null==n||n>r)&&(n=r),0>(n=Number(n))&&(n=Math.max(0,r+n)),t=Number(t||0);t(t=t||0)&&(t=Math.max(t+r,0));t>4),64!=o&&(t(s<<4&240|o>>2),64!=i&&t(o<<6&192|i))}}(e,function(e){r[a++]=e}),a!==n?r.subarray(0,a):r}function A(){if(!R){R={};for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),t=["+/=","+/","-_=","-_.","-_"],n=0;5>n;n++){var r=e.concat(t[n].split(""));E[n]=r;for(var a=0;a>2];o=t[(3&o)<<4|i>>4],i=t[(15&i)<<2|u>>6],u=t[63&u],n[s++]=l+o+i+u}switch(l=0,u=r,e.length-a){case 2:u=t[(15&(l=e[a+1]))<<2]||r;case 1:e=e[a],n[s]=t[e>>2]+t[(3&e)<<4|l>>4]+u+r}return n.join("")}for(t="";10240e,n=(e=Math.abs(e))>>>0;e=Math.floor((e-n)/4294967296),t&&(t=(n=o(K(n,e))).next().value,e=n.next().value,n=t),U=n>>>0,G=e>>>0}var j,q="function"===typeof BigInt;function K(e,t){return t=~t,e?e=1+~e:t+=1,[e,t]}function X(e,t){this.i=e>>>0,this.h=t>>>0}function Y(e){if(!e)return j||(j=new X(0,0));if(!/^-?\d+$/.test(e))return null;if(16>e.length)H(Number(e));else if(q)e=BigInt(e),U=Number(e&BigInt(4294967295))>>>0,G=Number(e>>BigInt(32)&BigInt(4294967295));else{var t=+("-"===e[0]);G=U=0;for(var n=e.length,r=t,a=(n-t)%6+t;a<=n;r=a,a+=6)r=Number(e.slice(r,a)),G*=1e6,4294967296<=(U=1e6*U+r)&&(G+=U/4294967296|0,U%=4294967296);t&&(e=(t=o(K(U,G))).next().value,t=t.next().value,U=e,G=t)}return new X(U,G)}function Q(e,t){return Error("Invalid wire type: "+e+" (at position "+t+")")}function Z(){return Error("Failed to read varint, encoding is invalid.")}function J(e,t){return Error("Tried to read past the end of the data "+t+" > "+e)}function ee(){throw Error("Invalid UTF8")}function te(e,t){return t=String.fromCharCode.apply(null,t),null==e?t:e+t}var ne,re,ae,se=void 0,oe="undefined"!==typeof TextDecoder,ie="undefined"!==typeof TextEncoder;function ue(e){if(e!==W)throw Error("illegal external caller")}function le(e,t){if(ue(t),this.V=e,null!=e&&0===e.length)throw Error("ByteString should be constructed with non-empty values")}function ce(){return ae||(ae=new le(null,W))}function de(e){ue(W);var t=e.V;return null==(t=null==t||O&&null!=t&&t instanceof Uint8Array?t:"string"===typeof t?B(t):null)?t:e.V=t}function pe(e,t){this.i=null,this.m=!1,this.h=this.j=this.l=0,he(this,e,t)}function he(e,t,n){n=void 0===n?{}:n,e.S=void 0!==n.S&&n.S,t&&(t=function(e){if("string"===typeof e)return{buffer:B(e),C:!1};if(Array.isArray(e))return{buffer:new Uint8Array(e),C:!1};if(e.constructor===Uint8Array)return{buffer:e,C:!1};if(e.constructor===ArrayBuffer)return{buffer:new Uint8Array(e),C:!1};if(e.constructor===le)return{buffer:de(e)||V(),C:!0};if(e instanceof Uint8Array)return{buffer:new Uint8Array(e.buffer,e.byteOffset,e.byteLength),C:!1};throw Error("Type not convertible to a Uint8Array, expected a Uint8Array, an ArrayBuffer, a base64 encoded string, a ByteString or an Array of numbers")}(t),e.i=t.buffer,e.m=t.C,e.l=0,e.j=e.i.length,e.h=e.l)}function fe(e,t){if(e.h=t,t>e.j)throw J(e.j,t)}function me(e){var t=e.i,n=e.h,r=t[n++],a=127&r;if(128&r&&(a|=(127&(r=t[n++]))<<7,128&r&&(a|=(127&(r=t[n++]))<<14,128&r&&(a|=(127&(r=t[n++]))<<21,128&r&&(a|=(r=t[n++])<<28,128&r&&128&t[n++]&&128&t[n++]&&128&t[n++]&&128&t[n++]&&128&t[n++])))))throw Z();return fe(e,n),a}function ge(e,t){if(0>t)throw Error("Tried to read a negative byte length: "+t);var n=e.h,r=n+t;if(r>e.j)throw J(t,e.j-n);return e.h=r,n}pe.prototype.reset=function(){this.h=this.l};var ye=[];function be(){this.h=[]}function xe(e,t,n){for(;0>>7|n<<25)>>>0,n>>>=7;e.h.push(t)}function ve(e,t){for(;127>>=7;e.h.push(t)}function we(e,t){if(ye.length){var n=ye.pop();he(n,e,t),e=n}else e=new pe(e,t);this.h=e,this.j=this.h.h,this.i=this.l=-1,this.setOptions(t)}function ke(e){var t=e.h;if(t.h==t.j)return!1;e.j=e.h.h;var n=me(e.h)>>>0;if(t=n>>>3,!(0<=(n&=7)&&5>=n))throw Q(n,e.j);if(1>t)throw Error("Invalid field number: "+t+" (at position "+e.j+")");return e.l=t,e.i=n,!0}function Ie(e){switch(e.i){case 0:if(0!=e.i)Ie(e);else e:{for(var t=(e=e.h).h,n=t+10,r=e.i;t>>0,fe(e=e.h,e.h+t));break;case 5:fe(e=e.h,e.h+4);break;case 3:for(t=e.l;;){if(!ke(e))throw Error("Unmatched start-group tag: stream EOF");if(4==e.i){if(e.l!=t)throw Error("Unmatched end-group tag");break}Ie(e)}break;default:throw Q(e.i,e.j)}}be.prototype.length=function(){return this.h.length},be.prototype.end=function(){var e=this.h;return this.h=[],e},we.prototype.setOptions=function(e){e=void 0===e?{}:e,this.ca=void 0!==e.ca&&e.ca},we.prototype.reset=function(){this.h.reset(),this.j=this.h.h,this.i=this.l=-1};var Ne=[];function Se(){this.j=[],this.i=0,this.h=new be}function Te(e,t){0!==t.length&&(e.j.push(t),e.i+=t.length)}var Ce="function"===typeof Symbol&&"symbol"===typeof/* @__PURE__ */Symbol()?/* @__PURE__ */Symbol():void 0;function $e(e,t){return Ce?e[Ce]|=t:void 0!==e.A?e.A|=t:(Object.defineProperties(e,{A:{value:t,configurable:!0,writable:!0,enumerable:!1}}),t)}function Ee(e,t){Ce?e[Ce]&&(e[Ce]&=~t):void 0!==e.A&&(e.A&=~t)}function Re(e){return(Ce?e[Ce]:e.A)??0}function _e(e,t){Ce?e[Ce]=t:void 0!==e.A?e.A=t:Object.defineProperties(e,{A:{value:t,configurable:!0,writable:!0,enumerable:!1}})}function Ae(e){return $e(e,1),e}function Oe(e,t){_e(t,-51&e)}function Fe(e,t){_e(t,-41&e|18)}var De={};function Me(e){return null!==e&&"object"===typeof e&&!Array.isArray(e)&&e.constructor===Object}var Pe,Le,Be=[];function Ve(e){if(2&Re(e.o))throw Error("Cannot mutate an immutable Message")}function We(e){var t=e.length;(t=t?e[t-1]:void 0)&&Me(t)?t.g=1:(t={},e.push((t.g=1,t)))}function ze(e){var t=e.i+e.G;return e.B||(e.B=e.o[t]={})}function Ue(e,t){return-1===t?null:t>=e.i?e.B?e.B[t]:void 0:e.o[t+e.G]}function Ge(e,t,n,r){Ve(e),He(e,t,n,r)}function He(e,t,n,r){e.j&&(e.j=void 0),t>=e.i||r?ze(e)[t]=n:(e.o[t+e.G]=n,(e=e.B)&&t in e&&delete e[t])}function je(e,t,n,r){var a=Ue(e,t);Array.isArray(a)||(a=Pe);var s=Re(a);if(1&s||Ae(a),r)2&s||$e(a,2),1&n||Object.freeze(a);else{r=!(2&n);var o=2&s;1&n||!o?r&&16&s&&!o&&Ee(a,16):He(e,t,a=Ae(Array.prototype.slice.call(a)))}return a}function qe(e,t){var n=Ue(e,t),r=null==n?n:"number"===typeof n||"NaN"===n||"Infinity"===n||"-Infinity"===n?Number(n):void 0;return null!=r&&r!==n&&He(e,t,r),r}function Ke(e,t,n,r,a){e.h||(e.h={});var s=e.h[n],o=je(e,n,3,a);if(!s){var i=o;s=[];var u=!!(16&Re(e.o));o=!!(2&Re(i));var l=i;!a&&o&&(i=Array.prototype.slice.call(i));for(var c=o,d=0;do&&"number"!==typeof e[o]){var i=e[o++];n(t,i)}for(;o>>0)>>31)+1,s=o>>>23&255,o&=8388607,Ge(t,n,255==s?o?NaN:1/0*e:0==s?e*Math.pow(2,-149)*o:e*Math.pow(2,s-150)*(o+Math.pow(2,23))),!0},function(e,t,n){if(null!=(t=qe(t,n))){ve(e.h,8*n+5),e=e.h;var r=+t;0===r?0<1/r?U=G=0:(G=0,U=2147483648):isNaN(r)?(G=0,U=2147483647):34028234663852886e22<(r=(n=0>r?-2147483648:0)?-r:r)?(G=0,U=(2139095040|n)>>>0):11754943508222875e-54>r?(r=Math.round(r/Math.pow(2,-149)),G=0,U=(n|r)>>>0):(t=Math.floor(Math.log(r)/Math.LN2),r*=Math.pow(2,-t),16777216<=(r=Math.round(8388608*r))&&++t,G=0,U=(n|t+127<<23|8388607&r)>>>0),n=U,e.h.push(n>>>0&255),e.h.push(n>>>8&255),e.h.push(n>>>16&255),e.h.push(n>>>24&255)}}),Mt=Ft(function(e,t,n){if(0!==e.i)return!1;var r=e.h,a=0,s=e=0,o=r.i,i=r.h;do{var u=o[i++];a|=(127&u)<s&&128&u);for(32>4),s=3;32>s&&128&u;s+=7)e|=(127&(u=o[i++]))<u))throw Z();return r=a>>>0,(e=2147483648&(u=e>>>0))&&(u=~u>>>0,0==(r=1+~r>>>0)&&(u=u+1>>>0)),r=4294967296*u+(r>>>0),Ge(t,n,e?-r:r),!0},function(e,t,n){null!=(t=Ue(t,n))&&("string"===typeof t&&Y(t),null!=t&&(ve(e.h,8*n),"number"===typeof t?(e=e.h,H(t),xe(e,U,G)):(n=Y(t),xe(e.h,n.i,n.h))))}),Pt=Ft(function(e,t,n){return 0===e.i&&(Ge(t,n,me(e.h)),!0)},function(e,t,n){if(null!=(t=Ue(t,n))&&null!=t)if(ve(e.h,8*n),e=e.h,0<=(n=t))ve(e,n);else{for(t=0;9>t;t++)e.h.push(127&n|128),n>>=7;e.h.push(1)}}),Lt=Ft(function(e,t,n){if(2!==e.i)return!1;var r=me(e.h)>>>0,a=ge(e=e.h,r);if(e=e.i,oe){var s,o=e;(s=ne)||(s=ne=new TextDecoder("utf-8",{fatal:!0})),e=a+r,o=0===a&&e===o.length?o:o.subarray(a,e);try{var i=s.decode(o)}catch(d){if(void 0===se){try{s.decode(new Uint8Array([128]))}catch(p){}try{s.decode(new Uint8Array([97])),se=!0}catch(p){se=!1}}throw!se&&(ne=void 0),d}}else{r=(i=a)+r,a=[];for(var u,l,c=null;i(u=e[i++])?a.push(u):224>u?i>=r?ee():(l=e[i++],194>u||128!==(192&l)?(i--,ee()):a.push((31&u)<<6|63&l)):240>u?i>=r-1?ee():128!==(192&(l=e[i++]))||224===u&&160>l||237===u&&160<=l||128!==(192&(o=e[i++]))?(i--,ee()):a.push((15&u)<<12|(63&l)<<6|63&o):244>=u?i>=r-2?ee():128!==(192&(l=e[i++]))||0!==l-144+(u<<28)>>30||128!==(192&(o=e[i++]))||128!==(192&(s=e[i++]))?(i--,ee()):(u=(7&u)<<18|(63&l)<<12|(63&o)<<6|63&s,u-=65536,a.push(55296+(u>>10&1023),56320+(1023&u))):ee(),8192<=a.length&&(c=te(c,a),a.length=0);i=te(c,a)}return Ge(t,n,i),!0},function(e,t,n){if(null!=(t=Ue(t,n))){var r=!1;if(r=void 0!==r&&r,ie){if(r&&/(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])/.test(t))throw Error("Found an unpaired surrogate");t=(re||(re=new TextEncoder)).encode(t)}else{for(var a=0,s=new Uint8Array(3*t.length),o=0;oi)s[a++]=i;else{if(2048>i)s[a++]=i>>6|192;else{if(55296<=i&&57343>=i){if(56319>=i&&o=u){i=1024*(i-55296)+u-56320+65536,s[a++]=i>>18|240,s[a++]=i>>12&63|128,s[a++]=i>>6&63|128,s[a++]=63&i|128;continue}o--}if(r)throw Error("Found an unpaired surrogate");i=65533}s[a++]=i>>12|224,s[a++]=i>>6&63|128}s[a++]=63&i|128}}t=a===s.length?s:s.subarray(0,a)}ve(e.h,8*n+2),ve(e.h,t.length),Te(e,e.h.end()),Te(e,t)}}),Bt=Ft(function(e,t,n,r,a){if(2!==e.i)return!1;t=Qe(t,n,r),n=e.h.j,r=me(e.h)>>>0;var s=e.h.h+r,o=s-n;if(0>=o&&(e.h.j=s,a(t,e,void 0,void 0,void 0),o=s-e.h.h),o)throw Error("Message parsing ended unexpectedly. Expected to read "+r+" bytes, instead read "+(r-o)+" bytes, either the data ended unexpectedly or the message misreported its own length");return e.h.h=s,e.h.j=n,!0},function(e,t,n,r,a){if(null!=(t=Xe(t,r,n)))for(r=0;r>>=7,o.i++;s.push(i),o.i++}});function Vt(e){return function(t,n){e:{if(Ne.length){var r=Ne.pop();r.setOptions(n),he(r.h,t,n),t=r}else t=new we(t,n);try{var a=_t(e),s=At(new a.P,t,a);break e}finally{(a=t.h).i=null,a.m=!1,a.l=0,a.j=0,a.h=0,a.S=!1,t.l=-1,t.i=-1,100>Ne.length&&Ne.push(t)}s=void 0}return s}}function Wt(e){return function(){var t=new Se;Ot(this,t,St(e)),Te(t,t.h.end());for(var n=new Uint8Array(t.i),r=t.j,a=r.length,s=0,o=0;o0&&a[a.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!a||s[1]>a[0]&&s[1]=256)throw new Error("Mask value must be in range [0, 255] but got "+e);if(!Number.isInteger(e))throw new Error("Mask value must be an integer but got "+e)}function gm(e){var t=e.shape[2],n=Qs(e,2),r=vo(n,[-1]);return Ou(r,t)}function ym(e,t){return Ba(function(){return Ls(Gi(e,Ri(t)),"int32")})}function bm(e,t){var n=t.shape,r=n[0],a=n[1],s=n[2];return Ba(function(){var n=gm(t),o=Li(Nl(0,s,1,"int32"),1),i=Ls(No(n,o),"int32"),u=vo(i,[r,a]),l=Ws(u,Ri(1,"int32"));return uu(Gs(l,e),Ri(1,"int32"))})}var xm=function(){function e(e,t){this.model=e,this.outputStride=t;var n=this.model.inputs[0].shape;i(-1===n[1]&&-1===n[2],function(){return"Input shape ["+n[1]+", "+n[2]+"] must both be equal to or -1"})}return e.prototype.predict=function(e){var t=this;return Ba(function(){var n=t.preprocessInput(Ls(e,"float32")),r=Li(n,0),a=t.model.predict(r).map(function(e){return Jl(e,[0])}),s=t.nameOutputResults(a);return{heatmapScores:So(s.heatmap),offsets:s.offsets,displacementFwd:s.displacementFwd,displacementBwd:s.displacementBwd,segmentation:s.segmentation,partHeatmaps:s.partHeatmaps,longOffsets:s.longOffsets,partOffsets:s.partOffsets}})},e.prototype.dispose=function(){this.model.dispose()},e}(),vm=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return im(t,e),t.prototype.preprocessInput=function(e){return Ba(function(){return uu(Us(e,127.5),1)})},t.prototype.nameOutputResults=function(e){return{offsets:e[0],segmentation:e[1],partHeatmaps:e[2],longOffsets:e[3],heatmap:e[4],displacementFwd:e[5],displacementBwd:e[6],partOffsets:e[7]}},t}(xm),wm=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"],km=wm.length,Im=wm.reduce(function(e,t,n){return e[t]=n,e},{});function Nm(e,t,n){var r=e[0],a=e[1],s=t[0],o=t[1],i=n.top,u=n.bottom;return[o/(n.left+n.right+a),s/(i+u+r)]}function Sm(e,t,n,r){return{y:r.get(e,t,n),x:r.get(e,t,n+km)}}function Tm(e,t,n){var r=Sm(e.heatmapY,e.heatmapX,e.id,n),a=r.y,s=r.x;return{x:e.heatmapX*t+s,y:e.heatmapY*t+a}}function Cm(e,t,n){return en?n:e}function $m(e,t){return{x:e.x+t.x,y:e.y+t.y}}function Em(e,t,n){void 0===n&&(n=.3);for(var r=0,a=0,s=0;sn&&(a+=1,r+=Math.pow(e[s].x-t.keypoints[s].position.x,2)+Math.pow(e[s].y-t.keypoints[s].position.y,2));return 0===a?r=1/0:r/=a,r}function Rm(e,t,n,r,a,s,o){for(var i=o[0],u=o[1],l=n(e),c=l.y*r+l.x,d=a[km*(2*c)+t],p=a[km*(2*c+1)+t],h=e.y+d,f=e.x+p,m=0;m "+l+") {\n numKpt = numKpt + 1;\n curDistSum = curDistSum + dist(x, y, poseX, poseY);\n }\n }\n if (numKpt > 0 && curDistSum / float(numKpt) < minDist) {\n minDist = curDistSum / float(numKpt);\n iMin = i;\n }\n }\n return iMin;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int nearestPose = findNearestPose(coords[0], coords[1]);\n setOutput(float(nearestPose));\n }\n "};return Ha().compileAndRun(O,[e,x,R])}function Fm(){return"webgl"===Ua()}function Dm(e,t,n,r,a,s,o,i,u,l,c,d){var p=o[0],h=o[1];return void 0===u&&(u=.2),void 0===l&&(l=8),void 0===c&&(c=.3),void 0===d&&(d=10),lm(this,0,void 0,function(){var o,f,m,g,y;return cm(this,function(b){switch(b.label){case 0:return o=n.filter(function(e){return e.score>=u}),Fm()?(m=Ba(function(){var n=Om(e,t,o,r,a,s,[p,h],i,l,c,d),u=La().makeTensorFromDataId(n.dataId,n.shape,n.dtype);return o.map(function(e,t){return n=u,r=t,Ba(function(){return Ls(ci(n,Ri(r)),"int32")});var n,r})}),[4,Promise.all(m.map(function(e){return e.data()}))]):[3,2];case 1:return f=b.sent(),m.forEach(function(e){return e.dispose()}),[3,5];case 2:return[4,e.data()];case 3:return g=b.sent(),[4,t.data()];case 4:y=b.sent(),f=function(e,t,n,r,a,s,o,i,u,l){var c=o[0],d=o[1];void 0===l&&(l=5);for(var p=n.map(function(e){return new Uint8Array(r*a).fill(0)}),h=i.top,f=i.left,m=Nm([r,a],[c,d],i),g=m[0],y=m[1],b=Am([c,d],s)[0],x=0;x=0&&(p[k][w]=1)}}return p}(g,y,o,r,a,s,[p,h],i,l),b.label=5;case 5:return[2,f.map(function(e,t){return{data:e,pose:o[t],width:a,height:r}})]}})})}function Mm(e,t,n,r,a,s,o,i,u,l,c,d,p){var h=i[0],f=i[1];return void 0===l&&(l=.2),void 0===c&&(c=8),void 0===d&&(d=.3),void 0===p&&(p=10),lm(this,0,void 0,function(){var i,m,g,y,b,x;return cm(this,function(v){switch(v.label){case 0:return i=r.filter(function(e){return e.score>=l}),Fm()?(g=Ba(function(){var r=Om(e,t,i,a,s,o,[h,f],u,c,d,p),l=La().makeTensorFromDataId(r.dataId,r.shape,r.dtype);return i.map(function(e,t){return r=l,a=n,s=t,Ba(function(){return uu(Gs(Ls(ci(r,Ri(s)),"int32"),Ws(a,1)),1)});var r,a,s})}),[4,Promise.all(g.map(function(e){return e.data()}))]):[3,2];case 1:return m=v.sent(),g.forEach(function(e){return e.dispose()}),[3,6];case 2:return[4,e.data()];case 3:return y=v.sent(),[4,t.data()];case 4:return b=v.sent(),[4,n.data()];case 5:x=v.sent(),m=function(e,t,n,r,a,s,o,i,u,l,c){var d=i[0],p=i[1];void 0===c&&(c=5);for(var h=r.map(function(e){return new Int32Array(a*s).fill(-1)}),f=u.top,m=u.left,g=Nm([a,s],[d,p],u),y=g[0],b=g[1],x=Am([d,p],o)[0],v=0;v=0&&(h[I][k]=n[k])}}return h}(y,b,x,i,a,s,o,[h,f],u,c),v.label=6;case 6:return[2,m.map(function(e,t){return{pose:i[t],data:e,height:a,width:s}})]}})})}function Pm(e){return Math.floor(e/2)}[["leftHip","leftShoulder"],["leftElbow","leftShoulder"],["leftElbow","leftWrist"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["rightHip","rightShoulder"],["rightElbow","rightShoulder"],["rightElbow","rightWrist"],["rightHip","rightKnee"],["rightKnee","rightAnkle"],["leftShoulder","rightShoulder"],["leftHip","rightHip"]].map(function(e){var t=e[0],n=e[1];return[Im[t],Im[n]]});var Lm=function(){function e(e,t){this.priorityQueue=new Array(e),this.numberOfElements=-1,this.getElementValue=t}return e.prototype.enqueue=function(e){this.priorityQueue[++this.numberOfElements]=e,this.swim(this.numberOfElements)},e.prototype.dequeue=function(){var e=this.priorityQueue[0];return this.exchange(0,this.numberOfElements--),this.sink(0),this.priorityQueue[this.numberOfElements+1]=null,e},e.prototype.empty=function(){return-1===this.numberOfElements},e.prototype.size=function(){return this.numberOfElements+1},e.prototype.all=function(){return this.priorityQueue.slice(0,this.numberOfElements+1)},e.prototype.max=function(){return this.priorityQueue[0]},e.prototype.swim=function(e){for(;e>0&&this.less(Pm(e),e);)this.exchange(e,Pm(e)),e=Pm(e)},e.prototype.sink=function(e){for(;2*e<=this.numberOfElements;){var t=2*e;if(tt){l=!1;break}if(!l)break}return l}var Vm=[["nose","leftEye"],["leftEye","leftEar"],["nose","rightEye"],["rightEye","rightEar"],["nose","leftShoulder"],["leftShoulder","leftElbow"],["leftElbow","leftWrist"],["leftShoulder","leftHip"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["nose","rightShoulder"],["rightShoulder","rightElbow"],["rightElbow","rightWrist"],["rightShoulder","rightHip"],["rightHip","rightKnee"],["rightKnee","rightAnkle"]].map(function(e){var t=e[0],n=e[1];return[Im[t],Im[n]]}),Wm=Vm.map(function(e){return e[1]}),zm=Vm.map(function(e){return e[0]});function Um(e,t,n,r){return{y:Cm(Math.round(e.y/t),0,n-1),x:Cm(Math.round(e.x/t),0,r-1)}}function Gm(e,t,n,r,a,s,o,i){void 0===i&&(i=2);for(var u=r.shape,l=u[0],c=u[1],d=function(e,t,n){var r=n.shape[2]/2;return{y:n.get(t.y,t.x,e),x:n.get(t.y,t.x,r+e)}}(e,Um(t.position,s,l,c),o),p=$m(t.position,d),h=0;h=0;--p){var h=Wm[p],f=zm[p];u[h]&&!u[f]&&(u[f]=Gm(p,u[h],f,t,n,r,s))}for(p=0;p=.1,function(){return"inputResolution must be a string or number between 0.1 and 2, but was "+e}),e}(e);return[tg(r*s,t),tg(a*s,t)]}function sg(e,t,n,r,a){var s=t[0],o=t[1],i=n[0],u=n[1],l=r[0],c=l[0],d=l[1],p=r[1],h=p[0],f=p[1];return Ba(function(){var t=Md.resizeBilinear(e,[i,u],!0);return function(e,t,n){var r=t[0],a=t[1],s=n[0],o=s[0],i=s[1],u=n[1],l=u[0],c=u[1];return Ba(function(){var t=Li(e);return Jl(Md.cropAndResize(t,[[o/(r+o+i-1),l/(a+l+c-1),(o+r-1)/(r+o+i-1),(l+a-1)/(a+l+c-1)]],[0],[r,a]),[0])})}(t=So(t),[s,o],[[c,d],[h,f]])})}function og(e,t){var n=t[0],r=t[1],a=eg(e),s=a[0],o=a[1],i=r/n,u=[0,0,0,0],l=u[0],c=u[1],d=u[2],p=u[3];return o/s1)throw new Error("segmentationThreshold "+t+". Should be in range [0.0, 1.0]");if(n<=0)throw new Error("Invalid maxDetections "+n+". Should be > 0");if(r<0||r>1)throw new Error("Invalid scoreThreshold "+r+". Should be in range [0.0, 1.0]");if(a<=0)throw new Error("Invalid nmsRadius "+a+".")}function yg(e){var t=e.segmentationThreshold,n=e.maxDetections,r=e.scoreThreshold,a=e.nmsRadius,s=e.minKeypointScore,o=e.refineSteps;if(t<0||t>1)throw new Error("segmentationThreshold "+t+". Should be in range [0.0, 1.0]");if(n<=0)throw new Error("Invalid maxDetections "+n+". Should be > 0");if(r<0||r>1)throw new Error("Invalid scoreThreshold "+r+". Should be in range [0.0, 1.0]");if(a<=0)throw new Error("Invalid nmsRadius "+a+".");if(s<0||s>1)throw new Error("Invalid minKeypointScore "+s+".Should be in range [0.0, 1.0]");if(o<=0||o>20)throw new Error("Invalid refineSteps "+o+".Should be in range [1, 20]")}var bg=function(){function e(e){this.baseModel=e}return e.prototype.predictForPersonSegmentation=function(e){var t=this.baseModel.predict(e);return{segmentLogits:t.segmentation,heatmapScores:t.heatmapScores,offsets:t.offsets,displacementFwd:t.displacementFwd,displacementBwd:t.displacementBwd}},e.prototype.predictForPersonSegmentationAndPart=function(e){var t=this.baseModel.predict(e);return{segmentLogits:t.segmentation,partHeatmapLogits:t.partHeatmaps,heatmapScores:t.heatmapScores,offsets:t.offsets,displacementFwd:t.displacementFwd,displacementBwd:t.displacementBwd}},e.prototype.predictForMultiPersonInstanceSegmentationAndPart=function(e){var t=this.baseModel.predict(e);return{segmentLogits:t.segmentation,longOffsets:t.longOffsets,heatmapScores:t.heatmapScores,offsets:t.offsets,displacementFwd:t.displacementFwd,displacementBwd:t.displacementBwd,partHeatmaps:t.partHeatmaps}},e.prototype.segmentPersonActivation=function(e,t,n){var r=this;void 0===n&&(n=.5);var a=eg(e),s=a[0],o=a[1],i=ag(t,this.baseModel.outputStride,[s,o]),u=og(e,i),l=u.resized,c=u.padding,d=Ba(function(){var e=r.predictForPersonSegmentation(l),t=e.segmentLogits,a=e.heatmapScores,i=e.offsets,u=e.displacementFwd,d=e.displacementBwd,p=l.shape,h=p[0],f=p[1],m=sg(t,[s,o],[h,f],[[c.top,c.bottom],[c.left,c.right]]);return{segmentation:ym(Jl(m),n),heatmapScores:a,offsets:i,displacementFwd:u,displacementBwd:d}}),p=d.segmentation,h=d.heatmapScores,f=d.offsets,m=d.displacementFwd,g=d.displacementBwd;return l.dispose(),{segmentation:p,heatmapScores:h,offsets:f,displacementFwd:m,displacementBwd:g,padding:c,internalResolutionHeightAndWidth:i}},e.prototype.segmentPerson=function(e,t){return void 0===t&&(t=fg),lm(this,0,void 0,function(){var n,r,a,s,o,i,u,l,c,d,p,h,f,m,g,y,b,x;return cm(this,function(v){switch(v.label){case 0:return gg(t=um(um({},fg),t)),n=this.segmentPersonActivation(e,t.internalResolution,t.segmentationThreshold),r=n.segmentation,a=n.heatmapScores,s=n.offsets,o=n.displacementFwd,i=n.displacementBwd,u=n.padding,l=n.internalResolutionHeightAndWidth,c=r.shape,d=c[0],p=c[1],[4,r.data()];case 1:return h=v.sent(),r.dispose(),[4,ig([a,s,o,i])];case 2:return f=v.sent(),m=f[0],g=f[1],y=f[2],b=f[3],x=ug(x=Km(m,g,y,b,this.baseModel.outputStride,t.maxDetections,t.scoreThreshold,t.nmsRadius),[d,p],l,u,!1),a.dispose(),s.dispose(),o.dispose(),i.dispose(),[2,{height:d,width:p,data:h,allPoses:x}]}})})},e.prototype.segmentMultiPerson=function(e,t){return void 0===t&&(t=mg),lm(this,0,void 0,function(){var n,r,a,s,o,i,u,l,c,d,p,h,f,m,g,y,b,x,v,w,k,I=this;return cm(this,function(N){switch(N.label){case 0:return yg(t=um(um({},mg),t)),n=eg(e),r=n[0],a=n[1],s=ag(t.internalResolution,this.baseModel.outputStride,[r,a]),o=og(e,s),i=o.resized,u=o.padding,l=Ba(function(){var e,n=I.predictForMultiPersonInstanceSegmentationAndPart(i),o=n.segmentLogits,l=n.longOffsets,c=n.heatmapScores,d=n.offsets,p=n.displacementFwd,h=n.displacementBwd,f=sg(o,[r,a],s,[[u.top,u.bottom],[u.left,u.right]]);return e=l,{segmentation:ym(Jl(f),t.segmentationThreshold),longOffsets:e,heatmapScoresRaw:c,offsetsRaw:d,displacementFwdRaw:p,displacementBwdRaw:h}}),c=l.segmentation,d=l.longOffsets,p=l.heatmapScoresRaw,h=l.offsetsRaw,f=l.displacementFwdRaw,m=l.displacementBwdRaw,[4,ig([p,h,f,m])];case 1:return g=N.sent(),y=g[0],b=g[1],x=g[2],v=g[3],w=ug(w=Km(y,b,x,v,this.baseModel.outputStride,t.maxDetections,t.scoreThreshold,t.nmsRadius),[r,a],s,u,!1),[4,Dm(c,d,w,r,a,this.baseModel.outputStride,s,u,t.scoreThreshold,t.refineSteps,t.minKeypointScore,t.maxDetections)];case 2:return k=N.sent(),i.dispose(),c.dispose(),d.dispose(),p.dispose(),h.dispose(),f.dispose(),m.dispose(),[2,k]}})})},e.prototype.segmentPersonPartsActivation=function(e,t,n){var r=this;void 0===n&&(n=.5);var a=eg(e),s=a[0],o=a[1],i=ag(t,this.baseModel.outputStride,[s,o]),u=og(e,i),l=u.resized,c=u.padding,d=Ba(function(){var e=r.predictForPersonSegmentationAndPart(l),t=e.segmentLogits,a=e.partHeatmapLogits,i=e.heatmapScores,u=e.offsets,d=e.displacementFwd,p=e.displacementBwd,h=l.shape,f=h[0],m=h[1],g=sg(t,[s,o],[f,m],[[c.top,c.bottom],[c.left,c.right]]),y=sg(a,[s,o],[f,m],[[c.top,c.bottom],[c.left,c.right]]);return{partSegmentation:bm(ym(Jl(g),n),y),heatmapScores:i,offsets:u,displacementFwd:d,displacementBwd:p}}),p=d.partSegmentation,h=d.heatmapScores,f=d.offsets,m=d.displacementFwd,g=d.displacementBwd;return l.dispose(),{partSegmentation:p,heatmapScores:h,offsets:f,displacementFwd:m,displacementBwd:g,padding:c,internalResolutionHeightAndWidth:i}},e.prototype.segmentPersonParts=function(e,t){return void 0===t&&(t=fg),lm(this,0,void 0,function(){var n,r,a,s,o,i,u,l,c,d,p,h,f,m,g,y,b,x;return cm(this,function(v){switch(v.label){case 0:return gg(t=um(um({},fg),t)),n=this.segmentPersonPartsActivation(e,t.internalResolution,t.segmentationThreshold),r=n.partSegmentation,a=n.heatmapScores,s=n.offsets,o=n.displacementFwd,i=n.displacementBwd,u=n.padding,l=n.internalResolutionHeightAndWidth,c=r.shape,d=c[0],p=c[1],[4,r.data()];case 1:return h=v.sent(),r.dispose(),[4,ig([a,s,o,i])];case 2:return f=v.sent(),m=f[0],g=f[1],y=f[2],b=f[3],x=ug(x=Km(m,g,y,b,this.baseModel.outputStride,t.maxDetections,t.scoreThreshold,t.nmsRadius),[d,p],l,u,!1),a.dispose(),s.dispose(),o.dispose(),i.dispose(),[2,{height:d,width:p,data:h,allPoses:x}]}})})},e.prototype.segmentMultiPersonParts=function(e,t){return void 0===t&&(t=mg),lm(this,0,void 0,function(){var n,r,a,s,o,i,u,l,c,d,p,h,f,m,g,y,b,x,v,w,k,I,N=this;return cm(this,function(S){switch(S.label){case 0:return yg(t=um(um({},mg),t)),n=eg(e),r=n[0],a=n[1],s=ag(t.internalResolution,this.baseModel.outputStride,[r,a]),o=og(e,s),i=o.resized,u=o.padding,l=Ba(function(){var e=N.predictForMultiPersonInstanceSegmentationAndPart(i),n=e.segmentLogits,o=e.longOffsets,l=e.heatmapScores,c=e.offsets,d=e.displacementFwd,p=e.displacementBwd,h=e.partHeatmaps,f=sg(n,[r,a],s,[[u.top,u.bottom],[u.left,u.right]]),m=sg(h,[r,a],s,[[u.top,u.bottom],[u.left,u.right]]),g=o;return{segmentation:ym(Jl(f),t.segmentationThreshold),longOffsets:g,heatmapScoresRaw:l,offsetsRaw:c,displacementFwdRaw:d,displacementBwdRaw:p,partSegmentation:function(e){var t=e.shape,n=t[0],r=t[1],a=t[2];return Ba(function(){var t=gm(e),s=Li(Nl(0,a,1,"int32"),1),o=Ls(No(t,s),"int32");return vo(o,[n,r])})}(m)}}),c=l.segmentation,d=l.longOffsets,p=l.heatmapScoresRaw,h=l.offsetsRaw,f=l.displacementFwdRaw,m=l.displacementBwdRaw,g=l.partSegmentation,[4,ig([p,h,f,m])];case 1:return y=S.sent(),b=y[0],x=y[1],v=y[2],w=y[3],k=ug(k=Km(b,x,v,w,this.baseModel.outputStride,t.maxDetections,t.scoreThreshold,t.nmsRadius),[r,a],s,u,!1),[4,Mm(c,d,g,k,r,a,this.baseModel.outputStride,s,u,t.scoreThreshold,t.refineSteps,t.minKeypointScore,t.maxDetections)];case 2:return I=S.sent(),i.dispose(),c.dispose(),d.dispose(),p.dispose(),h.dispose(),f.dispose(),m.dispose(),g.dispose(),[2,I]}})})},e.prototype.dispose=function(){this.baseModel.dispose()},e}();function xg(e){return lm(this,0,void 0,function(){var t,n,r,a,s,o;return cm(this,function(i){switch(i.label){case 0:if(t=e.outputStride,n=e.quantBytes,r=e.multiplier,null==Ah)throw new Error("Cannot find TensorFlow.js. If you are using a + \ No newline at end of file diff --git a/docs/document/advanced/built-in.html b/docs/document/advanced/built-in.html index cd3591710..646e33aab 100644 --- a/docs/document/advanced/built-in.html +++ b/docs/document/advanced/built-in.html @@ -217,7 +217,7 @@ art.on('ready', () => { art.plugins.add(myPlugin); }); - + \ No newline at end of file diff --git a/docs/document/advanced/class.html b/docs/document/advanced/class.html index 55cc3e51c..7b6268da6 100644 --- a/docs/document/advanced/class.html +++ b/docs/document/advanced/class.html @@ -31,7 +31,7 @@ }); console.info([...Artplayer.instances]);

version ​

返回播放器的版本信息

▶ Run Code
js
console.info(Artplayer.version);

env ​

返回播放器的环境变量

▶ Run Code
js
console.info(Artplayer.env);

build ​

返回播放器的打包时间

▶ Run Code
js
console.info(Artplayer.build);

config ​

返回视频的默认配置

▶ Run Code
js
console.info(Artplayer.config);

utils ​

返回播放器的工具函数集合

▶ Run Code
js
console.info(Artplayer.utils);

全部工具函数请参考以下地址:

artplayer/types/utils.d.ts

scheme ​

返回播放器选项的校验方案

▶ Run Code
js
console.info(Artplayer.scheme);

Emitter ​

返回事件分发器的构造函数

▶ Run Code
js
console.info(Artplayer.Emitter);

validator ​

返回选项的校验函数

▶ Run Code
js
console.info(Artplayer.validator);

kindOf ​

返回类型检测的函数工具

▶ Run Code
js
console.info(Artplayer.kindOf);

html ​

返回播放器所需的 html 字符串

▶ Run Code
js
console.info(Artplayer.html);

option ​

返回播放器的默认选项

▶ Run Code
js
console.info(Artplayer.option);
- + \ No newline at end of file diff --git a/docs/document/advanced/event.html b/docs/document/advanced/event.html index 07cbfe96b..e6589498a 100644 --- a/docs/document/advanced/event.html +++ b/docs/document/advanced/event.html @@ -385,7 +385,7 @@ art.on('keydown', (event) => { console.log(event.code); });

video:canplay ​

浏览器可以播放媒体文件了,但估计没有足够的数据来支撑播放到结束,不必停下来进一步缓冲内容

video:canplaythrough ​

浏览器估计它可以在不停止内容缓冲的情况下播放媒体直到结束

video:complete ​

OfflineAudioContext 渲染完成

video:durationchange ​

duration 属性的值改变时触发

video:emptied ​

媒体内容变为空;例如,当这个 media 已经加载完成(或者部分加载完成),则发送此事件,并调用 load() 方法重新加载它

video:ended ​

视频停止播放,因为 media 已经到达结束点

video:error ​

获取媒体数据时出错,或者资源类型不是受支持的媒体格式

video:loadeddata ​

media 中的首帧已经完成加载

video:loadedmetadata ​

已加载元数据

video:pause ​

播放已暂停

video:play ​

播放已开始

video:playing ​

由于缺乏数据而暂停或延迟后,播放准备开始

video:progress ​

在浏览器加载资源时周期性触发

video:ratechange ​

播放速率发生变化

video:seeked ​

跳帧(seek)操作完成

video:seeking ​

跳帧(seek)操作开始

video:stalled ​

用户代理(user agent)正在尝试获取媒体数据,但数据意外未出现

video:suspend ​

媒体数据加载已暂停

video:timeupdate ​

currentTime 属性指定的时间发生变化

video:volumechange ​

音量发生变化

video:waiting ​

由于暂时缺少数据,播放已停止

- + \ No newline at end of file diff --git a/docs/document/advanced/global.html b/docs/document/advanced/global.html index c87d95947..29afaad0b 100644 --- a/docs/document/advanced/global.html +++ b/docs/document/advanced/global.html @@ -248,7 +248,7 @@ // 只销毁界面,不主动清空 src art.destroy(); - + \ No newline at end of file diff --git a/docs/document/advanced/plugin.html b/docs/document/advanced/plugin.html index 7e18f6ced..f1d81d84f 100644 --- a/docs/document/advanced/plugin.html +++ b/docs/document/advanced/plugin.html @@ -122,7 +122,7 @@ }) ], }); - + \ No newline at end of file diff --git a/docs/document/advanced/property.html b/docs/document/advanced/property.html index cc7232d77..99151927a 100644 --- a/docs/document/advanced/property.html +++ b/docs/document/advanced/property.html @@ -457,7 +457,7 @@ art.on('ready', () => { art.subtitleOffset = 1; }); - + \ No newline at end of file diff --git a/docs/document/assets/en_index.md.B6J2cqvj.js b/docs/document/assets/en_index.md.D_XAyEyy.js similarity index 96% rename from docs/document/assets/en_index.md.B6J2cqvj.js rename to docs/document/assets/en_index.md.D_XAyEyy.js index 893f3fa7f..8d999c48d 100644 --- a/docs/document/assets/en_index.md.B6J2cqvj.js +++ b/docs/document/assets/en_index.md.D_XAyEyy.js @@ -1,4 +1,4 @@ -import{_ as i,c as a,o as n,ak as l}from"./chunks/framework.xxfEszSJ.js";const g=JSON.parse('{"title":"Installation & Usage","description":"","frontmatter":{},"headers":[],"relativePath":"en/index.md","filePath":"en/index.md","lastUpdated":1767420511000}'),p={name:"en/index.md"};function t(e,s,h,k,r,E){return n(),a("div",null,s[0]||(s[0]=[l(`

Installation & Usage ​

Installation ​

bash
npm install artplayer
bash
yarn add artplayer
bash
pnpm add artplayer
html
<script src="path/to/artplayer.js"></script>

CDN ​

bash
https://cdn.jsdelivr.net/npm/artplayer/dist/artplayer.js
bash
https://unpkg.com/artplayer/dist/artplayer.js

Usage ​

html
<html>
+import{_ as i,c as a,o as n,ak as l}from"./chunks/framework.xxfEszSJ.js";const g=JSON.parse('{"title":"Installation & Usage","description":"","frontmatter":{},"headers":[],"relativePath":"en/index.md","filePath":"en/index.md","lastUpdated":1767420511000}'),p={name:"en/index.md"};function t(e,s,h,k,r,E){return n(),a("div",null,s[0]||(s[0]=[l(`

Installation & Usage ​

Installation ​

bash
npm install artplayer
bash
yarn add artplayer
bash
pnpm add artplayer
html
<script src="path/to/artplayer.js"></script>

CDN ​

bash
https://cdn.jsdelivr.net/npm/artplayer/dist/artplayer.js
bash
https://unpkg.com/artplayer/dist/artplayer.js

Usage ​

html
<html>
     <head>
         <title>ArtPlayer Demo</title>
         <meta charset="UTF-8" />
@@ -19,7 +19,7 @@ import{_ as i,c as a,o as n,ak as l}from"./chunks/framework.xxfEszSJ.js";const g
           });
         </script>
     </body>
-</html>

Note

The player's dimensions depend on the size of its container container, so your container must have defined dimensions.

See more usage examples at the following link:

/example

Vue.js ​

vue
<template>
+</html>

Note

The player's dimensions depend on the size of its container container, so your container must have defined dimensions.

See more usage examples at the following link:

/example

Vue.js ​

vue
<template>
   <div ref="$container" />
 </template>
 
@@ -51,7 +51,7 @@ import{_ as i,c as a,o as n,ak as l}from"./chunks/framework.xxfEszSJ.js";const g
   art.value.destroy(false)
 })
 </script>
vue
<template>
-  <Artplayer :option="option" :style="style" @get-instance="getInstance" />
+  <Artplayer :option="option" :style="style" @get-instance="getInstance" />
 </template>
 
 <script setup>
@@ -71,7 +71,7 @@ import{_ as i,c as a,o as n,ak as l}from"./chunks/framework.xxfEszSJ.js";const g
 function getInstance(art) {
   console.log(art)
 }
-</script>

Artplayer is not reactive:

Directly modifying option in Vue.js will not update the player.

React.js ​

jsx
import Artplayer from 'artplayer'
+</script>

Artplayer is not reactive:

Directly modifying option in Vue.js will not update the player.

React.js ​

jsx
import Artplayer from 'artplayer'
 import { useEffect, useRef } from 'react'
 
 export default function Player({ option, getInstance, ...rest }) {
@@ -154,7 +154,7 @@ import{_ as i,c as a,o as n,ak as l}from"./chunks/framework.xxfEszSJ.js";const g
 
 option.volume = 0.5;
 
-const art8 = new Artplayer(option);

Legacy Browsers ​

The production build artplayer.js only supports the latest major version of Chrome: last 1 Chrome version

For legacy browsers, you can use the artplayer.legacy.js file, which supports compatibility down to: IE 11

js
import Artplayer from 'artplayer/legacy'
bash
https://cdn.jsdelivr.net/npm/artplayer/dist/artplayer.legacy.js
bash
https://unpkg.com/artplayer/dist/artplayer.legacy.js

If you need to support even older browsers, modify the following configuration and build it yourself:

Build configuration: scripts/build.js

Reference documentation: browserslist

ECMAScript Module ​

Starting from 5.2.6, artplayer and all plugins also provide an ESM version mjs, such as:

  • artplayer/dist/artplayer.mjs
  • artplayer-plugin-danmuku/dist/artplayer-plugin-danmuku.mjs
html
<!DOCTYPE html>
+const art8 = new Artplayer(option);

Legacy Browsers ​

The production build artplayer.js only supports the latest major version of Chrome: last 1 Chrome version

For legacy browsers, you can use the artplayer.legacy.js file, which supports compatibility down to: IE 11

js
import Artplayer from 'artplayer/legacy'
bash
https://cdn.jsdelivr.net/npm/artplayer/dist/artplayer.legacy.js
bash
https://unpkg.com/artplayer/dist/artplayer.legacy.js

If you need to support even older browsers, modify the following configuration and build it yourself:

Build configuration: scripts/build.js

Reference documentation: browserslist

ECMAScript Module ​

Starting from 5.2.6, artplayer and all plugins also provide an ESM version mjs, such as:

  • artplayer/dist/artplayer.mjs
  • artplayer-plugin-danmuku/dist/artplayer-plugin-danmuku.mjs
html
<!DOCTYPE html>
 <html lang="en">
 
 <head>
diff --git a/docs/document/assets/en_index.md.B6J2cqvj.lean.js b/docs/document/assets/en_index.md.D_XAyEyy.lean.js
similarity index 100%
rename from docs/document/assets/en_index.md.B6J2cqvj.lean.js
rename to docs/document/assets/en_index.md.D_XAyEyy.lean.js
diff --git a/docs/document/assets/en_start_i18n.md.BhiDfadM.js b/docs/document/assets/en_start_i18n.md.fbCR_PMw.js
similarity index 98%
rename from docs/document/assets/en_start_i18n.md.BhiDfadM.js
rename to docs/document/assets/en_start_i18n.md.fbCR_PMw.js
index e1a6dc745..80a90ccea 100644
--- a/docs/document/assets/en_start_i18n.md.BhiDfadM.js
+++ b/docs/document/assets/en_start_i18n.md.fbCR_PMw.js
@@ -2,7 +2,7 @@ import{_ as a,c as i,o as n,ak as l}from"./chunks/framework.xxfEszSJ.js";const g
     container: '.artplayer-app',
     url: '/assets/sample/video.mp4',
     lang: 'zh-cn', // or 'en'
-});

Importing Languages ​

Language files before bundling are located at: artplayer/src/i18n/*.js. Contributions to add your language are welcome.

Language files after bundling are located at: artplayer/dist/i18n/*.js

js
import id from 'artplayer/i18n/id';
+});

Importing Languages ​

Language files before bundling are located at: artplayer/src/i18n/*.js. Contributions to add your language are welcome.

Language files after bundling are located at: artplayer/dist/i18n/*.js

js
import id from 'artplayer/i18n/id';
 import zhTw from 'artplayer/i18n/zh-tw';
 
 var art = new Artplayer({
diff --git a/docs/document/assets/en_start_i18n.md.BhiDfadM.lean.js b/docs/document/assets/en_start_i18n.md.fbCR_PMw.lean.js
similarity index 100%
rename from docs/document/assets/en_start_i18n.md.BhiDfadM.lean.js
rename to docs/document/assets/en_start_i18n.md.fbCR_PMw.lean.js
diff --git a/docs/document/assets/index.md.CDZ-sHkw.js b/docs/document/assets/index.md.BaNZbFwu.js
similarity index 96%
rename from docs/document/assets/index.md.CDZ-sHkw.js
rename to docs/document/assets/index.md.BaNZbFwu.js
index 34bac633f..680a05f66 100644
--- a/docs/document/assets/index.md.CDZ-sHkw.js
+++ b/docs/document/assets/index.md.BaNZbFwu.js
@@ -1,4 +1,4 @@
-import{_ as i,c as a,o as n,ak as l}from"./chunks/framework.xxfEszSJ.js";const g=JSON.parse('{"title":"安装使用","description":"","frontmatter":{},"headers":[],"relativePath":"index.md","filePath":"index.md","lastUpdated":1767420511000}'),p={name:"index.md"};function t(e,s,h,k,r,E){return n(),a("div",null,s[0]||(s[0]=[l(`

安装使用 ​

安装 ​

bash
npm install artplayer
bash
yarn add artplayer
bash
pnpm add artplayer
html
<script src="path/to/artplayer.js"></script>

CDN ​

bash
https://cdn.jsdelivr.net/npm/artplayer/dist/artplayer.js
bash
https://unpkg.com/artplayer/dist/artplayer.js

使用 ​

html
<html>
+import{_ as i,c as a,o as n,ak as l}from"./chunks/framework.xxfEszSJ.js";const g=JSON.parse('{"title":"安装使用","description":"","frontmatter":{},"headers":[],"relativePath":"index.md","filePath":"index.md","lastUpdated":1767420511000}'),p={name:"index.md"};function t(e,s,h,k,r,E){return n(),a("div",null,s[0]||(s[0]=[l(`

安装使用 ​

安装 ​

bash
npm install artplayer
bash
yarn add artplayer
bash
pnpm add artplayer
html
<script src="path/to/artplayer.js"></script>

CDN ​

bash
https://cdn.jsdelivr.net/npm/artplayer/dist/artplayer.js
bash
https://unpkg.com/artplayer/dist/artplayer.js

使用 ​

html
<html>
     <head>
         <title>ArtPlayer Demo</title>
         <meta charset="UTF-8" />
@@ -19,7 +19,7 @@ import{_ as i,c as a,o as n,ak as l}from"./chunks/framework.xxfEszSJ.js";const g
           });
         </script>
     </body>
-</html>

提示

播放器的尺寸依赖于容器 container 的尺寸,所以你的容器 container 必须是有尺寸的

以下链接可以看到更多的使用例子

/example

Vue.js ​

vue
<template>
+</html>

提示

播放器的尺寸依赖于容器 container 的尺寸,所以你的容器 container 必须是有尺寸的

以下链接可以看到更多的使用例子

/example

Vue.js ​

vue
<template>
   <div ref="$container" />
 </template>
 
@@ -51,7 +51,7 @@ import{_ as i,c as a,o as n,ak as l}from"./chunks/framework.xxfEszSJ.js";const g
   art.value.destroy(false)
 })
 </script>
vue
<template>
-  <Artplayer :option="option" :style="style" @get-instance="getInstance" />
+  <Artplayer :option="option" :style="style" @get-instance="getInstance" />
 </template>
 
 <script setup>
@@ -71,7 +71,7 @@ import{_ as i,c as a,o as n,ak as l}from"./chunks/framework.xxfEszSJ.js";const g
 function getInstance(art) {
   console.log(art)
 }
-</script>

Artplayer 非响应式:

在 Vue.js 里直接修改 option 是不会改变播放器的

React.js ​

jsx
import Artplayer from 'artplayer'
+</script>

Artplayer 非响应式:

在 Vue.js 里直接修改 option 是不会改变播放器的

React.js ​

jsx
import Artplayer from 'artplayer'
 import { useEffect, useRef } from 'react'
 
 export default function Player({ option, getInstance, ...rest }) {
@@ -154,7 +154,7 @@ import{_ as i,c as a,o as n,ak as l}from"./chunks/framework.xxfEszSJ.js";const g
 
 option.volume = 0.5;
 
-const art8 = new Artplayer(option);

古老的浏览器 ​

生产构建的 artplayer.js 只兼容最新一个主版本的 Chrome:last 1 Chrome version

对于古老的浏览器,可以使用 artplayer.legacy.js 文件,可以兼容到:IE 11

js
import Artplayer from 'artplayer/legacy'
bash
https://cdn.jsdelivr.net/npm/artplayer/dist/artplayer.legacy.js
bash
https://unpkg.com/artplayer/dist/artplayer.legacy.js

假如你要兼容更古老的浏览器时,请修改以下配置然后自行构建:

构建配置:scripts/build.js

参考文档:browserslist

ECMAScript Module ​

从 5.2.6 开始,artplayer 和所有插件还会提供一个 ESM 版本的 mjs,如:

  • artplayer/dist/artplayer.mjs
  • artplayer-plugin-danmuku/dist/artplayer-plugin-danmuku.mjs
html
<!DOCTYPE html>
+const art8 = new Artplayer(option);

古老的浏览器 ​

生产构建的 artplayer.js 只兼容最新一个主版本的 Chrome:last 1 Chrome version

对于古老的浏览器,可以使用 artplayer.legacy.js 文件,可以兼容到:IE 11

js
import Artplayer from 'artplayer/legacy'
bash
https://cdn.jsdelivr.net/npm/artplayer/dist/artplayer.legacy.js
bash
https://unpkg.com/artplayer/dist/artplayer.legacy.js

假如你要兼容更古老的浏览器时,请修改以下配置然后自行构建:

构建配置:scripts/build.js

参考文档:browserslist

ECMAScript Module ​

从 5.2.6 开始,artplayer 和所有插件还会提供一个 ESM 版本的 mjs,如:

  • artplayer/dist/artplayer.mjs
  • artplayer-plugin-danmuku/dist/artplayer-plugin-danmuku.mjs
html
<!DOCTYPE html>
 <html lang="en">
 
 <head>
diff --git a/docs/document/assets/index.md.CDZ-sHkw.lean.js b/docs/document/assets/index.md.BaNZbFwu.lean.js
similarity index 100%
rename from docs/document/assets/index.md.CDZ-sHkw.lean.js
rename to docs/document/assets/index.md.BaNZbFwu.lean.js
diff --git a/docs/document/assets/plugin_danmuku.md.pX46PRX9.js b/docs/document/assets/plugin_danmuku.md.Dz71RGDv.js
similarity index 99%
rename from docs/document/assets/plugin_danmuku.md.pX46PRX9.js
rename to docs/document/assets/plugin_danmuku.md.Dz71RGDv.js
index a7ce703ef..6f6e055b2 100644
--- a/docs/document/assets/plugin_danmuku.md.pX46PRX9.js
+++ b/docs/document/assets/plugin_danmuku.md.Dz71RGDv.js
@@ -1,4 +1,4 @@
-import{_ as n,c as l,o as p,ak as s,j as i}from"./chunks/framework.xxfEszSJ.js";const y=JSON.parse('{"title":"弹幕库","description":"","frontmatter":{},"headers":[],"relativePath":"plugin/danmuku.md","filePath":"plugin/danmuku.md","lastUpdated":1734270991000}'),h={name:"plugin/danmuku.md"};function e(k,a,t,r,E,d){return p(),l("div",null,a[0]||(a[0]=[s(`

弹幕库 ​

演示 ​

👉 查看完整演示

安装 ​

bash
npm install artplayer-plugin-danmuku
bash
yarn add artplayer-plugin-danmuku
bash
pnpm add artplayer-plugin-danmuku
html
<script src="path/to/artplayer-plugin-danmuku.js"></script>

CDN ​

bash
https://cdn.jsdelivr.net/npm/artplayer-plugin-danmuku/dist/artplayer-plugin-danmuku.js
bash
https://unpkg.com/artplayer-plugin-danmuku/dist/artplayer-plugin-danmuku.js

弹幕结构 ​

每一个弹幕是一个对象,多个弹幕组成的数组就是弹幕库,通常只需要text就可以发送一个弹幕,其余都是非必要参数

js
{
+import{_ as n,c as l,o as p,ak as s,j as i}from"./chunks/framework.xxfEszSJ.js";const y=JSON.parse('{"title":"弹幕库","description":"","frontmatter":{},"headers":[],"relativePath":"plugin/danmuku.md","filePath":"plugin/danmuku.md","lastUpdated":1734270991000}'),h={name:"plugin/danmuku.md"};function e(k,a,t,r,E,d){return p(),l("div",null,a[0]||(a[0]=[s(`

弹幕库 ​

演示 ​

👉 查看完整演示

安装 ​

bash
npm install artplayer-plugin-danmuku
bash
yarn add artplayer-plugin-danmuku
bash
pnpm add artplayer-plugin-danmuku
html
<script src="path/to/artplayer-plugin-danmuku.js"></script>

CDN ​

bash
https://cdn.jsdelivr.net/npm/artplayer-plugin-danmuku/dist/artplayer-plugin-danmuku.js
bash
https://unpkg.com/artplayer-plugin-danmuku/dist/artplayer-plugin-danmuku.js

弹幕结构 ​

每一个弹幕是一个对象,多个弹幕组成的数组就是弹幕库,通常只需要text就可以发送一个弹幕,其余都是非必要参数

js
{
     text: '', // 弹幕文本
     time: 10, // 弹幕时间, 默认为当前播放器时间
     mode: 0, // 弹幕模式: 0: 滚动(默认),1: 顶部,2: 底部
diff --git a/docs/document/assets/plugin_danmuku.md.pX46PRX9.lean.js b/docs/document/assets/plugin_danmuku.md.Dz71RGDv.lean.js
similarity index 100%
rename from docs/document/assets/plugin_danmuku.md.pX46PRX9.lean.js
rename to docs/document/assets/plugin_danmuku.md.Dz71RGDv.lean.js
diff --git a/docs/document/assets/start_i18n.md.BrnMiJ2K.js b/docs/document/assets/start_i18n.md.CpGYSiAS.js
similarity index 98%
rename from docs/document/assets/start_i18n.md.BrnMiJ2K.js
rename to docs/document/assets/start_i18n.md.CpGYSiAS.js
index a4f8a8da6..4e8fb1511 100644
--- a/docs/document/assets/start_i18n.md.BrnMiJ2K.js
+++ b/docs/document/assets/start_i18n.md.CpGYSiAS.js
@@ -2,7 +2,7 @@ import{_ as a,c as i,o as n,ak as l}from"./chunks/framework.xxfEszSJ.js";const c
     container: '.artplayer-app',
     url: '/assets/sample/video.mp4',
     lang: 'zh-cn', // or 'en'
-});

导入语言 ​

打包前的语言文件存放于: artplayer/src/i18n/*.js, 欢迎来添加你的语言

打包后的语言文件存放于: artplayer/dist/i18n/*.js

js
import id from 'artplayer/i18n/id';
+});

导入语言 ​

打包前的语言文件存放于: artplayer/src/i18n/*.js, 欢迎来添加你的语言

打包后的语言文件存放于: artplayer/dist/i18n/*.js

js
import id from 'artplayer/i18n/id';
 import zhTw from 'artplayer/i18n/zh-tw';
 
 var art = new Artplayer({
diff --git a/docs/document/assets/start_i18n.md.BrnMiJ2K.lean.js b/docs/document/assets/start_i18n.md.CpGYSiAS.lean.js
similarity index 100%
rename from docs/document/assets/start_i18n.md.BrnMiJ2K.lean.js
rename to docs/document/assets/start_i18n.md.CpGYSiAS.lean.js
diff --git a/docs/document/component/contextmenu.html b/docs/document/component/contextmenu.html
index aede92062..856e6f2c2 100644
--- a/docs/document/component/contextmenu.html
+++ b/docs/document/component/contextmenu.html
@@ -106,7 +106,7 @@
         })
     }, 3000);
 });
- + \ No newline at end of file diff --git a/docs/document/component/controls.html b/docs/document/component/controls.html index 20ba5cbbb..f605241ff 100644 --- a/docs/document/component/controls.html +++ b/docs/document/component/controls.html @@ -153,7 +153,7 @@ }); }, 3000); });
- + \ No newline at end of file diff --git a/docs/document/component/layers.html b/docs/document/component/layers.html index 38bbc3d0f..cf2fed27e 100644 --- a/docs/document/component/layers.html +++ b/docs/document/component/layers.html @@ -125,7 +125,7 @@ }); }, 3000); }); - + \ No newline at end of file diff --git a/docs/document/component/setting.html b/docs/document/component/setting.html index 6c094be50..5f8946935 100644 --- a/docs/document/component/setting.html +++ b/docs/document/component/setting.html @@ -245,7 +245,7 @@ }); }, 3000); }); - + \ No newline at end of file diff --git a/docs/document/en/advanced/built-in.html b/docs/document/en/advanced/built-in.html index a884d5429..2d9424d98 100644 --- a/docs/document/en/advanced/built-in.html +++ b/docs/document/en/advanced/built-in.html @@ -217,7 +217,7 @@ art.on('ready', () => { art.plugins.add(myPlugin); }); - + \ No newline at end of file diff --git a/docs/document/en/advanced/class.html b/docs/document/en/advanced/class.html index a27c615a4..658daf023 100644 --- a/docs/document/en/advanced/class.html +++ b/docs/document/en/advanced/class.html @@ -31,7 +31,7 @@ }); console.info([...Artplayer.instances]);

version ​

Returns the version information of the player.

▶ Run Code
js
console.info(Artplayer.version);

env ​

Returns the environment variables of the player.

▶ Run Code
js
console.info(Artplayer.env);

build ​

Returns the build time of the player.

▶ Run Code
js
console.info(Artplayer.build);

config ​

Returns the default configuration for videos.

▶ Run Code
js
console.info(Artplayer.config);

utils ​

Returns the collection of utility functions for the player.

▶ Run Code
js
console.info(Artplayer.utils);

For all utility functions, please refer to the following address:

artplayer/types/utils.d.ts

scheme ​

Returns the validation schema for player options.

▶ Run Code
js
console.info(Artplayer.scheme);

Emitter ​

Returns the constructor function for the event emitter.

▶ Run Code
js
console.info(Artplayer.Emitter);

validator ​

Returns the validation function for options.

▶ Run Code
js
console.info(Artplayer.validator);

kindOf ​

Returns the utility function for type detection.

▶ Run Code
js
console.info(Artplayer.kindOf);

html ​

Returns the html string required by the player.

▶ Run Code
js
console.info(Artplayer.html);

option ​

Returns the default options for the player.

▶ Run Code
js
console.info(Artplayer.option);
- + \ No newline at end of file diff --git a/docs/document/en/advanced/event.html b/docs/document/en/advanced/event.html index fb49eded9..d362f7ba9 100644 --- a/docs/document/en/advanced/event.html +++ b/docs/document/en/advanced/event.html @@ -385,7 +385,7 @@ art.on('keydown', (event) => { console.log(event.code); });

video:canplay ​

The browser can start playing the media, but estimates there isn't enough data to play through to the end without having to stop for further buffering

video:canplaythrough ​

The browser estimates it can play the media through to the end without stopping to buffer content

video:complete ​

OfflineAudioContext rendering is complete

video:durationchange ​

Triggered when the value of the duration property changes

video:emptied ​

The media has become empty; for example, this event is sent when the media has already been loaded (or partially loaded), and the load() method is called to reload it

video:ended ​

Playback has stopped because the media has reached its end point

video:error ​

An error occurred while fetching media data, or the resource type is not a supported media format

video:loadeddata ​

The first frame of the media has finished loading

video:loadedmetadata ​

Metadata has been loaded

video:pause ​

Playback has been paused

video:play ​

Playback has begun

video:playing ​

Playback is ready to start after having been paused or delayed due to lack of data

video:progress ​

Periodically triggered while the browser is loading the resource

video:ratechange ​

The playback rate has changed

video:seeked ​

A seek operation has completed

video:seeking ​

A seek operation has begun

video:stalled ​

The user agent is trying to fetch media data, but data is unexpectedly not forthcoming

video:suspend ​

Media data loading has been suspended

video:timeupdate ​

The time indicated by the currentTime attribute has been updated

video:volumechange ​

The volume has changed

video:waiting ​

Playback has stopped due to temporary lack of data

- + \ No newline at end of file diff --git a/docs/document/en/advanced/global.html b/docs/document/en/advanced/global.html index 7c6403b1b..1b1fb124d 100644 --- a/docs/document/en/advanced/global.html +++ b/docs/document/en/advanced/global.html @@ -248,7 +248,7 @@ // Only destroys the UI, does not actively clear src art.destroy(); - + \ No newline at end of file diff --git a/docs/document/en/advanced/plugin.html b/docs/document/en/advanced/plugin.html index 77ad58e41..b4defc3e0 100644 --- a/docs/document/en/advanced/plugin.html +++ b/docs/document/en/advanced/plugin.html @@ -122,7 +122,7 @@ }) ], }); - + \ No newline at end of file diff --git a/docs/document/en/advanced/property.html b/docs/document/en/advanced/property.html index 8b98926c1..cebb44d72 100644 --- a/docs/document/en/advanced/property.html +++ b/docs/document/en/advanced/property.html @@ -457,7 +457,7 @@ art.on('ready', () => { art.subtitleOffset = 1; }); - + \ No newline at end of file diff --git a/docs/document/en/component/contextmenu.html b/docs/document/en/component/contextmenu.html index cefec544c..bb25aa902 100644 --- a/docs/document/en/component/contextmenu.html +++ b/docs/document/en/component/contextmenu.html @@ -106,7 +106,7 @@ }) }, 3000); }); - + \ No newline at end of file diff --git a/docs/document/en/component/controls.html b/docs/document/en/component/controls.html index 7e373467b..667b4fb4d 100644 --- a/docs/document/en/component/controls.html +++ b/docs/document/en/component/controls.html @@ -153,7 +153,7 @@ }); }, 3000); }); - + \ No newline at end of file diff --git a/docs/document/en/component/layers.html b/docs/document/en/component/layers.html index 7ac5172f7..8724a88e3 100644 --- a/docs/document/en/component/layers.html +++ b/docs/document/en/component/layers.html @@ -125,7 +125,7 @@ }); }, 3000); }); - + \ No newline at end of file diff --git a/docs/document/en/component/setting.html b/docs/document/en/component/setting.html index 1b604dfff..2249350f3 100644 --- a/docs/document/en/component/setting.html +++ b/docs/document/en/component/setting.html @@ -245,7 +245,7 @@ }); }, 3000); }); - + \ No newline at end of file diff --git a/docs/document/en/index.html b/docs/document/en/index.html index 30520e085..b6e5ded35 100644 --- a/docs/document/en/index.html +++ b/docs/document/en/index.html @@ -13,7 +13,7 @@ - + @@ -23,7 +23,7 @@ -
Skip to content

Installation & Usage ​

Installation ​

bash
npm install artplayer
bash
yarn add artplayer
bash
pnpm add artplayer
html
<script src="path/to/artplayer.js"></script>

CDN ​

bash
https://cdn.jsdelivr.net/npm/artplayer/dist/artplayer.js
bash
https://unpkg.com/artplayer/dist/artplayer.js

Usage ​

html
<html>
+    
Skip to content

Installation & Usage ​

Installation ​

bash
npm install artplayer
bash
yarn add artplayer
bash
pnpm add artplayer
html
<script src="path/to/artplayer.js"></script>

CDN ​

bash
https://cdn.jsdelivr.net/npm/artplayer/dist/artplayer.js
bash
https://unpkg.com/artplayer/dist/artplayer.js

Usage ​

html
<html>
     <head>
         <title>ArtPlayer Demo</title>
         <meta charset="UTF-8" />
@@ -44,7 +44,7 @@
           });
         </script>
     </body>
-</html>

Note

The player's dimensions depend on the size of its container container, so your container must have defined dimensions.

See more usage examples at the following link:

/example

Vue.js ​

vue
<template>
+</html>

Note

The player's dimensions depend on the size of its container container, so your container must have defined dimensions.

See more usage examples at the following link:

/example

Vue.js ​

vue
<template>
   <div ref="$container" />
 </template>
 
@@ -76,7 +76,7 @@
   art.value.destroy(false)
 })
 </script>
vue
<template>
-  <Artplayer :option="option" :style="style" @get-instance="getInstance" />
+  <Artplayer :option="option" :style="style" @get-instance="getInstance" />
 </template>
 
 <script setup>
@@ -96,7 +96,7 @@
 function getInstance(art) {
   console.log(art)
 }
-</script>

Artplayer is not reactive:

Directly modifying option in Vue.js will not update the player.

React.js ​

jsx
import Artplayer from 'artplayer'
+</script>

Artplayer is not reactive:

Directly modifying option in Vue.js will not update the player.

React.js ​

jsx
import Artplayer from 'artplayer'
 import { useEffect, useRef } from 'react'
 
 export default function Player({ option, getInstance, ...rest }) {
@@ -179,7 +179,7 @@
 
 option.volume = 0.5;
 
-const art8 = new Artplayer(option);

Legacy Browsers ​

The production build artplayer.js only supports the latest major version of Chrome: last 1 Chrome version

For legacy browsers, you can use the artplayer.legacy.js file, which supports compatibility down to: IE 11

js
import Artplayer from 'artplayer/legacy'
bash
https://cdn.jsdelivr.net/npm/artplayer/dist/artplayer.legacy.js
bash
https://unpkg.com/artplayer/dist/artplayer.legacy.js

If you need to support even older browsers, modify the following configuration and build it yourself:

Build configuration: scripts/build.js

Reference documentation: browserslist

ECMAScript Module ​

Starting from 5.2.6, artplayer and all plugins also provide an ESM version mjs, such as:

  • artplayer/dist/artplayer.mjs
  • artplayer-plugin-danmuku/dist/artplayer-plugin-danmuku.mjs
html
<!DOCTYPE html>
+const art8 = new Artplayer(option);

Legacy Browsers ​

The production build artplayer.js only supports the latest major version of Chrome: last 1 Chrome version

For legacy browsers, you can use the artplayer.legacy.js file, which supports compatibility down to: IE 11

js
import Artplayer from 'artplayer/legacy'
bash
https://cdn.jsdelivr.net/npm/artplayer/dist/artplayer.legacy.js
bash
https://unpkg.com/artplayer/dist/artplayer.legacy.js

If you need to support even older browsers, modify the following configuration and build it yourself:

Build configuration: scripts/build.js

Reference documentation: browserslist

ECMAScript Module ​

Starting from 5.2.6, artplayer and all plugins also provide an ESM version mjs, such as:

  • artplayer/dist/artplayer.mjs
  • artplayer-plugin-danmuku/dist/artplayer-plugin-danmuku.mjs
html
<!DOCTYPE html>
 <html lang="en">
 
 <head>
@@ -237,7 +237,7 @@
         </script>
     </body>
 </html>

Note

You need to modify it before importing the Artplayer dependency for it to take effect.

- + \ No newline at end of file diff --git a/docs/document/en/start/i18n.html b/docs/document/en/start/i18n.html index 3baf4f188..e9b1ef9e4 100644 --- a/docs/document/en/start/i18n.html +++ b/docs/document/en/start/i18n.html @@ -13,7 +13,7 @@ - + @@ -27,7 +27,7 @@ container: '.artplayer-app', url: '/assets/sample/video.mp4', lang: 'zh-cn', // or 'en' -});

Importing Languages ​

Language files before bundling are located at: artplayer/src/i18n/*.js. Contributions to add your language are welcome.

Language files after bundling are located at: artplayer/dist/i18n/*.js

js
import id from 'artplayer/i18n/id';
+});

Importing Languages ​

Language files before bundling are located at: artplayer/src/i18n/*.js. Contributions to add your language are welcome.

Language files after bundling are located at: artplayer/dist/i18n/*.js

js
import id from 'artplayer/i18n/id';
 import zhTw from 'artplayer/i18n/zh-tw';
 
 var art = new Artplayer({
@@ -75,7 +75,7 @@
         },
     },
 });
- + \ No newline at end of file diff --git a/docs/document/en/start/option.html b/docs/document/en/start/option.html index 966285b3e..699be562d 100644 --- a/docs/document/en/start/option.html +++ b/docs/document/en/start/option.html @@ -415,7 +415,7 @@ url: '/assets/sample/video.mp4', proxy: () => document.createElement('video') }); - + \ No newline at end of file diff --git a/docs/document/hashmap.json b/docs/document/hashmap.json index 0c5233a9b..0280d69d4 100644 --- a/docs/document/hashmap.json +++ b/docs/document/hashmap.json @@ -1 +1 @@ -{"advanced_built-in.md":"DiyRIcIA","advanced_class.md":"Da3aE0pP","advanced_event.md":"mrsB0MsK","advanced_global.md":"Bdw3azKs","advanced_plugin.md":"B3Pobmcq","advanced_property.md":"CA7GaeI3","component_contextmenu.md":"ClKmcIKr","component_controls.md":"Cl62yW1F","component_layers.md":"Cys52VMi","component_setting.md":"BP5674ir","en_advanced_built-in.md":"B_F31aPz","en_advanced_class.md":"D17lDToP","en_advanced_event.md":"Cw7LYSEa","en_advanced_global.md":"DwHxhtQU","en_advanced_plugin.md":"Cnaq654P","en_advanced_property.md":"JV0Ib3j3","en_component_contextmenu.md":"Dn3gMYMB","en_component_controls.md":"BRzTYykf","en_component_layers.md":"B88JJHwY","en_component_setting.md":"C5z-_-Yy","en_index.md":"B6J2cqvj","en_start_i18n.md":"BhiDfadM","en_start_option.md":"Bei8B6RP","index.md":"CDZ-sHkw","plugin_danmuku.md":"pX46PRX9","start_i18n.md":"BrnMiJ2K","start_option.md":"D52S8Ynf"} +{"advanced_built-in.md":"DiyRIcIA","advanced_class.md":"Da3aE0pP","advanced_event.md":"mrsB0MsK","advanced_global.md":"Bdw3azKs","advanced_plugin.md":"B3Pobmcq","advanced_property.md":"CA7GaeI3","component_contextmenu.md":"ClKmcIKr","component_controls.md":"Cl62yW1F","component_layers.md":"Cys52VMi","component_setting.md":"BP5674ir","en_advanced_built-in.md":"B_F31aPz","en_advanced_class.md":"D17lDToP","en_advanced_event.md":"Cw7LYSEa","en_advanced_global.md":"DwHxhtQU","en_advanced_plugin.md":"Cnaq654P","en_advanced_property.md":"JV0Ib3j3","en_component_contextmenu.md":"Dn3gMYMB","en_component_controls.md":"BRzTYykf","en_component_layers.md":"B88JJHwY","en_component_setting.md":"C5z-_-Yy","en_index.md":"D_XAyEyy","en_start_i18n.md":"fbCR_PMw","en_start_option.md":"Bei8B6RP","index.md":"BaNZbFwu","plugin_danmuku.md":"Dz71RGDv","start_i18n.md":"CpGYSiAS","start_option.md":"D52S8Ynf"} diff --git a/docs/document/index.html b/docs/document/index.html index 49be1af96..b67b34fd6 100644 --- a/docs/document/index.html +++ b/docs/document/index.html @@ -13,7 +13,7 @@ - + @@ -23,7 +23,7 @@ -
Skip to content

安装使用 ​

安装 ​

bash
npm install artplayer
bash
yarn add artplayer
bash
pnpm add artplayer
html
<script src="path/to/artplayer.js"></script>

CDN ​

bash
https://cdn.jsdelivr.net/npm/artplayer/dist/artplayer.js
bash
https://unpkg.com/artplayer/dist/artplayer.js

使用 ​

html
<html>
+    
Skip to content

安装使用 ​

安装 ​

bash
npm install artplayer
bash
yarn add artplayer
bash
pnpm add artplayer
html
<script src="path/to/artplayer.js"></script>

CDN ​

bash
https://cdn.jsdelivr.net/npm/artplayer/dist/artplayer.js
bash
https://unpkg.com/artplayer/dist/artplayer.js

使用 ​

html
<html>
     <head>
         <title>ArtPlayer Demo</title>
         <meta charset="UTF-8" />
@@ -44,7 +44,7 @@
           });
         </script>
     </body>
-</html>

提示

播放器的尺寸依赖于容器 container 的尺寸,所以你的容器 container 必须是有尺寸的

以下链接可以看到更多的使用例子

/example

Vue.js ​

vue
<template>
+</html>

提示

播放器的尺寸依赖于容器 container 的尺寸,所以你的容器 container 必须是有尺寸的

以下链接可以看到更多的使用例子

/example

Vue.js ​

vue
<template>
   <div ref="$container" />
 </template>
 
@@ -76,7 +76,7 @@
   art.value.destroy(false)
 })
 </script>
vue
<template>
-  <Artplayer :option="option" :style="style" @get-instance="getInstance" />
+  <Artplayer :option="option" :style="style" @get-instance="getInstance" />
 </template>
 
 <script setup>
@@ -96,7 +96,7 @@
 function getInstance(art) {
   console.log(art)
 }
-</script>

Artplayer 非响应式:

在 Vue.js 里直接修改 option 是不会改变播放器的

React.js ​

jsx
import Artplayer from 'artplayer'
+</script>

Artplayer 非响应式:

在 Vue.js 里直接修改 option 是不会改变播放器的

React.js ​

jsx
import Artplayer from 'artplayer'
 import { useEffect, useRef } from 'react'
 
 export default function Player({ option, getInstance, ...rest }) {
@@ -179,7 +179,7 @@
 
 option.volume = 0.5;
 
-const art8 = new Artplayer(option);

古老的浏览器 ​

生产构建的 artplayer.js 只兼容最新一个主版本的 Chrome:last 1 Chrome version

对于古老的浏览器,可以使用 artplayer.legacy.js 文件,可以兼容到:IE 11

js
import Artplayer from 'artplayer/legacy'
bash
https://cdn.jsdelivr.net/npm/artplayer/dist/artplayer.legacy.js
bash
https://unpkg.com/artplayer/dist/artplayer.legacy.js

假如你要兼容更古老的浏览器时,请修改以下配置然后自行构建:

构建配置:scripts/build.js

参考文档:browserslist

ECMAScript Module ​

从 5.2.6 开始,artplayer 和所有插件还会提供一个 ESM 版本的 mjs,如:

  • artplayer/dist/artplayer.mjs
  • artplayer-plugin-danmuku/dist/artplayer-plugin-danmuku.mjs
html
<!DOCTYPE html>
+const art8 = new Artplayer(option);

古老的浏览器 ​

生产构建的 artplayer.js 只兼容最新一个主版本的 Chrome:last 1 Chrome version

对于古老的浏览器,可以使用 artplayer.legacy.js 文件,可以兼容到:IE 11

js
import Artplayer from 'artplayer/legacy'
bash
https://cdn.jsdelivr.net/npm/artplayer/dist/artplayer.legacy.js
bash
https://unpkg.com/artplayer/dist/artplayer.legacy.js

假如你要兼容更古老的浏览器时,请修改以下配置然后自行构建:

构建配置:scripts/build.js

参考文档:browserslist

ECMAScript Module ​

从 5.2.6 开始,artplayer 和所有插件还会提供一个 ESM 版本的 mjs,如:

  • artplayer/dist/artplayer.mjs
  • artplayer-plugin-danmuku/dist/artplayer-plugin-danmuku.mjs
html
<!DOCTYPE html>
 <html lang="en">
 
 <head>
@@ -237,7 +237,7 @@
         </script>
     </body>
 </html>

提示

你需要在引入 Artplayer 依赖前来修改它才会生效

- + \ No newline at end of file diff --git a/docs/document/plugin/danmuku.html b/docs/document/plugin/danmuku.html index f38d4d1e7..2d7d498f5 100644 --- a/docs/document/plugin/danmuku.html +++ b/docs/document/plugin/danmuku.html @@ -13,7 +13,7 @@ - + @@ -23,7 +23,7 @@ -
Skip to content

弹幕库 ​

演示 ​

👉 查看完整演示

安装 ​

bash
npm install artplayer-plugin-danmuku
bash
yarn add artplayer-plugin-danmuku
bash
pnpm add artplayer-plugin-danmuku
html
<script src="path/to/artplayer-plugin-danmuku.js"></script>

CDN ​

bash
https://cdn.jsdelivr.net/npm/artplayer-plugin-danmuku/dist/artplayer-plugin-danmuku.js
bash
https://unpkg.com/artplayer-plugin-danmuku/dist/artplayer-plugin-danmuku.js

弹幕结构 ​

每一个弹幕是一个对象,多个弹幕组成的数组就是弹幕库,通常只需要text就可以发送一个弹幕,其余都是非必要参数

js
{
+    
Skip to content

弹幕库 ​

演示 ​

👉 查看完整演示

安装 ​

bash
npm install artplayer-plugin-danmuku
bash
yarn add artplayer-plugin-danmuku
bash
pnpm add artplayer-plugin-danmuku
html
<script src="path/to/artplayer-plugin-danmuku.js"></script>

CDN ​

bash
https://cdn.jsdelivr.net/npm/artplayer-plugin-danmuku/dist/artplayer-plugin-danmuku.js
bash
https://unpkg.com/artplayer-plugin-danmuku/dist/artplayer-plugin-danmuku.js

弹幕结构 ​

每一个弹幕是一个对象,多个弹幕组成的数组就是弹幕库,通常只需要text就可以发送一个弹幕,其余都是非必要参数

js
{
     text: '', // 弹幕文本
     time: 10, // 弹幕时间, 默认为当前播放器时间
     mode: 0, // 弹幕模式: 0: 滚动(默认),1: 顶部,2: 底部
@@ -367,7 +367,7 @@
 art.on('artplayerPluginDanmuku:destroy', () => {
     console.info('弹幕销毁');
 });
- + \ No newline at end of file diff --git a/docs/document/start/i18n.html b/docs/document/start/i18n.html index 3f423f505..b21275985 100644 --- a/docs/document/start/i18n.html +++ b/docs/document/start/i18n.html @@ -13,7 +13,7 @@ - + @@ -27,7 +27,7 @@ container: '.artplayer-app', url: '/assets/sample/video.mp4', lang: 'zh-cn', // or 'en' -});

导入语言 ​

打包前的语言文件存放于: artplayer/src/i18n/*.js, 欢迎来添加你的语言

打包后的语言文件存放于: artplayer/dist/i18n/*.js

js
import id from 'artplayer/i18n/id';
+});

导入语言 ​

打包前的语言文件存放于: artplayer/src/i18n/*.js, 欢迎来添加你的语言

打包后的语言文件存放于: artplayer/dist/i18n/*.js

js
import id from 'artplayer/i18n/id';
 import zhTw from 'artplayer/i18n/zh-tw';
 
 var art = new Artplayer({
@@ -75,7 +75,7 @@
         },
     },
 });
- + \ No newline at end of file diff --git a/docs/document/start/option.html b/docs/document/start/option.html index 97fb23da3..dfeb8c007 100644 --- a/docs/document/start/option.html +++ b/docs/document/start/option.html @@ -415,7 +415,7 @@ url: '/assets/sample/video.mp4', proxy: () => document.createElement('video') });
- + \ No newline at end of file diff --git a/packages/artplayer-plugin-ads/dist/artplayer-plugin-ads.mjs b/packages/artplayer-plugin-ads/dist/artplayer-plugin-ads.mjs index b2c413ed7..b5132a64f 100644 --- a/packages/artplayer-plugin-ads/dist/artplayer-plugin-ads.mjs +++ b/packages/artplayer-plugin-ads/dist/artplayer-plugin-ads.mjs @@ -4,4 +4,248 @@ * (c) 2017-2026 Harvey Zhao * Released under the MIT License. */ -function l(e){return n=>{!function(e){const{version:n,utils:{errorHandle:a}}=e.constructor,i=n.split(".").map(Number);a(i[0]+i[1]/100>=5,`Artplayer.js@${n} is not compatible the artplayerPluginAds@${l.version}. Please update it to version Artplayer.js@5.x.x`)}(n);const{template:{$player:a},icons:{volume:i,volumeClose:t,fullscreenOn:r,fullscreenOff:d,loading:o},constructor:{validator:s,utils:{query:p,append:u,setStyle:c}}}=n;e=s({html:"",video:"",url:"",playDuration:5,totalDuration:10,muted:!1,i18n:{close:"\u5173\u95ed\u5e7f\u544a",countdown:"%s\u79d2",detail:"\u67e5\u770b\u8be6\u60c5",canBeClosed:"%s\u79d2\u540e\u53ef\u5173\u95ed\u5e7f\u544a"},...e},{html:"?string",video:"?string",url:"?string",playDuration:"number",totalDuration:"number",muted:"?boolean",i18n:{close:"string",countdown:"string",detail:"string",canBeClosed:"string"}});let y=null,g=null,m=null,f=null,v=null,x=null,h=0,b=null,w=!1,$=!1,k=!1;function D(l,e){return e.replace("%s",l)}function A(){w=!0,n.play(),e.video&&y.pause(),c(n.template.$ads,"display","none"),n.emit("artplayerPluginAds:skip",e)}function C(){w||(b=setTimeout(()=>{h+=1;const l=e.playDuration-h;l>=1?m.innerHTML=D(l,e.i18n.canBeClosed):(m.innerHTML=e.i18n.close,k||(k=!0)),f.innerHTML=D(e.totalDuration-h,e.i18n.countdown),h>=e.totalDuration?A():C()},1e3))}function P(){w||clearTimeout(b)}function B(){$||($=!0,function(){n.template.$ads=u(a,'
'),y=u(n.template.$ads,e.video?``:`
${e.html}
`),x=u(n.template.$ads,'
'),u(x,o),g=u(n.template.$ads,`
\n
${e.playDuration<=0?e.i18n.close:D(e.playDuration,e.i18n.canBeClosed)}
\n
${D(e.totalDuration,e.i18n.countdown)}
\n
`),m=p(".artplayer-plugin-ads-close",g),f=p(".artplayer-plugin-ads-countdown",g),e.playDuration>=e.totalDuration&&c(m,"display","none"),n.proxy(m,"click",()=>{k&&A()}),v=u(n.template.$ads,`
\n
${e.i18n.detail}
\n
\n
\n
`);const l=p(".artplayer-plugin-ads-detail",v),s=p(".artplayer-plugin-ads-muted",v),h=p(".artplayer-plugin-ads-fullscreen",v);if(e.url?n.proxy(l,"click",()=>{window.open(e.url),n.emit("artplayerPluginAds:click",e)}):c(l,"display","none"),e.video){const l=u(s,i),a=u(s,t);c(a,"display","none"),e.muted&&(y.muted=!0,c(l,"display","none"),c(a,"display","inline-flex")),n.proxy(s,"click",()=>{y.muted=!y.muted,y.muted?(c(l,"display","none"),c(a,"display","inline-flex")):(c(l,"display","inline-flex"),c(a,"display","none"))})}else c(s,"display","none");const b=u(h,r),w=u(h,d);c(w,"display","none"),n.proxy(h,"click",()=>{n.fullscreen=!n.fullscreen,n.fullscreen?(c(b,"display","inline-flex"),c(w,"display","none")):(c(b,"display","none"),c(w,"display","inline-flex"))}),n.proxy(y,"click",()=>{e.url&&window.open(e.url),n.emit("artplayerPluginAds:click",e)})}(),n.pause(),e.video?(n.proxy(y,"error",A),n.proxy(y,"loadedmetadata",()=>{C(),y.play(),c(g,"display","flex"),c(v,"display","flex"),c(x,"display","none")})):(C(),c(g,"display","flex"),c(v,"display","flex"),c(x,"display","none")),n.on("document:visibilitychange",()=>{document.hidden?P():C()}))}return n.on("ready",()=>{n.once("play",B),n.once("video:playing",B)}),{name:"artplayerPluginAds",skip:A,pause:P,play:C}}}if("undefined"!==typeof document&&!document.getElementById("artplayer-plugin-ads")){const l=document.createElement("style");l.id="artplayer-plugin-ads",l.textContent=".artplayer-plugin-ads{position:absolute;z-index:150;inset:0;width:100%;height:100%;overflow:hidden;font-size:13px;line-height:1;color:#fff;background-color:#000}.artplayer-plugin-ads .artplayer-plugin-ads-html{display:flex;align-items:center;justify-content:center;width:100%;height:100%}.artplayer-plugin-ads .artplayer-plugin-ads-video{width:100%;height:100%}.artplayer-plugin-ads .artplayer-plugin-ads-timer{display:none;position:absolute;top:10px;right:10px}.artplayer-plugin-ads .artplayer-plugin-ads-timer>div{display:flex;align-items:center;background-color:#00000080;border-radius:15px;margin-left:5px;padding:5px 10px;cursor:pointer}.artplayer-plugin-ads .artplayer-plugin-ads-control{display:none;position:absolute;bottom:10px;right:10px}.artplayer-plugin-ads .artplayer-plugin-ads-control>div{display:flex;align-items:center;background-color:#00000080;border-radius:15px;margin-left:5px;padding:5px 10px;cursor:pointer}.artplayer-plugin-ads .artplayer-plugin-ads-control .art-icon svg{width:20px;height:20px}.artplayer-plugin-ads .artplayer-plugin-ads-loading{display:flex;align-items:center;justify-content:center;position:absolute;inset:0;width:100%;height:100%}",document.head.appendChild(l)}export{l as default}; +const style = ".artplayer-plugin-ads {\n position: absolute;\n z-index: 150;\n left: 0;\n top: 0;\n right: 0;\n bottom: 0;\n width: 100%;\n height: 100%;\n overflow: hidden;\n font-size: 13px;\n line-height: 1;\n color: #fff;\n background-color: #000;\n}\n.artplayer-plugin-ads .artplayer-plugin-ads-html {\n display: flex;\n align-items: center;\n justify-content: center;\n width: 100%;\n height: 100%;\n}\n.artplayer-plugin-ads .artplayer-plugin-ads-video {\n width: 100%;\n height: 100%;\n}\n.artplayer-plugin-ads .artplayer-plugin-ads-timer {\n display: none;\n position: absolute;\n top: 10px;\n right: 10px;\n}\n.artplayer-plugin-ads .artplayer-plugin-ads-timer > div {\n display: flex;\n align-items: center;\n background-color: rgba(0, 0, 0, 0.5);\n border-radius: 15px;\n margin-left: 5px;\n padding: 5px 10px;\n cursor: pointer;\n}\n.artplayer-plugin-ads .artplayer-plugin-ads-control {\n display: none;\n position: absolute;\n bottom: 10px;\n right: 10px;\n}\n.artplayer-plugin-ads .artplayer-plugin-ads-control > div {\n display: flex;\n align-items: center;\n background-color: rgba(0, 0, 0, 0.5);\n border-radius: 15px;\n margin-left: 5px;\n padding: 5px 10px;\n cursor: pointer;\n}\n.artplayer-plugin-ads .artplayer-plugin-ads-control .art-icon svg {\n width: 20px;\n height: 20px;\n}\n.artplayer-plugin-ads .artplayer-plugin-ads-loading {\n display: flex;\n align-items: center;\n justify-content: center;\n position: absolute;\n left: 0;\n top: 0;\n right: 0;\n bottom: 0;\n width: 100%;\n height: 100%;\n}\n"; +function checkVersion(art) { + const { + version, + utils: { errorHandle } + } = art.constructor; + const arr = version.split(".").map(Number); + const major = arr[0]; + const minor = arr[1] / 100; + errorHandle( + major + minor >= 5, + `Artplayer.js@${version} is not compatible the artplayerPluginAds@${artplayerPluginAds.version}. Please update it to version Artplayer.js@5.x.x` + ); +} +function artplayerPluginAds(option) { + return (art) => { + checkVersion(art); + const { + template: { $player }, + icons: { volume, volumeClose, fullscreenOn, fullscreenOff, loading }, + constructor: { + validator, + utils: { query, append, setStyle } + } + } = art; + option = validator( + { + html: "", + video: "", + url: "", + playDuration: 5, + totalDuration: 10, + muted: false, + i18n: { + close: "关闭广告", + countdown: "%s秒", + detail: "查看详情", + canBeClosed: "%s秒后可关闭广告" + }, + ...option + }, + { + html: "?string", + video: "?string", + url: "?string", + playDuration: "number", + totalDuration: "number", + muted: "?boolean", + i18n: { + close: "string", + countdown: "string", + detail: "string", + canBeClosed: "string" + } + } + ); + let $ads = null; + let $timer = null; + let $close = null; + let $countdown = null; + let $control = null; + let $loading = null; + let time = 0; + let timer = null; + let isEnd = false; + let isInit = false; + let isCanClose = false; + function getI18n(val, str) { + return str.replace("%s", val); + } + function skip() { + isEnd = true; + art.play(); + if (option.video) + $ads.pause(); + setStyle(art.template.$ads, "display", "none"); + art.emit("artplayerPluginAds:skip", option); + } + function play() { + if (isEnd) + return; + timer = setTimeout(() => { + time += 1; + const playDuration = option.playDuration - time; + if (playDuration >= 1) { + $close.innerHTML = getI18n(playDuration, option.i18n.canBeClosed); + } else { + $close.innerHTML = option.i18n.close; + if (!isCanClose) { + isCanClose = true; + } + } + $countdown.innerHTML = getI18n(option.totalDuration - time, option.i18n.countdown); + if (time >= option.totalDuration) { + skip(); + } else { + play(); + } + }, 1e3); + } + function pause() { + if (isEnd) + return; + clearTimeout(timer); + } + function show() { + art.template.$ads = append($player, '
'); + $ads = append( + art.template.$ads, + option.video ? `` : `
${option.html}
` + ); + $loading = append(art.template.$ads, '
'); + append($loading, loading); + $timer = append( + art.template.$ads, + `
+
${option.playDuration <= 0 ? option.i18n.close : getI18n(option.playDuration, option.i18n.canBeClosed)}
+
${getI18n( + option.totalDuration, + option.i18n.countdown + )}
+
` + ); + $close = query(".artplayer-plugin-ads-close", $timer); + $countdown = query(".artplayer-plugin-ads-countdown", $timer); + if (option.playDuration >= option.totalDuration) { + setStyle($close, "display", "none"); + } + art.proxy($close, "click", () => { + if (isCanClose) { + skip(); + } + }); + $control = append( + art.template.$ads, + `
+
${option.i18n.detail}
+
+
+
` + ); + const $detail = query(".artplayer-plugin-ads-detail", $control); + const $muted = query(".artplayer-plugin-ads-muted", $control); + const $fullscreen = query(".artplayer-plugin-ads-fullscreen", $control); + if (option.url) { + art.proxy($detail, "click", () => { + window.open(option.url); + art.emit("artplayerPluginAds:click", option); + }); + } else { + setStyle($detail, "display", "none"); + } + if (option.video) { + const $volume = append($muted, volume); + const $volumeClose = append($muted, volumeClose); + setStyle($volumeClose, "display", "none"); + if (option.muted) { + $ads.muted = true; + setStyle($volume, "display", "none"); + setStyle($volumeClose, "display", "inline-flex"); + } + art.proxy($muted, "click", () => { + $ads.muted = !$ads.muted; + if ($ads.muted) { + setStyle($volume, "display", "none"); + setStyle($volumeClose, "display", "inline-flex"); + } else { + setStyle($volume, "display", "inline-flex"); + setStyle($volumeClose, "display", "none"); + } + }); + } else { + setStyle($muted, "display", "none"); + } + const $fullscreenOn = append($fullscreen, fullscreenOn); + const $fullscreenOff = append($fullscreen, fullscreenOff); + setStyle($fullscreenOff, "display", "none"); + art.proxy($fullscreen, "click", () => { + art.fullscreen = !art.fullscreen; + if (art.fullscreen) { + setStyle($fullscreenOn, "display", "inline-flex"); + setStyle($fullscreenOff, "display", "none"); + } else { + setStyle($fullscreenOn, "display", "none"); + setStyle($fullscreenOff, "display", "inline-flex"); + } + }); + art.proxy($ads, "click", () => { + if (option.url) + window.open(option.url); + art.emit("artplayerPluginAds:click", option); + }); + } + function init() { + if (isInit) + return; + isInit = true; + show(); + art.pause(); + if (option.video) { + art.proxy($ads, "error", skip); + art.proxy($ads, "loadedmetadata", () => { + play(); + $ads.play(); + setStyle($timer, "display", "flex"); + setStyle($control, "display", "flex"); + setStyle($loading, "display", "none"); + }); + } else { + play(); + setStyle($timer, "display", "flex"); + setStyle($control, "display", "flex"); + setStyle($loading, "display", "none"); + } + art.on("document:visibilitychange", () => { + if (document.hidden) { + pause(); + } else { + play(); + } + }); + } + art.on("ready", () => { + art.once("play", init); + art.once("video:playing", init); + }); + return { + name: "artplayerPluginAds", + skip, + pause, + play + }; + }; +} +if (typeof document !== "undefined") { + if (!document.getElementById("artplayer-plugin-ads")) { + const $style = document.createElement("style"); + $style.id = "artplayer-plugin-ads"; + $style.textContent = style; + document.head.appendChild($style); + } +} +export { + artplayerPluginAds as default +}; diff --git a/packages/artplayer-plugin-ambilight/dist/artplayer-plugin-ambilight.mjs b/packages/artplayer-plugin-ambilight/dist/artplayer-plugin-ambilight.mjs index a70e04807..19196e4c8 100644 --- a/packages/artplayer-plugin-ambilight/dist/artplayer-plugin-ambilight.mjs +++ b/packages/artplayer-plugin-ambilight/dist/artplayer-plugin-ambilight.mjs @@ -4,4 +4,101 @@ * (c) 2017-2026 Harvey Zhao * Released under the MIT License. */ -function t(t={}){return e=>{const{$video:n}=e.template,{createElement:r,addClass:o,setStyles:i}=e.constructor.utils,{blur:a="50px",opacity:l=.5,frequency:s=10,duration:c=.3}=t,u=r("div"),d=((f=u).innerHTML=Array.from({length:9}).fill("
").join(""),Array.from(f.children));var f,m,g,p;!function(t,e){o(t,"artplayer-plugin-ambilight"),e.parentNode.insertBefore(t,e),i(t,{position:"absolute",top:0,left:0,zIndex:9,inset:0,display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gridTemplateRows:"1fr 1fr 1fr"})}(u,n),m=a,g=l,p=c,d.forEach(t=>{i(t,{opacity:g,filter:`blur(${m})`,transition:`background-color ${p}s ease`})});const y=function(t,n,o){const i=r("canvas"),a=i.getContext("2d");i.width=3,i.height=3;let l=0;return function r(){const i=performance.now();if(i-l<1e3/o||!e.playing)return void(h=requestAnimationFrame(r));l=i;const s=t.videoWidth/3,c=t.videoHeight/3,u=[[0,0],[s,0],[2*s,0],[0,c],[s,c],[2*s,c],[0,2*c],[s,2*c],[2*s,2*c]].map(([e,n])=>function(e,n,r,o){a.drawImage(t,e,n,r,o,0,0,1,1);const[i,l,s]=a.getImageData(0,0,1,1).data;return`rgb(${i}, ${l}, ${s})`}(e,n,s,c));n.forEach((t,e)=>{t.style.backgroundColor=u[e]}),h=requestAnimationFrame(r)}}(n,d,s);let h=null;function v(){h||y()}function b(){h&&(cancelAnimationFrame(h),h=null)}return e.on("ready",v),e.on("destroy",b),{name:"artplayerPluginAmbilight",start:v,stop:b}}}export{t as default}; +function artplayerPluginAmbilight(option = {}) { + return (art) => { + const { $video } = art.template; + const { createElement, addClass, setStyles } = art.constructor.utils; + const { blur = "50px", opacity = 0.5, frequency = 10, duration = 0.3 } = option; + const $ambilight = createElement("div"); + const gridItems = createGridItems($ambilight); + setupAmbilight($ambilight, $video); + setupGridItems(gridItems, blur, opacity, duration); + const updateColors = createColorUpdater($video, gridItems, frequency); + let animationFrameId = null; + function start() { + if (!animationFrameId) { + updateColors(); + } + } + function stop() { + if (animationFrameId) { + cancelAnimationFrame(animationFrameId); + animationFrameId = null; + } + } + art.on("ready", start); + art.on("destroy", stop); + return { + name: "artplayerPluginAmbilight", + start, + stop + }; + function createGridItems($ambilight2) { + $ambilight2.innerHTML = Array.from({ length: 9 }).fill("
").join(""); + return Array.from($ambilight2.children); + } + function setupAmbilight($ambilight2, $video2) { + addClass($ambilight2, "artplayer-plugin-ambilight"); + $video2.parentNode.insertBefore($ambilight2, $video2); + setStyles($ambilight2, { + position: "absolute", + top: 0, + left: 0, + zIndex: 9, + inset: 0, + display: "grid", + gridTemplateColumns: "1fr 1fr 1fr", + gridTemplateRows: "1fr 1fr 1fr" + }); + } + function setupGridItems(gridItems2, blur2, opacity2, duration2) { + gridItems2.forEach(($item) => { + setStyles($item, { + opacity: opacity2, + filter: `blur(${blur2})`, + transition: `background-color ${duration2}s ease` + }); + }); + } + function createColorUpdater($video2, gridItems2, frequency2) { + const canvas = createElement("canvas"); + const ctx = canvas.getContext("2d"); + canvas.width = 3; + canvas.height = 3; + function getAverageColor(x, y, w, h) { + ctx.drawImage($video2, x, y, w, h, 0, 0, 1, 1); + const [r, g, b] = ctx.getImageData(0, 0, 1, 1).data; + return `rgb(${r}, ${g}, ${b})`; + } + let lastUpdateTime = 0; + return function updateColors2() { + const now = performance.now(); + if (now - lastUpdateTime < 1e3 / frequency2 || !art.playing) { + animationFrameId = requestAnimationFrame(updateColors2); + return; + } + lastUpdateTime = now; + const w = $video2.videoWidth / 3; + const h = $video2.videoHeight / 3; + const colors = [ + [0, 0], + [w, 0], + [2 * w, 0], + [0, h], + [w, h], + [2 * w, h], + [0, 2 * h], + [w, 2 * h], + [2 * w, 2 * h] + ].map(([x, y]) => getAverageColor(x, y, w, h)); + gridItems2.forEach(($item, index) => { + $item.style.backgroundColor = colors[index]; + }); + animationFrameId = requestAnimationFrame(updateColors2); + }; + } + }; +} +export { + artplayerPluginAmbilight as default +}; diff --git a/packages/artplayer-plugin-asr/dist/artplayer-plugin-asr.mjs b/packages/artplayer-plugin-asr/dist/artplayer-plugin-asr.mjs index d35dbe4eb..691a4e3a1 100644 --- a/packages/artplayer-plugin-asr/dist/artplayer-plugin-asr.mjs +++ b/packages/artplayer-plugin-asr/dist/artplayer-plugin-asr.mjs @@ -4,4 +4,249 @@ * (c) 2017-2026 Harvey Zhao * Released under the MIT License. */ -function t(t={}){const{length:e=3,interval:n=100,sampleRate:r=16e3,autoHideTimeout:a=1e4,onAudioChunk:o=()=>null}=t;return t=>{let i=!1,l=null,s=null,u=null,c=null,p=[],d=null,m=!1,y=null,f=null,g=null;const w=t.layers.add({name:"asr",html:""});function h(){w.style.display="none"}function v(t){var n;"string"===typeof t&&(clearTimeout(y),y=setTimeout(h,a),w.style.display="",w.innerHTML=(n=t,n.split(/(?<=[\u3001\u3002\uff01\uff1f!?.])\s*/u).map(t=>t.trim()).filter(Boolean).slice(-e)).map(t=>`
${t}
`).join(""))}async function b(){if(!s&&t.video)try{return s=l.createMediaElementSource(t.video),s}catch(e){console.warn("[artplayerPluginAsr] Direct connection failed:",e)}try{if(f||(f=await async function(t){try{return t.captureStream?t.captureStream():t.mozCaptureStream?t.mozCaptureStream():(console.warn("[artplayerPluginAsr] captureStream not supported"),null)}catch(e){return console.warn("[artplayerPluginAsr] Error capturing stream:",e),null}}(t.video)),f)return g=l.createMediaStreamSource(f),g}catch(e){console.warn("[artplayerPluginAsr] MediaStream fallback failed:",e)}return null}async function x(){i&&(i=!1,clearInterval(d),d=null,u&&(u.disconnect(),u.port.onmessage=null,u=null),c&&(c.disconnect(),c=null),p=[])}async function A(){await x(),g&&(g.disconnect(),g=null),s&&(s.disconnect(),s=null),f&&(f.getTracks().forEach(t=>t.stop()),f=null),l&&(await l.close(),l=null),m=!1}return t.on("video:volumechange",()=>{c&&(c.gain.value=t.volume)}),t.on("play",async function(){if(!i)try{await async function(){return l||(l=new(window.AudioContext||window.webkitAudioContext)({sampleRate:r}),"suspended"===l.state&&await l.resume(),l)}();const t=await b();if(!t)throw new Error("Could not establish audio source");if(!m){const t=(()=>{const t=new Blob(["\n class RecorderProcessor extends AudioWorkletProcessor {\n process(inputs) {\n const input = inputs[0];\n if (input && input[0]) {\n this.port.postMessage(input[0]);\n }\n return true;\n }\n }\n registerProcessor('recorder-processor', RecorderProcessor);\n "],{type:"application/javascript"});return URL.createObjectURL(t)})();await l.audioWorklet.addModule(t),URL.revokeObjectURL(t),m=!0}c=l.createGain(),c.gain.value=1,u=new AudioWorkletNode(l,"recorder-processor"),u.port.onmessage=t=>{p.push(new Float32Array(t.data))},t.connect(u),t.connect(c),c.connect(l.destination);const e=r*(n/1e3);d=setInterval(async()=>{if(0===p.length)return;let t=new Float32Array(0);for(;t.length{for(let n=0;n null + } = option; + return (art) => { + let started = false; + let audioCtx = null; + let sourceNode = null; + let recorderNode = null; + let gainNode = null; + let bufferChunks = []; + let timer = null; + let workletLoaded = false; + let hideTimer = null; + let mediaStream = null; + let mediaStreamSource = null; + const $asr = art.layers.add({ + name: "asr", + html: "" + }); + function splitByPunctuation(text) { + return text.split(/(?<=[、。!?!?.])\s*/u).map((s) => s.trim()).filter(Boolean).slice(-length); + } + function hide() { + $asr.style.display = "none"; + } + function append(subtitle) { + if (typeof subtitle !== "string") + return; + clearTimeout(hideTimer); + hideTimer = setTimeout(hide, autoHideTimeout); + $asr.style.display = ""; + $asr.innerHTML = splitByPunctuation(subtitle).map((line) => `
${line}
`).join(""); + } + const recorderProcessorCode = ` + class RecorderProcessor extends AudioWorkletProcessor { + process(inputs) { + const input = inputs[0]; + if (input && input[0]) { + this.port.postMessage(input[0]); + } + return true; + } + } + registerProcessor('recorder-processor', RecorderProcessor); + `; + const createWorkletBlobUrl = () => { + const blob = new Blob([recorderProcessorCode], { type: "application/javascript" }); + return URL.createObjectURL(blob); + }; + function floatTo16BitPCM(float32Array) { + const len = float32Array.length; + const buffer = new ArrayBuffer(len * 2); + const view = new DataView(buffer); + for (let i = 0; i < len; i++) { + const s = Math.max(-1, Math.min(1, float32Array[i])); + view.setInt16(i * 2, s < 0 ? s * 32768 : s * 32767, true); + } + return buffer; + } + function pcmToWav(pcmBuffer, sampleRate2) { + const pcmLength = pcmBuffer.byteLength; + const wavBuffer = new ArrayBuffer(44 + pcmLength); + const view = new DataView(wavBuffer); + const writeString = (offset, str) => { + for (let i = 0; i < str.length; i++) { + view.setUint8(offset + i, str.charCodeAt(i)); + } + }; + writeString(0, "RIFF"); + view.setUint32(4, 36 + pcmLength, true); + writeString(8, "WAVE"); + writeString(12, "fmt "); + view.setUint32(16, 16, true); + view.setUint16(20, 1, true); + view.setUint16(22, 1, true); + view.setUint32(24, sampleRate2, true); + view.setUint32(28, sampleRate2 * 2, true); + view.setUint16(32, 2, true); + view.setUint16(34, 16, true); + writeString(36, "data"); + view.setUint32(40, pcmLength, true); + new Uint8Array(wavBuffer).set(new Uint8Array(pcmBuffer), 44); + return wavBuffer; + } + async function setupAudioContext() { + if (audioCtx) + return audioCtx; + audioCtx = new (window.AudioContext || window.webkitAudioContext)({ sampleRate }); + if (audioCtx.state === "suspended") + await audioCtx.resume(); + return audioCtx; + } + async function setupAudioSource() { + if (!sourceNode && art.video) { + try { + sourceNode = audioCtx.createMediaElementSource(art.video); + return sourceNode; + } catch (err) { + console.warn("[artplayerPluginAsr] Direct connection failed:", err); + } + } + try { + if (!mediaStream) { + mediaStream = await captureAudioFromVideo(art.video); + } + if (mediaStream) { + mediaStreamSource = audioCtx.createMediaStreamSource(mediaStream); + return mediaStreamSource; + } + } catch (err) { + console.warn("[artplayerPluginAsr] MediaStream fallback failed:", err); + } + return null; + } + async function captureAudioFromVideo(videoElement) { + try { + if (videoElement.captureStream) + return videoElement.captureStream(); + if (videoElement.mozCaptureStream) + return videoElement.mozCaptureStream(); + console.warn("[artplayerPluginAsr] captureStream not supported"); + return null; + } catch (err) { + console.warn("[artplayerPluginAsr] Error capturing stream:", err); + return null; + } + } + async function startCapture() { + if (started) + return; + try { + await setupAudioContext(); + const audioSource = await setupAudioSource(); + if (!audioSource) + throw new Error("Could not establish audio source"); + if (!workletLoaded) { + const blobUrl = createWorkletBlobUrl(); + await audioCtx.audioWorklet.addModule(blobUrl); + URL.revokeObjectURL(blobUrl); + workletLoaded = true; + } + gainNode = audioCtx.createGain(); + gainNode.gain.value = 1; + recorderNode = new AudioWorkletNode(audioCtx, "recorder-processor"); + recorderNode.port.onmessage = (event) => { + bufferChunks.push(new Float32Array(event.data)); + }; + audioSource.connect(recorderNode); + audioSource.connect(gainNode); + gainNode.connect(audioCtx.destination); + const CHUNK_SAMPLES = sampleRate * (interval / 1e3); + timer = setInterval(async () => { + if (bufferChunks.length === 0) + return; + let accumulated = new Float32Array(0); + while (accumulated.length < CHUNK_SAMPLES && bufferChunks.length) { + const next = bufferChunks.shift(); + const tmp = new Float32Array(accumulated.length + next.length); + tmp.set(accumulated, 0); + tmp.set(next, accumulated.length); + accumulated = tmp; + } + if (accumulated.length < CHUNK_SAMPLES) + return; + const chunkToSend = accumulated.slice(0, CHUNK_SAMPLES); + const pcm = floatTo16BitPCM(chunkToSend); + const wav = pcmToWav(pcm, sampleRate); + const subtitle = await onAudioChunk({ pcm, wav }); + append(subtitle); + }, interval); + started = true; + } catch (err) { + console.error("[artplayerPluginAsr] Initialization failed:", err); + await stopCapture(); + } + } + async function stopCapture() { + if (!started) + return; + started = false; + clearInterval(timer); + timer = null; + if (recorderNode) { + recorderNode.disconnect(); + recorderNode.port.onmessage = null; + recorderNode = null; + } + if (gainNode) { + gainNode.disconnect(); + gainNode = null; + } + bufferChunks = []; + } + async function destroy() { + await stopCapture(); + if (mediaStreamSource) { + mediaStreamSource.disconnect(); + mediaStreamSource = null; + } + if (sourceNode) { + sourceNode.disconnect(); + sourceNode = null; + } + if (mediaStream) { + mediaStream.getTracks().forEach((track) => track.stop()); + mediaStream = null; + } + if (audioCtx) { + await audioCtx.close(); + audioCtx = null; + } + workletLoaded = false; + } + art.on("video:volumechange", () => { + if (gainNode) { + gainNode.gain.value = art.volume; + } + }); + art.on("play", startCapture); + art.on("pause", stopCapture); + art.on("destroy", destroy); + return { + name: "artplayerPluginAsr", + stop: destroy, + hide, + append + }; + }; +} +if (typeof document !== "undefined") { + if (!document.getElementById("artplayer-plugin-asr")) { + const $style = document.createElement("style"); + $style.id = "artplayer-plugin-asr"; + $style.textContent = style; + document.head.appendChild($style); + } +} +export { + artplayerPluginAsr as default +}; diff --git a/packages/artplayer-plugin-audio-track/dist/artplayer-plugin-audio-track.mjs b/packages/artplayer-plugin-audio-track/dist/artplayer-plugin-audio-track.mjs index e00c8166a..65bc77c9e 100644 --- a/packages/artplayer-plugin-audio-track/dist/artplayer-plugin-audio-track.mjs +++ b/packages/artplayer-plugin-audio-track/dist/artplayer-plugin-audio-track.mjs @@ -4,4 +4,89 @@ * (c) 2017-2026 Harvey Zhao * Released under the MIT License. */ -function e(e){return a=>{let{url:o,offset:n=0,sync:t=.3}=e;const u=new Audio;function c(){if(!a.video||!o)return;const e=a.currentTime+n;Math.abs(u.currentTime-e)>t&&(u.currentTime=e)}return u.preload="auto",o&&(u.src=o),a.on("play",()=>{o&&(c(),u.play().catch(e=>{console.warn(e)}))}),a.on("pause",()=>{u.pause()}),a.on("seek",()=>{c()}),a.on("video:timeupdate",()=>{a.playing&&c()}),a.on("video:ratechange",()=>{u.playbackRate=a.video.playbackRate}),a.on("video:volumechange",()=>{u.volume=a.volume,u.muted=a.muted}),a.on("video:waiting",()=>{u.pause()}),a.on("video:playing",()=>{o&&a.playing&&u.play().catch(e=>{console.warn(e)})}),a.on("destroy",()=>{u.pause(),u.src="",u.load()}),u.volume=a.volume,u.muted=a.muted,u.playbackRate=a.video?.playbackRate||1,{name:"artplayerPluginAudioTrack",audio:u,update:function(e){e.url&&e.url!==o&&(o=e.url,u.src=o,a.playing&&u.play().catch(e=>console.warn(e))),void 0!==e.offset&&(n=e.offset),void 0!==e.sync&&(t=e.sync)}}}}export{e as default}; +function artplayerPluginAudioTrack(option) { + return (art) => { + let { url, offset = 0, sync = 0.3 } = option; + const audio = new Audio(); + audio.preload = "auto"; + if (url) { + audio.src = url; + } + function syncAudio() { + if (!art.video || !url) + return; + const videoTime = art.currentTime; + const targetTime = videoTime + offset; + if (Math.abs(audio.currentTime - targetTime) > sync) { + audio.currentTime = targetTime; + } + } + art.on("play", () => { + if (!url) + return; + syncAudio(); + audio.play().catch((err) => { + console.warn(err); + }); + }); + art.on("pause", () => { + audio.pause(); + }); + art.on("seek", () => { + syncAudio(); + }); + art.on("video:timeupdate", () => { + if (art.playing) { + syncAudio(); + } + }); + art.on("video:ratechange", () => { + audio.playbackRate = art.video.playbackRate; + }); + art.on("video:volumechange", () => { + audio.volume = art.volume; + audio.muted = art.muted; + }); + art.on("video:waiting", () => { + audio.pause(); + }); + art.on("video:playing", () => { + if (url && art.playing) { + audio.play().catch((err) => { + console.warn(err); + }); + } + }); + art.on("destroy", () => { + audio.pause(); + audio.src = ""; + audio.load(); + }); + function update(newOption) { + if (newOption.url && newOption.url !== url) { + url = newOption.url; + audio.src = url; + if (art.playing) { + audio.play().catch((err) => console.warn(err)); + } + } + if (newOption.offset !== void 0) { + offset = newOption.offset; + } + if (newOption.sync !== void 0) { + sync = newOption.sync; + } + } + audio.volume = art.volume; + audio.muted = art.muted; + audio.playbackRate = art.video?.playbackRate || 1; + return { + name: "artplayerPluginAudioTrack", + audio, + update + }; + }; +} +export { + artplayerPluginAudioTrack as default +}; diff --git a/packages/artplayer-plugin-auto-thumbnail/dist/artplayer-plugin-auto-thumbnail.mjs b/packages/artplayer-plugin-auto-thumbnail/dist/artplayer-plugin-auto-thumbnail.mjs index 74673a601..057c7208f 100644 --- a/packages/artplayer-plugin-auto-thumbnail/dist/artplayer-plugin-auto-thumbnail.mjs +++ b/packages/artplayer-plugin-auto-thumbnail/dist/artplayer-plugin-auto-thumbnail.mjs @@ -4,4 +4,60 @@ * (c) 2017-2026 Harvey Zhao * Released under the MIT License. */ -function e(e){return async t=>(t.on("video:loadedmetadata",()=>{const n=e.url||t.option.url,o=e.width||160,a=e.number||100,r=e.scale||1;!function({url:e,width:t,number:n},o){const a=document.createElement("video");a.crossOrigin="anonymous",a.src=e,a.onloadedmetadata=()=>{const e=a.duration,r=document.createElement("canvas"),i=r.getContext("2d"),u=Math.floor(t*a.videoHeight/a.videoWidth);r.width=10*t,r.height=u*Math.ceil(n/10);let l=null;!function d(c){r.toBlob(e=>{URL.revokeObjectURL(l),l=URL.createObjectURL(e),o({url:l,height:u})},"image/jpeg"),c>=n||(a.currentTime=e*c/n,a.onseeked=()=>{i.drawImage(a,c%10*t,Math.floor(c/10)*u,t,u),d(c+1)})}(0)}}({url:n,width:o,number:a},e=>{t.thumbnails={...e,column:10,number:a,width:o,scale:r}})}),{name:"artplayerPluginAutoThumbnail"})}export{e as default}; +function create({ url, width, number }, callback) { + const video = document.createElement("video"); + video.crossOrigin = "anonymous"; + video.src = url; + video.onloadedmetadata = () => { + const duration = video.duration; + const canvas = document.createElement("canvas"); + const ctx = canvas.getContext("2d"); + const height = Math.floor(width * video.videoHeight / video.videoWidth); + canvas.width = width * 10; + canvas.height = height * Math.ceil(number / 10); + let blobUrl = null; + function seekAndDraw(index) { + canvas.toBlob((blob) => { + URL.revokeObjectURL(blobUrl); + blobUrl = URL.createObjectURL(blob); + callback({ + url: blobUrl, + height + }); + }, "image/jpeg"); + if (index >= number) + return; + video.currentTime = duration * index / number; + video.onseeked = () => { + ctx.drawImage(video, index % 10 * width, Math.floor(index / 10) * height, width, height); + seekAndDraw(index + 1); + }; + } + seekAndDraw(0); + }; +} +function artplayerPluginAutoThumbnail(option) { + return async (art) => { + art.on("video:loadedmetadata", () => { + const url = option.url || art.option.url; + const width = option.width || 160; + const number = option.number || 100; + const scale = option.scale || 1; + create({ url, width, number }, (config) => { + art.thumbnails = { + ...config, + column: 10, + number, + width, + scale + }; + }); + }); + return { + name: "artplayerPluginAutoThumbnail" + }; + }; +} +export { + artplayerPluginAutoThumbnail as default +}; diff --git a/packages/artplayer-plugin-chapter/dist/artplayer-plugin-chapter.mjs b/packages/artplayer-plugin-chapter/dist/artplayer-plugin-chapter.mjs index f8ede6d03..fff9ff1f3 100644 --- a/packages/artplayer-plugin-chapter/dist/artplayer-plugin-chapter.mjs +++ b/packages/artplayer-plugin-chapter/dist/artplayer-plugin-chapter.mjs @@ -4,4 +4,156 @@ * (c) 2017-2026 Harvey Zhao * Released under the MIT License. */ -function t(t={}){return r=>{const{$player:e}=r.template,{setStyle:a,append:n,clamp:o,query:i,addClass:p,removeClass:s}=r.constructor.utils;let d=[];const l=r.query(".art-control-progress-inner"),c=n(l,'
'),h=n(l,'
');function u({$chapter:t,width:r}){const e=t.dataset.title.trim();if(e){h.textContent=e;const t=h.clientWidth;r<=t/2?a(h,"left",0):r>l.clientWidth-t/2?a(h,"left",l.clientWidth-t+"px"):a(h,"left",r-t/2+"px")}}function g(t=[]){if(d=[],c.textContent="",s(e,"artplayer-plugin-chapter"),Array.isArray(t)&&t.length&&r.duration){t=t.sort((t,r)=>t.start-r.start);for(let e=0;er.duration||a.start>=a.end)throw new Error("Illegal chapter time point");if(n&&a.end>n.start)throw new Error("Illegal chapter time point")}t[0].start>0&&t.unshift({start:0,end:t[0].start,title:""}),t[t.length-1].end{const e=n(c,'\n
\n
\n
\n
\n
\n
\n
\n '),a=o(t.start,0,r.duration),p=o(t.end,0,r.duration),s=p-a,d=s/r.duration;return e.dataset.start=a,e.dataset.end=p,e.dataset.duration=s,e.dataset.title=t.title.trim(),e.style.width=100*d+"%",{$chapter:e,$hover:i(".art-progress-hover",e),$loaded:i(".art-progress-loaded",e),$played:i(".art-progress-played",e)}}),p(e,"artplayer-plugin-chapter"),r.emit("setBar","loaded",r.loaded||0)}}return r.on("setBar",(t,e)=>{if(d.length)for(let n=0;nf&&a(l,"width","100%"),g>=y&&g<=f){a(l,"width",100*((g-y)/m)+"%"),"hover"===t&&h>0&&u({$chapter:o,width:h})}}}),r.once("video:loadedmetadata",()=>g(t.chapters)),{name:"artplayerPluginChapter",update:({chapters:t})=>g(t)}}}if("undefined"!==typeof document){const t="artplayer-plugin-chapter";let r=document.getElementById(t);r||(r=document.createElement("style"),r.id=t,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{document.head.appendChild(r)}):(document.head||document.documentElement).appendChild(r)),r.textContent=".artplayer-plugin-chapter .art-control-progress-inner{height:100%!important;background-color:transparent!important}.artplayer-plugin-chapter .art-control-progress-inner>.art-progress-hover,.artplayer-plugin-chapter .art-control-progress-inner>.art-progress-loaded,.artplayer-plugin-chapter .art-control-progress-inner>.art-progress-played{display:none!important}.artplayer-plugin-chapter .art-control-thumbnails{bottom:calc(var(--art-bottom-gap) + 64px)!important}.artplayer-plugin-chapter .art-chapters{position:absolute;z-index:0;inset:0;display:flex;align-items:center;gap:4px;height:100%;transform:scaleY(1.25)}.artplayer-plugin-chapter .art-chapters .art-chapter{display:flex;align-items:center;height:100%}.artplayer-plugin-chapter .art-chapters .art-chapter .art-chapter-inner{position:relative;cursor:pointer;width:100%;height:50%;border-radius:10px;overflow:hidden;transition:height var(--art-transition-duration) ease;background-color:var(--art-progress-color)}.artplayer-plugin-chapter .art-chapters .art-chapter:hover .art-chapter-inner{height:100%}.artplayer-plugin-chapter .art-chapter-title{transform-origin:bottom center;transform:scale(.5);opacity:0;position:absolute;z-index:70;top:-50px;left:0;padding:3px 5px;line-height:1;font-size:14px;border-radius:var(--art-border-radius);white-space:nowrap;background-color:var(--art-tip-background);transition:transform var(--art-transition-duration) ease,opacity var(--art-transition-duration) ease}.artplayer-plugin-chapter.art-progress-hover .art-chapter-title{transform:scale(1);opacity:1}"}export{t as default}; +const style = ".artplayer-plugin-chapter .art-control-progress-inner {\n height: 100% !important;\n background-color: transparent !important;\n}\n.artplayer-plugin-chapter .art-control-progress-inner > .art-progress-hover,\n.artplayer-plugin-chapter .art-control-progress-inner > .art-progress-loaded,\n.artplayer-plugin-chapter .art-control-progress-inner > .art-progress-played {\n display: none !important;\n}\n.artplayer-plugin-chapter .art-control-thumbnails {\n bottom: calc(var(--art-bottom-gap) + 64px) !important;\n}\n.artplayer-plugin-chapter .art-chapters {\n position: absolute;\n z-index: 0;\n inset: 0;\n display: flex;\n align-items: center;\n gap: 4px;\n height: 100%;\n transform: scaleY(1.25);\n}\n.artplayer-plugin-chapter .art-chapters .art-chapter {\n display: flex;\n align-items: center;\n height: 100%;\n}\n.artplayer-plugin-chapter .art-chapters .art-chapter .art-chapter-inner {\n position: relative;\n cursor: pointer;\n width: 100%;\n height: 50%;\n border-radius: 10px;\n overflow: hidden;\n transition: height var(--art-transition-duration) ease;\n background-color: var(--art-progress-color);\n}\n.artplayer-plugin-chapter .art-chapters .art-chapter:hover .art-chapter-inner {\n height: 100%;\n}\n.artplayer-plugin-chapter .art-chapter-title {\n transform-origin: bottom center;\n transform: scale(0.5);\n opacity: 0;\n position: absolute;\n z-index: 70;\n top: -50px;\n left: 0;\n padding: 3px 5px;\n line-height: 1;\n font-size: 14px;\n border-radius: var(--art-border-radius);\n white-space: nowrap;\n background-color: var(--art-tip-background);\n transition: transform var(--art-transition-duration) ease, opacity var(--art-transition-duration) ease;\n}\n.artplayer-plugin-chapter.art-progress-hover .art-chapter-title {\n transform: scale(1);\n opacity: 1;\n}\n"; +function artplayerPluginChapter(option = {}) { + return (art) => { + const { $player } = art.template; + const { setStyle, append, clamp, query, addClass, removeClass } = art.constructor.utils; + const html = ` +
+
+
+
+
+
+
+ `; + let $chapters = []; + const $inner = art.query(".art-control-progress-inner"); + const $control = append($inner, '
'); + const $title = append($inner, '
'); + function showTitle({ $chapter, width }) { + const title = $chapter.dataset.title.trim(); + if (title) { + $title.textContent = title; + const titleWidth = $title.clientWidth; + if (width <= titleWidth / 2) { + setStyle($title, "left", 0); + } else if (width > $inner.clientWidth - titleWidth / 2) { + setStyle($title, "left", `${$inner.clientWidth - titleWidth}px`); + } else { + setStyle($title, "left", `${width - titleWidth / 2}px`); + } + } + } + function update(chapters = []) { + $chapters = []; + $control.textContent = ""; + removeClass($player, "artplayer-plugin-chapter"); + if (!Array.isArray(chapters)) + return; + if (!chapters.length) + return; + if (!art.duration) + return; + chapters = chapters.sort((a, b) => a.start - b.start); + for (let i = 0; i < chapters.length; i++) { + const chapter = chapters[i]; + const nextChapter = chapters[i + 1]; + if (chapter.end === Infinity) { + chapter.end = art.duration; + } + if (typeof chapter.start !== "number" || typeof chapter.end !== "number" || typeof chapter.title !== "string") { + throw new TypeError("Illegal chapter data type"); + } + if (chapter.start < 0 || chapter.end > art.duration || chapter.start >= chapter.end) { + throw new Error("Illegal chapter time point"); + } + if (nextChapter && chapter.end > nextChapter.start) { + throw new Error("Illegal chapter time point"); + } + } + if (chapters[0].start > 0) { + chapters.unshift({ start: 0, end: chapters[0].start, title: "" }); + } + if (chapters[chapters.length - 1].end < art.duration) { + chapters.push({ start: chapters[chapters.length - 1].end, end: art.duration, title: "" }); + } + for (let i = 0; i < chapters.length - 1; i++) { + if (chapters[i].end !== chapters[i + 1].start) { + chapters.splice(i + 1, 0, { + start: chapters[i].end, + end: chapters[i + 1].start, + title: "" + }); + } + } + $chapters = chapters.map((chapter) => { + const $chapter = append($control, html); + const start = clamp(chapter.start, 0, art.duration); + const end = clamp(chapter.end, 0, art.duration); + const duration = end - start; + const percentage = duration / art.duration; + $chapter.dataset.start = start; + $chapter.dataset.end = end; + $chapter.dataset.duration = duration; + $chapter.dataset.title = chapter.title.trim(); + $chapter.style.width = `${percentage * 100}%`; + return { + $chapter, + $hover: query(".art-progress-hover", $chapter), + $loaded: query(".art-progress-loaded", $chapter), + $played: query(".art-progress-played", $chapter) + }; + }); + addClass($player, "artplayer-plugin-chapter"); + art.emit("setBar", "loaded", art.loaded || 0); + } + art.on("setBar", (type, percentage) => { + if (!$chapters.length) + return; + for (let i = 0; i < $chapters.length; i++) { + const { $chapter, $loaded, $played, $hover } = $chapters[i]; + const $target = { + hover: $hover, + loaded: $loaded, + played: $played + }[type]; + if (!$target) + return; + const width = $control.clientWidth * percentage; + const currentTime = art.duration * percentage; + const duration = Number.parseFloat($chapter.dataset.duration); + const start = Number.parseFloat($chapter.dataset.start); + const end = Number.parseFloat($chapter.dataset.end); + if (currentTime < start) { + setStyle($target, "width", 0); + } + if (currentTime > end) { + setStyle($target, "width", "100%"); + } + if (currentTime >= start && currentTime <= end) { + const percentage2 = (currentTime - start) / duration; + setStyle($target, "width", `${percentage2 * 100}%`); + if (type === "hover" && width > 0) { + showTitle({ $chapter, width }); + } + } + } + }); + art.once("video:loadedmetadata", () => update(option.chapters)); + return { + name: "artplayerPluginChapter", + update: ({ chapters }) => update(chapters) + }; + }; +} +if (typeof document !== "undefined") { + const id = "artplayer-plugin-chapter"; + let $style = document.getElementById(id); + if (!$style) { + $style = document.createElement("style"); + $style.id = id; + if (document.readyState === "loading") { + document.addEventListener("DOMContentLoaded", () => { + document.head.appendChild($style); + }); + } else { + (document.head || document.documentElement).appendChild($style); + } + } + $style.textContent = style; +} +export { + artplayerPluginChapter as default +}; diff --git a/packages/artplayer-plugin-chromecast/dist/artplayer-plugin-chromecast.mjs b/packages/artplayer-plugin-chromecast/dist/artplayer-plugin-chromecast.mjs index 9b4175ab0..1a828128a 100644 --- a/packages/artplayer-plugin-chromecast/dist/artplayer-plugin-chromecast.mjs +++ b/packages/artplayer-plugin-chromecast/dist/artplayer-plugin-chromecast.mjs @@ -4,4 +4,173 @@ * (c) 2017-2026 Harvey Zhao * Released under the MIT License. */ -function e(e){let t=!1,o=null,a=null;const n=e=>{const t=document.querySelector(".art-icon-cast");if(t)switch(e){case"connected":t.style.color="red";break;case"connecting":case"disconnecting":t.style.color="orange";break;default:t.style.color="white"}},c=()=>new Promise((c,s)=>{var i;window.__onGCastApiAvailable=i=>{if(i){const s=window.cast.framework.CastContext.getInstance();s.setOptions({receiverApplicationId:window.chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,autoJoinPolicy:window.chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}),s.addEventListener(window.cast.framework.CastContextEventType.SESSION_STATE_CHANGED,t=>{const c=window.cast.framework.SessionState;switch(a=t.sessionState,o=t.session,t.sessionState){case c.NO_SESSION:e.onStateChange?.("disconnected"),n("disconnected");break;case c.SESSION_STARTING:e.onStateChange?.("connecting"),n("connecting");break;case c.SESSION_STARTED:e.onStateChange?.("connected"),n("connected");break;case c.SESSION_ENDING:e.onStateChange?.("disconnecting"),n("disconnecting");break;case c.SESSION_RESUMED:e.onStateChange?.("connected"),n("connected")}}),s.addEventListener(window.cast.framework.CastContextEventType.CAST_STATE_CHANGED,t=>{const o=window.cast.framework.CastState;switch(t.castState){case o.NO_DEVICES_AVAILABLE:e.onCastAvailable?.(!1);break;case o.NOT_CONNECTED:case o.CONNECTING:case o.CONNECTED:e.onCastAvailable?.(!0)}}),t=!0,c()}else s(new Error("Cast API is not available"))},window.chrome&&window.chrome.cast||(i=e.sdk||"https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1",new Promise((e,t)=>{const o=document.createElement("script");o.src=i,o.onload=e,o.onerror=t,document.body.appendChild(o)})).catch(s)}),s=(t,o)=>{const a=e.url||t.option.url,n=new window.chrome.cast.media.MediaInfo(a,e.mimeType||function(e){return{mp4:"video/mp4",webm:"video/webm",ogg:"video/ogg",ogv:"video/ogg",mp3:"audio/mp3",wav:"audio/wav",flv:"video/x-flv",mov:"video/quicktime",avi:"video/x-msvideo",wmv:"video/x-ms-wmv",mpd:"application/dash+xml",m3u8:"application/x-mpegURL"}[e.split("?")[0].split("#")[0].split(".").pop().toLowerCase()]||"application/octet-stream"}(a)),c=new window.chrome.cast.media.LoadRequest(n);o.loadMedia(c).then(()=>{t.notice.show="Casting started",e.onCastStart?.()}).catch(o=>{throw t.notice.show="Error casting media",e.onError?.(o),o})};return async n=>(n.controls.add({name:"chromecast",position:"right",tooltip:"Chromecast",html:`${e.icon||''}`,click:async()=>{if(!t)try{await c()}catch(i){throw n.notice.show="Failed to initialize Cast API",e.onError?.(i),i}const a=window.cast.framework.CastContext.getInstance();if(o)s(n,o);else try{const e=await a.requestSession();s(n,e)}catch(i){throw n.notice.show="Error connecting to cast session",e.onError?.(i),i}}}),{name:"artplayerPluginChromecast",getCastState:()=>a,isCasting:()=>null!==o})}export{e as default}; +function loadScript(src) { + return new Promise((resolve, reject) => { + const script = document.createElement("script"); + script.src = src; + script.onload = resolve; + script.onerror = reject; + document.body.appendChild(script); + }); +} +function getMimeType(url) { + const extension = url.split("?")[0].split("#")[0].split(".").pop().toLowerCase(); + const mimeTypes = { + mp4: "video/mp4", + webm: "video/webm", + ogg: "video/ogg", + ogv: "video/ogg", + mp3: "audio/mp3", + wav: "audio/wav", + flv: "video/x-flv", + mov: "video/quicktime", + avi: "video/x-msvideo", + wmv: "video/x-ms-wmv", + mpd: "application/dash+xml", + m3u8: "application/x-mpegURL" + }; + return mimeTypes[extension] || "application/octet-stream"; +} +function artplayerPluginChromecast(option) { + const DEFAULT_ICON = ``; + const DEFAULT_SDK = "https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1"; + let isCastInitialized = false; + let castSession = null; + let castState = null; + const updateCastButton = (state) => { + const button = document.querySelector(".art-icon-cast"); + if (button) { + switch (state) { + case "connected": + button.style.color = "red"; + break; + case "connecting": + case "disconnecting": + button.style.color = "orange"; + break; + case "disconnected": + default: + button.style.color = "white"; + break; + } + } + }; + const initializeCastApi = () => { + return new Promise((resolve, reject) => { + window.__onGCastApiAvailable = (isAvailable) => { + if (isAvailable) { + const context = window.cast.framework.CastContext.getInstance(); + context.setOptions({ + receiverApplicationId: window.chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID, + autoJoinPolicy: window.chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED + }); + context.addEventListener( + window.cast.framework.CastContextEventType.SESSION_STATE_CHANGED, + (event) => { + const SessionState = window.cast.framework.SessionState; + castState = event.sessionState; + castSession = event.session; + switch (event.sessionState) { + case SessionState.NO_SESSION: + option.onStateChange?.("disconnected"); + updateCastButton("disconnected"); + break; + case SessionState.SESSION_STARTING: + option.onStateChange?.("connecting"); + updateCastButton("connecting"); + break; + case SessionState.SESSION_STARTED: + option.onStateChange?.("connected"); + updateCastButton("connected"); + break; + case SessionState.SESSION_ENDING: + option.onStateChange?.("disconnecting"); + updateCastButton("disconnecting"); + break; + case SessionState.SESSION_RESUMED: + option.onStateChange?.("connected"); + updateCastButton("connected"); + break; + } + } + ); + context.addEventListener(window.cast.framework.CastContextEventType.CAST_STATE_CHANGED, (event) => { + const CastState = window.cast.framework.CastState; + switch (event.castState) { + case CastState.NO_DEVICES_AVAILABLE: + option.onCastAvailable?.(false); + break; + case CastState.NOT_CONNECTED: + option.onCastAvailable?.(true); + break; + case CastState.CONNECTING: + case CastState.CONNECTED: + option.onCastAvailable?.(true); + break; + } + }); + isCastInitialized = true; + resolve(); + } else { + reject(new Error("Cast API is not available")); + } + }; + if (!window.chrome || !window.chrome.cast) { + loadScript(option.sdk || DEFAULT_SDK).catch(reject); + } + }); + }; + const castVideo = (art, session) => { + const url = option.url || art.option.url; + const mediaInfo = new window.chrome.cast.media.MediaInfo(url, option.mimeType || getMimeType(url)); + const request = new window.chrome.cast.media.LoadRequest(mediaInfo); + session.loadMedia(request).then(() => { + art.notice.show = "Casting started"; + option.onCastStart?.(); + }).catch((error) => { + art.notice.show = "Error casting media"; + option.onError?.(error); + throw error; + }); + }; + return async (art) => { + art.controls.add({ + name: "chromecast", + position: "right", + tooltip: "Chromecast", + html: `${option.icon || DEFAULT_ICON}`, + click: async () => { + if (!isCastInitialized) { + try { + await initializeCastApi(); + } catch (error) { + art.notice.show = "Failed to initialize Cast API"; + option.onError?.(error); + throw error; + } + } + const context = window.cast.framework.CastContext.getInstance(); + if (castSession) { + castVideo(art, castSession); + } else { + try { + const session = await context.requestSession(); + castVideo(art, session); + } catch (error) { + art.notice.show = "Error connecting to cast session"; + option.onError?.(error); + throw error; + } + } + } + }); + return { + name: "artplayerPluginChromecast", + getCastState: () => castState, + isCasting: () => castSession !== null + }; + }; +} +export { + artplayerPluginChromecast as default +}; diff --git a/packages/artplayer-plugin-danmuku-mask/dist/artplayer-plugin-danmuku-mask.mjs b/packages/artplayer-plugin-danmuku-mask/dist/artplayer-plugin-danmuku-mask.mjs index 8c45bdc9e..5b74e387a 100644 --- a/packages/artplayer-plugin-danmuku-mask/dist/artplayer-plugin-danmuku-mask.mjs +++ b/packages/artplayer-plugin-danmuku-mask/dist/artplayer-plugin-danmuku-mask.mjs @@ -4,4 +4,49172 @@ * (c) 2017-2026 Harvey Zhao * Released under the MIT License. */ -function e(e,t){for(var n=0;nr[t]})}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}class t{constructor(e,t){this.backend=e,this.dataMover=t,this.data=/* @__PURE__ */new WeakMap,this.dataIdsCount=0}get(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)}set(e,t){this.dataIdsCount++,this.data.set(e,t)}has(e){return this.data.has(e)}delete(e){return this.dataIdsCount--,this.data.delete(e)}numDataIds(){return this.dataIdsCount}}class n{refCount(e){return r("refCount")}incRef(e){return r("incRef")}timerAvailable(){return!0}time(e){return r("time")}read(e){return r("read")}readSync(e){return r("readSync")}readToGPU(e,t){return r("readToGPU")}numDataIds(){return r("numDataIds")}disposeData(e,t){return r("disposeData")}write(e,t,n){return r("write")}move(e,t,n,a,s){return r("move")}createTensorFromGPUData(e,t,n){return r("createTensorFromGPUData")}memory(){return r("memory")}floatPrecision(){return r("floatPrecision")}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}dispose(){return r("dispose")}}function r(e){throw new Error(`'${e}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}function a(e,t,n){return Math.max(e,Math.min(t,n))}function s(e){return e%2===0?e:e+1}function o(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function i(e,t){if(!e)throw new Error("string"===typeof t?t:t())}function u(e,t,n=""){i(d(e,t),()=>n+` Shapes ${e} and ${t} must match`)}function l(e){i(null!=e,()=>"The input to the tensor constructor must be a non-null value.")}function c(e){if(0===e.length)return 1;let t=e[0];for(let n=1;n0,n,r){return new Promise((a,s)=>{let o=0;const i=()=>{if(e())return void a();o++;const u=t(o);null!=n&&o>=n?s():null!=r?r(i,u):setTimeout(i,u)};i()})}function g(e,t){let n=1,r=-1;for(let s=0;s=0)n*=e[s];else if(-1===e[s]){if(-1!==r)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${r} and dim ${s}`);r=s}else if(e[s]<0)throw Error(`Shapes can not be < 0. Found ${e[s]} at dim ${s}`);if(-1===r){if(t>0&&t!==n)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(0===n)throw Error(`Cannot infer the missing size in [${e}] when there are 0 elements`);if(t%n!==0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${n}`);const a=e.slice();return a[r]=t/n,a}function y(e,t){const n=t.length;return i((e=null==e?t.map((e,t)=>t):[].concat(e)).every(e=>e>=-n&&e`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`),i(e.every(e=>p(e)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(e=>e<0?n+e:e)}function b(e,t){const n=[],r=[],a=null!=t&&Array.isArray(t)&&0===t.length,s=null==t||a?null:y(t,e).sort();let o=0;for(let i=0;ii)&&1===e[i]&&(n.push(e[i]),r.push(i)),s[o]<=i&&o++}1!==e[i]&&(n.push(e[i]),r.push(i))}return{newShape:n,keptDims:r}}function x(e,t){return v(e,t)}function v(e,t){let n=null;if(null==e||"float32"===e)n=new Float32Array(t);else if("int32"===e)n=new Int32Array(t);else if("bool"===e)n=new Uint8Array(t);else{if("string"!==e)throw new Error(`Unknown data type ${e}`);n=new Array(t)}return n}function w(e,t){return"complex64"!==t&&(("float32"!==t||"complex64"===e)&&(("int32"!==t||"float32"===e||"complex64"===e)&&("bool"!==t||"bool"!==e)))}function k(e){if("float32"===e||"int32"===e)return 4;if("complex64"===e)return 8;if("bool"===e)return 1;throw new Error(`Unknown dtype ${e}`)}function I(e){return"string"===typeof e||e instanceof String}function N(e){return Array.isArray(e)?N(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":"number"===typeof e?"float32":I(e)?"string":function(e){return"boolean"===typeof e}(e)?"bool":"float32"}function S(e){return!!(e&&e.constructor&&e.call&&e.apply)}function T(e,t){for(let n=t;n=0;--r)n[r]=n[r+1]*e[r+1];return n}function $(e,t,n,r=!1){const a=new Array;if(1===t.length){const s=t[0]*(r?2:1);for(let t=0;te*t)*(r?2:1);for(let t=0;te*t)*(n?2:1);if(0===r)return[];if(r!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${n?" for a complex tensor":""}.`);return $(0,e,t,n)}function R(e,t){const n=_(e,t);for(let r=0;re*t,1);if(null==t||"float32"===t)return E(e,new Float32Array(n));if("int32"===t)return E(e,new Int32Array(n));if("bool"===t)return E(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function O(e){e.forEach(t=>{i(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function F(e,t,n){if(0===t)return 0;if(1===t)return e[0];let r=e[e.length-1];for(let a=0;a{const[t,n]=e.split(":");this.urlFlags[t]=function(e,t){const n=t.toLowerCase();return"true"===n||"false"===n?"true"===n:""+ +n===n?+n:t}(0,n)})}}}function B(e){const t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(e,...n)=>(function(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}(t,n[0],n[1]),n.join("="))),t}function V(){return z}let W,z=null;function U(){if(null==W){let e;if("undefined"!==typeof window)e=window;else if("undefined"!==typeof global)e=global;else if("undefined"!==typeof process)e=process;else{if("undefined"===typeof self)throw new Error("Could not find a global object");e=self}W=e}return W}function G(e,t){const n=function(){const e=U();return null==e._tfGlobals&&(e._tfGlobals=/* @__PURE__ */new Map),e._tfGlobals}();if(n.has(e))return n.get(e);{const r=t();return n.set(e,r),n.get(e)}}const H="Abs",j="Acos",q="Acosh",K="Add",X="AddN",Y="All",Q="Any",Z="ArgMax",J="ArgMin",ee="Asin",te="Asinh",ne="Atan",re="Atanh",ae="Atan2",se="AvgPool",oe="AvgPoolGrad",ie="AvgPool3D",ue="AvgPool3DGrad",le="BatchMatMul",ce="BatchToSpaceND",de="Bincount",pe="BitwiseAnd",he="BroadcastArgs",fe="Cast",me="Ceil",ge="ClipByValue",ye="Complex",be="ComplexAbs",xe="Concat",ve="Conv2D",we="Conv2DBackpropFilter",ke="Conv2DBackpropInput",Ie="Conv3D",Ne="Conv3DBackpropFilterV2",Se="Conv3DBackpropInputV2",Te="Cos",Ce="Cosh",$e="Cumprod",Ee="Cumsum",Re="CropAndResize",_e="DenseBincount",Ae="DepthToSpace",Oe="DepthwiseConv2dNative",Fe="DepthwiseConv2dNativeBackpropFilter",De="DepthwiseConv2dNativeBackpropInput",Me="Diag",Pe="Dilation2D",Le="Dilation2DBackpropInput",Be="Dilation2DBackpropFilter",Ve="Draw",We="RealDiv",ze="Einsum",Ue="Elu",Ge="EluGrad",He="Erf",je="Equal",qe="Exp",Ke="ExpandDims",Xe="Expm1",Ye="FFT",Qe="Fill",Ze="FlipLeftRight",Je="Floor",et="FloorDiv",tt="FusedBatchNorm",nt="GatherV2",rt="GatherNd",at="Greater",st="GreaterEqual",ot="Identity",it="IFFT",ut="Imag",lt="IsFinite",ct="IsInf",dt="IsNan",pt="LeakyRelu",ht="Less",ft="LessEqual",mt="LinSpace",gt="Log",yt="Log1p",bt="LogicalAnd",xt="LogicalNot",vt="LogicalOr",wt="LRN",kt="LRNGrad",It="Max",Nt="Maximum",St="MaxPool",Tt="MaxPoolGrad",Ct="MaxPool3D",$t="MaxPool3DGrad",Et="MaxPoolWithArgmax",Rt="Mean",_t="Min",At="Minimum",Ot="MirrorPad",Ft="Mod",Dt="Multinomial",Mt="Multiply",Pt="Neg",Lt="NotEqual",Bt="NonMaxSuppressionV3",Vt="NonMaxSuppressionV4",Wt="NonMaxSuppressionV5",zt="OnesLike",Ut="OneHot",Gt="Pack",Ht="PadV2",jt="Pow",qt="Prelu",Kt="Prod",Xt="RaggedGather",Yt="RaggedRange",Qt="RaggedTensorToTensor",Zt="Range",Jt="Real",en="Reciprocal",tn="Relu",nn="Reshape",rn="ResizeNearestNeighbor",an="ResizeNearestNeighborGrad",sn="ResizeBilinear",on="ResizeBilinearGrad",un="Relu6",ln="Reverse",cn="Round",dn="Rsqrt",pn="ScatterNd",hn="TensorScatterUpdate",fn="SearchSorted",mn="Select",gn="Selu",yn="Slice",bn="Sin",xn="Sinh",vn="Sign",wn="Sigmoid",kn="Softplus",In="Sqrt",Nn="Sum",Sn="SpaceToBatchND",Tn="SplitV",Cn="Softmax",$n="SparseFillEmptyRows",En="SparseReshape",Rn="SparseSegmentMean",_n="SparseSegmentSum",An="SparseToDense",On="SquaredDifference",Fn="Square",Dn="StaticRegexReplace",Mn="StridedSlice",Pn="StringNGrams",Ln="StringSplit",Bn="StringToHashBucketFast",Vn="Sub",Wn="Tan",zn="Tanh",Un="Tile",Gn="TopK",Hn="Transform",jn="Transpose",qn="Unique",Kn="Unpack",Xn="UnsortedSegmentSum",Yn="ZerosLike",Qn="Step",Zn="FromPixels",Jn="RotateWithOffset",er="_FusedMatMul",tr="FusedConv2D",nr="FusedDepthwiseConv2D";function rr(...e){V().getBool("IS_TEST")||V().getBool("PROD")||console.warn(...e)}const ar=G("kernelRegistry",()=>/* @__PURE__ */new Map),sr=G("gradRegistry",()=>/* @__PURE__ */new Map);function or(e,t){const n=cr(e,t);return ar.get(n)}function ir(e){return sr.get(e)}function ur(e){const t=ar.entries(),n=[];for(;;){const{done:r,value:a}=t.next();if(r)break;const[s,o]=a,[i]=s.split("_");i===e&&n.push(o)}return n}function lr(e){const{kernelName:t,backendName:n}=e,r=cr(t,n);ar.has(r)&&rr(`The kernel '${t}' for backend '${n}' is already registered`),ar.set(r,e)}function cr(e,t){return`${t}_${e}`}function dr(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray}var pr,hr,fr="undefined"!==typeof globalThis?globalThis:"undefined"!==typeof window?window:"undefined"!==typeof global?global:"undefined"!==typeof self?self:{};function mr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function gr(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if("function"==typeof t){var n=function e(){var n=!1;try{n=this instanceof e}catch{}return n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,r.get?r:{enumerable:!0,get:function(){return e[t]}})}),n}var yr=function(){if(hr)return pr;hr=1,pr=t;var e=null;try{e=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(N){}function t(e,t,n){this.low=0|e,this.high=0|t,this.unsigned=!!n}function n(e){return!0===(e&&e.__isLong__)}t.prototype.__isLong__,Object.defineProperty(t.prototype,"__isLong__",{value:!0}),t.isLong=n;var r={},a={};function s(e,t){var n,s,o;return t?(o=0<=(e>>>=0)&&e<256)&&(s=a[e])?s:(n=i(e,(0|e)<0?-1:0,!0),o&&(a[e]=n),n):(o=-128<=(e|=0)&&e<128)&&(s=r[e])?s:(n=i(e,e<0?-1:0,!1),o&&(r[e]=n),n)}function o(e,t){if(isNaN(e))return t?g:m;if(t){if(e<0)return g;if(e>=p)return w}else{if(e<=-h)return k;if(e+1>=h)return v}return e<0?o(-e,t).neg():i(e%d|0,e/d|0,t)}function i(e,n,r){return new t(e,n,r)}t.fromInt=s,t.fromNumber=o,t.fromBits=i;var u=Math.pow;function l(e,t,n){if(0===e.length)throw Error("empty string");if("NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return m;if("number"===typeof t?(n=t,t=!1):t=!!t,(n=n||10)<2||360)throw Error("interior hyphen");if(0===r)return l(e.substring(1),t,n).neg();for(var a=o(u(n,8)),s=m,i=0;i>>0:this.low},I.toNumber=function(){return this.unsigned?(this.high>>>0)*d+(this.low>>>0):this.high*d+(this.low>>>0)},I.toString=function(e){if((e=e||10)<2||36>>0).toString(e);if((s=l).isZero())return c+i;for(;c.length<6;)c="0"+c;i=""+c+i}},I.getHighBits=function(){return this.high},I.getHighBitsUnsigned=function(){return this.high>>>0},I.getLowBits=function(){return this.low},I.getLowBitsUnsigned=function(){return this.low>>>0},I.getNumBitsAbs=function(){if(this.isNegative())return this.eq(k)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&0==(e&1<=0},I.isOdd=function(){return 1===(1&this.low)},I.isEven=function(){return 0===(1&this.low)},I.equals=function(e){return n(e)||(e=c(e)),(this.unsigned===e.unsigned||this.high>>>31!==1||e.high>>>31!==1)&&(this.high===e.high&&this.low===e.low)},I.eq=I.equals,I.notEquals=function(e){return!this.eq(e)},I.neq=I.notEquals,I.ne=I.notEquals,I.lessThan=function(e){return this.comp(e)<0},I.lt=I.lessThan,I.lessThanOrEqual=function(e){return this.comp(e)<=0},I.lte=I.lessThanOrEqual,I.le=I.lessThanOrEqual,I.greaterThan=function(e){return this.comp(e)>0},I.gt=I.greaterThan,I.greaterThanOrEqual=function(e){return this.comp(e)>=0},I.gte=I.greaterThanOrEqual,I.ge=I.greaterThanOrEqual,I.compare=function(e){if(n(e)||(e=c(e)),this.eq(e))return 0;var t=this.isNegative(),r=e.isNegative();return t&&!r?-1:!t&&r?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},I.comp=I.compare,I.negate=function(){return!this.unsigned&&this.eq(k)?k:this.not().add(y)},I.neg=I.negate,I.add=function(e){n(e)||(e=c(e));var t=this.high>>>16,r=65535&this.high,a=this.low>>>16,s=65535&this.low,o=e.high>>>16,u=65535&e.high,l=e.low>>>16,d=0,p=0,h=0,f=0;return h+=(f+=s+(65535&e.low))>>>16,p+=(h+=a+l)>>>16,d+=(p+=r+u)>>>16,d+=t+o,i((h&=65535)<<16|(f&=65535),(d&=65535)<<16|(p&=65535),this.unsigned)},I.subtract=function(e){return n(e)||(e=c(e)),this.add(e.neg())},I.sub=I.subtract,I.multiply=function(t){if(this.isZero())return m;if(n(t)||(t=c(t)),e)return i(e.mul(this.low,this.high,t.low,t.high),e.get_high(),this.unsigned);if(t.isZero())return m;if(this.eq(k))return t.isOdd()?k:m;if(t.eq(k))return this.isOdd()?k:m;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(f)&&t.lt(f))return o(this.toNumber()*t.toNumber(),this.unsigned);var r=this.high>>>16,a=65535&this.high,s=this.low>>>16,u=65535&this.low,l=t.high>>>16,d=65535&t.high,p=t.low>>>16,h=65535&t.low,g=0,y=0,b=0,x=0;return b+=(x+=u*h)>>>16,y+=(b+=s*h)>>>16,b&=65535,y+=(b+=u*p)>>>16,g+=(y+=a*h)>>>16,y&=65535,g+=(y+=s*p)>>>16,y&=65535,g+=(y+=u*d)>>>16,g+=r*h+a*p+s*d+u*l,i((b&=65535)<<16|(x&=65535),(g&=65535)<<16|(y&=65535),this.unsigned)},I.mul=I.multiply,I.divide=function(t){if(n(t)||(t=c(t)),t.isZero())throw Error("division by zero");var r,a,s;if(e)return this.unsigned||-2147483648!==this.high||-1!==t.low||-1!==t.high?i((this.unsigned?e.div_u:e.div_s)(this.low,this.high,t.low,t.high),e.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?g:m;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return g;if(t.gt(this.shru(1)))return b;s=g}else{if(this.eq(k))return t.eq(y)||t.eq(x)?k:t.eq(k)?y:(r=this.shr(1).div(t).shl(1)).eq(m)?t.isNegative()?y:x:(a=this.sub(t.mul(r)),s=r.add(a.div(t)));if(t.eq(k))return this.unsigned?g:m;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();s=m}for(a=this;a.gte(t);){r=Math.max(1,Math.floor(a.toNumber()/t.toNumber()));for(var l=Math.ceil(Math.log(r)/Math.LN2),d=l<=48?1:u(2,l-48),p=o(r),h=p.mul(t);h.isNegative()||h.gt(a);)h=(p=o(r-=d,this.unsigned)).mul(t);p.isZero()&&(p=y),s=s.add(p),a=a.sub(h)}return s},I.div=I.divide,I.modulo=function(t){return n(t)||(t=c(t)),e?i((this.unsigned?e.rem_u:e.rem_s)(this.low,this.high,t.low,t.high),e.get_high(),this.unsigned):this.sub(this.div(t).mul(t))},I.mod=I.modulo,I.rem=I.modulo,I.not=function(){return i(~this.low,~this.high,this.unsigned)},I.and=function(e){return n(e)||(e=c(e)),i(this.low&e.low,this.high&e.high,this.unsigned)},I.or=function(e){return n(e)||(e=c(e)),i(this.low|e.low,this.high|e.high,this.unsigned)},I.xor=function(e){return n(e)||(e=c(e)),i(this.low^e.low,this.high^e.high,this.unsigned)},I.shiftLeft=function(e){return n(e)&&(e=e.toInt()),0===(e&=63)?this:e<32?i(this.low<>>32-e,this.unsigned):i(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):i(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},I.shr=I.shiftRight,I.shiftRightUnsigned=function(e){if(n(e)&&(e=e.toInt()),0===(e&=63))return this;var t=this.high;return e<32?i(this.low>>>e|t<<32-e,t>>>e,this.unsigned):i(32===e?t:t>>>e-32,0,this.unsigned)},I.shru=I.shiftRightUnsigned,I.shr_u=I.shiftRightUnsigned,I.toSigned=function(){return this.unsigned?i(this.low,this.high,!1):this},I.toUnsigned=function(){return this.unsigned?this:i(this.low,this.high,!0)},I.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},I.toBytesLE=function(){var e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]},I.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]},t.fromBytes=function(e,n,r){return r?t.fromBytesLE(e,n):t.fromBytesBE(e,n)},t.fromBytesLE=function(e,n){return new t(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,n)},t.fromBytesBE=function(e,n){return new t(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],n)},pr}();const br=/* @__PURE__ */mr(yr),xr=br||/* @__PURE__ */e({__proto__:null,default:br},[yr]);function vr(e){return xr.fromString(e,!0,16)}const wr=vr("c3a5c85c97cb3127"),kr=vr("b492b66fbe98f273"),Ir=vr("9ae16a3b2f90404f");function Nr(e){return e.xor(e.shru(47))}function Sr(e,t,n){const r=e.slice(t,t+n);return xr.fromBytes(Array.from(r),!0,!0)}function Tr(e,t){return Sr(e,t,8)}function Cr(e,t){return Sr(e,t,4)}function $r(e,t){return 0===t?e:e.shru(t).or(e.shl(64-t))}function Er(e,t,n=vr("9ddfea08eb382d69")){let r=e.xor(t).mul(n);r=r.xor(r.shru(47));let a=t.xor(r).mul(n);return a=a.xor(a.shru(47)),a=a.mul(n),a}function Rr(e,t,n,r){return function(e,t,n,r,a,s){a=a.add(e),s=$r(s.add(a).add(r),21);const o=a;return a=(a=a.add(t)).add(n),s=s.add($r(a,44)),[a.add(r),s.add(o)]}(Tr(e,t),Tr(e,t+8),Tr(e,t+16),Tr(e,t+24),n,r)}function _r(e,t=e.length){const n=xr.fromNumber(81,!0);if(t<=32)return t<=16?function(e,t=e.length){if(t>=8){const n=Ir.add(2*t),r=Tr(e,0).add(Ir),a=Tr(e,t-8);return Er($r(a,37).mul(n).add(r),$r(r,25).add(a).mul(n),n)}if(t>=4){const n=Ir.add(2*t);return Er(Cr(e,0).shl(3).add(t),Cr(e,t-4),n)}if(t>0){const n=e[0]+(e[t>>1]<<8),r=t+(e[t-1]<<2);return Nr(Ir.mul(n).xor(wr.mul(r))).mul(Ir)}return Ir}(e,t):function(e,t=e.length){const n=Ir.add(2*t),r=Tr(e,0).mul(kr),a=Tr(e,8),s=Tr(e,t-8).mul(n),o=Tr(e,t-16).mul(Ir);return Er($r(r.add(a),43).add($r(s,30)).add(o),r.add($r(a.add(Ir),18)).add(s),n)}(e,t);if(t<=64)return function(e,t=e.length){const n=Ir.add(2*t),r=Tr(e,0).mul(Ir),a=Tr(e,8),s=Tr(e,t-8).mul(n),o=Tr(e,t-16).mul(Ir),i=$r(r.add(a),43).add($r(s,30)).add(o),u=Er(i,r.add($r(a.add(Ir),18)).add(s),n),l=Tr(e,16).mul(n),c=Tr(e,24),d=i.add(Tr(e,t-32)).mul(n),p=u.add(Tr(e,t-24)).mul(n);return Er($r(l.add(c),43).add($r(d,30)).add(p),l.add($r(c.add(r),18)).add(d),n)}(e,t);let r=n,a=n.mul(kr).add(113),s=Nr(a.mul(Ir).add(113)).mul(Ir),o=[xr.UZERO,xr.UZERO],i=[xr.UZERO,xr.UZERO];r=r.mul(Ir).add(Tr(e,0));let u=0;const l=64*(t-1>>6),c=l+(t-1&63)-63;do{r=$r(r.add(a).add(o[0]).add(Tr(e,u+8)),37).mul(kr),a=$r(a.add(o[1]).add(Tr(e,u+48)),42).mul(kr),r=r.xor(i[1]),a=a.add(o[0]).add(Tr(e,u+40)),s=$r(s.add(i[0]),33).mul(kr),o=Rr(e,u,o[1].mul(kr),r.add(i[0])),i=Rr(e,u+32,s.add(i[1]),a.add(Tr(e,u+16))),[s,r]=[r,s],u+=64}while(u!==l);const d=kr.add(s.and(255).shl(1));return u=c,i[0]=i[0].add(t-1&63),o[0]=o[0].add(i[0]),i[0]=i[0].add(o[0]),r=$r(r.add(a).add(o[0]).add(Tr(e,u+8)),37).mul(d),a=$r(a.add(o[1]).add(Tr(e,u+48)),42).mul(d),r=r.xor(i[1].mul(9)),a=a.add(o[0].mul(9).add(Tr(e,u+40))),s=$r(s.add(i[0]),33).mul(d),o=Rr(e,u,o[1].mul(d),r.add(i[0])),i=Rr(e,u+32,s.add(i[1]),a.add(Tr(e,u+16))),[s,r]=[r,s],Er(Er(o[0],i[0],d).add(Nr(a).mul(wr)).add(s),Er(o[1],i[1],d).add(r),d)}function Ar(e,t){return"string"===t?Dr(e):Or([e],t)}function Or(e,t){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=Lr(e)),V().getBool("DEBUG")&&function(e,t){for(let n=0;n{r=n()};let s;const o=Fr();if(this.backendTimer.timerAvailable())s=this.backendTimer.time(a);else{a();for(const e of r)e.dataSync();s=Promise.resolve({kernelMs:Fr()-o})}if(V().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let i=0;i{Vr(n,t.dtype,e)})}return{kernelName:e,outputs:r,inputs:t,timeMs:s.then(e=>e.kernelMs),extraInfo:s.then(e=>null!=e.getExtraProfileInfo?e.getExtraProfileInfo():"")}}logKernelProfile(e){const{kernelName:t,outputs:n,timeMs:r,inputs:a,extraInfo:s}=e;n.forEach(e=>{Promise.all([e.data(),r,s]).then(n=>{this.logger.logKernelProfile(t,e,n[0],n[1],a,n[2])})})}}function Vr(e,t,n){if("float32"!==t)return!1;for(let r=0;r0?n:""} `}}console.log(`%c${i}\t%c${o}\t%c${u}D ${c}\t%c${l}\t%c${d}\t%c${s}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}function zr(e,t,n,r){const a=C(t),s=function(e,t,n,r){const a=c(t),s=r[r.length-1],o=new Array(s).fill(0),i=t.length,u="complex64"===n?jr(e):e;if(i>1)for(let l=0;l" "+e).join("\n")),u.join("\n")}function Ur(e,t,n){let r;return r=Array.isArray(e)?`${parseFloat(e[0].toFixed(7))} + ${parseFloat(e[1].toFixed(7))}j`:I(e)?`'${e}'`:"bool"===n?Gr(e):parseFloat(e.toFixed(7)).toString(),f(r,t)}function Gr(e){return 0===e?"false":"true"}function Hr(e,t,n,r,a,s=!0){const o="complex64"===n?2:1,i=t[0],u=t.length;if(0===u){if("complex64"===n){return[Ur(jr(e)[0],0,n)]}return"bool"===n?[Gr(e[0])]:[e[0].toString()]}if(1===u){if(i>20){const t=3*o;let r=Array.from(e.slice(0,t)),s=Array.from(e.slice((i-3)*o,i*o));return"complex64"===n&&(r=jr(r),s=jr(s)),["["+r.map((e,t)=>Ur(e,a[t],n)).join(", ")+", ..., "+s.map((e,t)=>Ur(e,a[i-3+t],n)).join(", ")+"]"]}return["["+("complex64"===n?jr(e):Array.from(e)).map((e,t)=>Ur(e,a[t],n)).join(", ")+"]"]}const l=t.slice(1),c=r.slice(1),d=r[0]*o,p=[];if(i>20){for(let t=0;t<3;t++){const r=t*d,s=r+d;p.push(...Hr(e.slice(r,s),l,n,c,a,!1))}p.push("...");for(let t=i-3;t0?p[0]+h:"");for(let m=1;m`Length of values '${e}' does not match the size inferred by the shape '${this.size}'.`)}if("complex64"===t)throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||v(t,this.size),this.strides=C(e)}set(e,...t){0===t.length&&(t=[0]),i(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);const n=this.locToIndex(t);this.values[n]=e}get(...e){0===e.length&&(e=[0]);let t=0;for(const r of e){if(r<0||r>=this.shape[t]){const t=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(t)}t++}let n=e[e.length-1];for(let r=0;rMr(e))}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataToGPU(e){return this.throwIfDisposed(),Kr().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();const e=Kr().readSync(this.dataId);if("string"===this.dtype)try{return e.map(e=>Mr(e))}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e}async bytes(){this.throwIfDisposed();const e=await Kr().read(this.dataId);return"string"===this.dtype?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(this.kerasMask&&this.kerasMask.dispose(),Kr().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Xr.print(this,e)}clone(){return this.throwIfDisposed(),Xr.clone(this)}toString(e=!1){return zr(this.dataSync(),this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Xr.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Kr().makeVariable(this,e,t,n)}}function Qr(){return G("Tensor",()=>Yr)}Object.defineProperty(Yr,Symbol.hasInstance,{value:e=>!!e&&null!=e.data&&null!=e.dataSync&&null!=e.throwIfDisposed}),Qr();class Zr extends Yr{constructor(e,t,n,r){super(e.shape,e.dtype,e.dataId,r),this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!d(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Kr().disposeTensor(this),this.dataId=e.dataId,Kr().incRef(this,null)}dispose(){Kr().disposeVariable(this),this.isDisposedInternal=!0}}var Jr,ea,ta,na,ra,aa,sa,oa,ia,ua;Object.defineProperty(Zr,Symbol.hasInstance,{value:e=>e instanceof Yr&&null!=e.assign&&e.assign instanceof Function}),(ea=Jr||(Jr={})).R0="R0",ea.R1="R1",ea.R2="R2",ea.R3="R3",ea.R4="R4",ea.R5="R5",ea.R6="R6",(na=ta||(ta={})).float32="float32",na.int32="int32",na.bool="int32",na.complex64="complex64",(aa=ra||(ra={})).float32="float32",aa.int32="int32",aa.bool="bool",aa.complex64="complex64",(oa=sa||(sa={})).float32="float32",oa.int32="float32",oa.bool="float32",oa.complex64="complex64",(ua=ia||(ia={})).float32="complex64",ua.int32="complex64",ua.bool="complex64",ua.complex64="complex64";const la={float32:sa,int32:ta,bool:ra,complex64:ia};function ca(e,t){if("string"===e||"string"===t){if("string"===e&&"string"===t)return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return la[e][t]}function da(e){return ca(e,"int32")}function pa(e){return null!=e&&"object"===typeof e&&"texture"in e&&e.texture instanceof WebGLTexture}function ha(e){return"undefined"!==typeof GPUBuffer&&null!=e&&"object"===typeof e&&"buffer"in e&&e.buffer instanceof GPUBuffer}function fa(e,t){if(e.dtype===t.dtype)return[e,t];const n=ca(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function ma(e){const t=[];return ga(e,t,/* @__PURE__ */new Set),t}function ga(e,t,n){if(null==e)return;if(e instanceof Yr)return void t.push(e);if(r=e,!Array.isArray(r)&&"object"!==typeof r)return;var r;const a=e;for(const s in a){const e=a[s];n.has(e)||(n.add(e),ga(e,t,n))}}function ya(e){return null!=e.kernelName}class ba{constructor(){this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.gradientDepth=0,this.kernelDepth=0,this.scopeStack=[],this.numDataMovesStack=[],this.nextScopeId=0,this.tensorInfo=/* @__PURE__ */new WeakMap,this.profiling=!1,this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null,get kernelNames(){return Array.from(new Set(this.kernels.map(e=>e.name)))}}}dispose(){for(const e in this.registeredVariables)this.registeredVariables[e].dispose()}}class xa{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new ba}async ready(){if(null!=this.pendingBackendInit)return this.pendingBackendInit.then(()=>{});if(null!=this.backendInstance)return;const e=this.getSortedBackends();for(let t=0;t{null!=e.setupFunc&&e.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){ur(e).forEach(t=>{null!=t.disposeFunc&&t.disposeFunc(this.registry[e])})}initializeBackend(e){const t=this.registryFactory[e];if(null==t)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{const r=t.factory();if(!r||r instanceof n||"function"!==typeof r.then)return this.registry[e]=r,{success:!0,asyncInit:!1};{const t=++this.pendingBackendInitId,n=r.then(n=>!(t(tthis.registryFactory[t].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){const e=this.getSortedBackends();for(let t=0;tthis.startScope(r),()=>this.endScope(n),()=>(n=t(),n instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n))}scopedRun(e,t,n){e();try{const e=n();return t(),e}catch(r){throw t(),r}}nextTensorId(){return xa.nextTensorId++}nextVariableId(){return xa.nextVariableId++}clone(e){const t=wa.runKernel(ot,{x:e}),n={x:e};return this.addTapeNode(this.state.activeScope.name,n,[t],e=>({x:()=>{const t={x:e},n={dtype:"float32"};return wa.runKernel(fe,t,n)}}),[],{}),t}runKernel(e,t,n){null==this.backendName&&this.backend;if(!(null!=or(e,this.backendName)))throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){const r=this.backend.numDataIds();let a=0;n.forEach(e=>{a+="complex64"===e.dtype?3:1});const s=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],o=r-t-a-s;if(o>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${o} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[];const r=this.isTapeOn(),a=this.state.numBytes,s=this.state.numTensors;let o,u;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0),null==this.backendName&&this.backend;const l=ya(e)?e.kernelName:null!=this.state.activeScope?this.state.activeScope.name:"";if(ya(e)){const{kernelName:t,inputs:a,attrs:s}=e;null==this.backendName&&this.backend;const l=or(t,this.backendName);i(null!=l,()=>`Cannot find registered kernel '${t}' for backend '${this.backendName}'`),o=()=>{const e=this.backend.numDataIds();u=l.kernelFunc({inputs:a,attrs:s,backend:this.backend});const o=Array.isArray(u)?u:[u];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(t,e,o);const i=o.map(e=>null!=e.rank?e:this.makeTensorFromTensorInfo(e));if(r){const e=this.getTensorsForGradient(t,a,i);n=this.saveTensorsForBackwardMode(e)}return i}}else{const{forwardFunc:t}=e,a=e=>{r&&(n=e.map(e=>this.keep(this.clone(e))))};o=()=>{const e=this.backend.numDataIds();u=this.tidy(()=>t(this.backend,a));const n=Array.isArray(u)?u:[u];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,e,n),n}}const{inputs:c,attrs:d}=e,p=ya(e)?null:e.backwardsFunc;let h;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{this.ENV.getBool("DEBUG")||this.state.profiling?(h=this.profiler.profileKernel(l,c,()=>o()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(h),t=h.outputs):t=o()}),r&&this.addTapeNode(l,c,t,p,n,d),this.state.profiling&&this.state.activeProfile.kernels.push({name:l,bytesAdded:this.state.numBytes-a,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-s,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(c).map(e=>null!=c[e]?c[e].shape:null),outputShapes:t.map(e=>e.shape),kernelTimeMs:h.timeMs,extraInfo:h.extraInfo}),Array.isArray(u)?t:t[0]}saveTensorsForBackwardMode(e){return e.map(e=>this.keep(this.clone(e)))}getTensorsForGradient(e,t,n){const r=ir(e);if(null!=r){const e=r.inputsToSave||[],a=r.outputsToSave||[];let s;r.saveAllInputs?(i(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),s=Object.keys(t).map(e=>t[e])):s=e.map(e=>t[e]);const o=n.filter((e,t)=>a[t]);return s.concat(o)}return[]}makeTensor(e,t,n,r){if(null==e)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",r=r||this.backend;let a=e;"string"===n&&I(e[0])&&(a=e.map(e=>Dr(e)));const s=r.write(a,t,n),o=new Yr(t,n,s,this.nextTensorId());if(this.trackTensor(o,r),"string"===n){const e=this.state.tensorInfo.get(s),t=function(e){if(null==e)return 0;let t=0;return e.forEach(e=>t+=e.length),t}(a);this.state.numBytes+=t-e.bytes,e.bytes=t}return o}makeTensorFromDataId(e,t,n,r){const a={dataId:e,shape:t,dtype:n=n||"float32"};return this.makeTensorFromTensorInfo(a,r)}makeTensorFromTensorInfo(e,t){const{dataId:n,shape:r,dtype:a}=e,s=new Yr(r,a,n,this.nextTensorId());return this.trackTensor(s,t),s}makeVariable(e,t=!0,n,r){n=n||this.nextVariableId().toString(),null!=r&&r!==e.dtype&&(e=e.cast(r));const a=new Zr(e,t,n,this.nextTensorId());if(null!=this.state.registeredVariables[a.name])throw new Error(`Variable with name ${a.name} was already registered`);return this.state.registeredVariables[a.name]=a,this.incRef(a,this.backend),a}trackTensor(e,t){this.state.numTensors++,"string"===e.dtype&&this.state.numStringTensors++;let n=0;"complex64"!==e.dtype&&"string"!==e.dtype&&(n=e.size*k(e.dtype)),this.state.numBytes+=n,this.state.tensorInfo.has(e.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:n})),e instanceof Zr||this.track(e)}incRef(e,t){this.trackTensor(e,t),this.backend.incRef(e.dataId)}removeDataId(e,t){this.state.tensorInfo.has(e)&&this.state.tensorInfo.get(e).backend===t&&(this.state.tensorInfo.delete(e),this.state.numDataBuffers--)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;const t=this.state.tensorInfo.get(e.dataId);if(this.state.numTensors--,"string"===e.dtype&&(this.state.numStringTensors--,this.state.numBytes-=t.bytes),"complex64"!==e.dtype&&"string"!==e.dtype){const t=e.size*k(e.dtype);this.state.numBytes-=t}t.backend.disposeData(e.dataId)&&this.removeDataId(e.dataId,t.backend)}disposeVariables(){for(const e in this.state.registeredVariables){const t=this.state.registeredVariables[e];this.disposeVariable(t)}}disposeVariable(e){this.disposeTensor(e),null!=this.state.registeredVariables[e.name]&&delete this.state.registeredVariables[e.name]}memory(){const e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,null==e.reasons&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e}async profile(e){this.state.profiling=!0;const t=this.state.numBytes,n=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map(e=>e.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(const r of this.state.activeProfile.kernels)r.kernelTimeMs=await r.kernelTimeMs,r.extraInfo=await r.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&0===this.state.kernelDepth}addTapeNode(e,t,n,r,a,s){const o={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:a},i=ir(e);null!=i&&(r=i.gradFunc),null!=r&&(o.gradient=e=>(e=e.map((e,t)=>{if(null==e){const e=n[t],r=_(e.size,e.dtype);return this.makeTensor(r,e.shape,e.dtype)}return e}),r(e.length>1?e:e[0],a,s))),this.state.activeTape.push(o)}keep(e){return e.kept=!0,e}startTape(){0===this.state.gradientDepth&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){const t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){const t=ma(e),n=new Set(t.map(e=>e.id));for(let a=0;a{e.kept||e.scopeId!==r.id||this.track(e)})}gradients(e,t,n,r=!1){if(i(t.length>0,()=>"gradients() received an empty list of xs."),null!=n&&"float32"!==n.dtype)throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`);const a=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));i(a instanceof Yr,()=>"The result y returned by f() must be a tensor.");const s=function(e,t,n){const r={},a={};for(let u=0;ur[e.id]=!0),i=!0,a[n.id]=!0;break}if(i)break}}const s={};s[n.id]=!0;const o={};for(let u=e.length-1;u>=0;u--){const t=e[u],n=t.inputs;for(let e=0;e0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",()=>{const e={};e[a.id]=n??function(e){const t=R(c(e),"float32");return wa.makeTensor(t,e,"float32")}(a.shape),function(e,t,n,r){for(let a=t.length-1;a>=0;a--){const s=t[a],o=[];if(s.outputs.forEach(t=>{const n=e[t.id];null!=n?o.push(n):o.push(null)}),null==s.gradient)throw new Error(`Cannot compute gradient: gradient function not found for ${s.kernelName}.`);const i=s.gradient(o);for(const t in s.inputs){if(!(t in i))throw new Error(`Cannot backprop through input ${t}. Available gradients found: ${Object.keys(i)}.`);const a=n(()=>i[t]());if("float32"!==a.dtype)throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input ${t} must have 'float32' dtype, but has '${a.dtype}'`);const o=s.inputs[t];if(!d(a.shape,o.shape))throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input '${t}' has shape '${a.shape}', which does not match the shape of the input '${o.shape}'`);if(null==e[o.id])e[o.id]=a;else{const t=e[o.id];e[o.id]=r(t,a),t.dispose()}}}}(e,s,e=>this.tidy(e),ka);const r=t.map(t=>e[t.id]);return 0===this.state.gradientDepth&&(this.state.activeTape.forEach(e=>{for(const t of e.saved)t.dispose()}),this.state.activeTape=null),{value:a,grads:r}})}customGrad(e){return i(S(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{let n;i(t.every(e=>e instanceof Yr),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");const r={};t.forEach((e,t)=>{r[t]=e});return this.runKernelFunc({forwardFunc:(r,a)=>(n=e(...t,a),i(n.value instanceof Yr,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),i(S(n.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),n.value),backwardsFunc:(e,r)=>{const a=n.gradFunc(e,r),s=Array.isArray(a)?a:[a];i(s.length===t.length,()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."),i(s.every(e=>e instanceof Yr),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");const o={};return s.forEach((e,t)=>{o[t]=()=>e}),o},inputs:r})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}readToGPU(e,t){return this.state.tensorInfo.get(e).backend.readToGPU(e,t)}async time(e){const t=Fr(),n=await this.backend.time(e);return n.wallMs=Fr()-t,n}track(e){return null!=this.state.activeScope&&(e.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(e)),e}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new ba;for(const e in this.registry)this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}}function va(){const e=U();if(null==e._tfengine){const t=new L(e);e._tfengine=new xa(t)}var t;return t=e._tfengine.ENV,z=t,Kr=()=>e._tfengine,e._tfengine}xa.nextTensorId=0,xa.nextVariableId=0;const wa=va();function ka(e,t){const n={a:e,b:t};return wa.runKernel(K,n)}function Ia(e){if(e||"undefined"!==typeof navigator&&null!=navigator){if(e||(e=navigator),"ReactNative"===e.product)return!0;const t=e.userAgent||e.vendor||("undefined"!==typeof window?window.opera:"");if(!t){const t=e;return t.userAgentData&&t.userAgentData.mobile}return/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(t)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(t.substr(0,4))}return!1}function Na(){return"undefined"!==typeof window&&null!=window.document||"undefined"!==typeof WorkerGlobalScope}const Sa=V();function Ta(e,t){let n=e;if(Pr(e))return"string"===t?[]:[e.length];if(pa(e)){const t=e.channels||"RGBA";return[e.height,e.width*t.length]}if(ha(e))return[e.buffer.size/(null==t?4:k(t))];if(!Array.isArray(e))return[];const r=[];for(;Array.isArray(n)||Pr(n)&&"string"!==t;)r.push(n.length),n=n[0];return Array.isArray(e)&&V().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&Ca(e,r,[]),r}function Ca(e,t,n){if(n=n||[],!Array.isArray(e)&&!Pr(e))return void i(0===t.length,()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);i(t.length>0,()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`),i(e.length===t[0],()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`);const r=t.slice(1);for(let a=0;a=0&&(a=r),$a(r,a,t,n),null==e||!Pr(e)&&!Array.isArray(e)&&"number"!==typeof e&&"boolean"!==typeof e&&"string"!==typeof e){const r=null==e?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${n}' must be a Tensor or TensorLike, but got '${r}'`)}const s=Ta(e,a);Pr(e)||Array.isArray(e)||(e=[e]);const o="string"!==a?Or(e,a):Lr(e,[],!0);return wa.makeTensor(o,s,a)}function Ra(e,t,n,r="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);return e.map((e,a)=>Ea(e,`${t}[${a}]`,n,r))}Sa.registerFlag("DEBUG",()=>!1,e=>{e&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")}),Sa.registerFlag("IS_BROWSER",()=>Na()),Sa.registerFlag("IS_NODE",()=>"undefined"!==typeof process&&"undefined"!==typeof process.versions&&"undefined"!==typeof process.versions.node),Sa.registerFlag("IS_CHROME",()=>"undefined"!==typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)),Sa.registerFlag("IS_SAFARI",()=>"undefined"!==typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Safari/.test(navigator.userAgent)&&/Apple/.test(navigator.vendor)),Sa.registerFlag("PROD",()=>!1),Sa.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Sa.getBool("DEBUG")),Sa.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0),Sa.registerFlag("IS_TEST",()=>!1),Sa.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>Sa.getBool("DEBUG")),Sa.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1),Sa.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU",()=>!1),Sa.registerFlag("USE_SETTIMEOUTCUSTOM",()=>!1);const _a="__op";function Aa(e){const t=Object.keys(e);if(1!==t.length)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${t.length} keys.`);let n=t[0];const r=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1)),n+=_a;const a=(...e)=>{wa.startScope(n);try{const t=r(...e);return M(t)&&console.error("Cannot return a Promise inside of tidy."),wa.endScope(t),t}catch(t){throw wa.endScope(null),t}};return Object.defineProperty(a,"name",{value:n,configurable:!0}),a}const Oa=/* @__PURE__ */Aa({complex_:function(e,t){const n=Ea(e,"real","complex"),r=Ea(t,"imag","complex");u(n.shape,r.shape,`real and imag shapes, ${n.shape} and ${r.shape}, must match in call to tf.complex().`);const a={real:n,imag:r};return wa.runKernel(ye,a)}});function Fa(e,t,n,r){if(null==r)r=N(e);else if("complex64"===r)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(ha(e)||pa(e)){if("float32"!==r&&"int32"!==r)throw new Error(`Creating tensor from GPU data only supports 'float32'|'int32' dtype, while the dtype is ${r}.`);return wa.backend.createTensorFromGPUData(e,t||n,r)}if(!Pr(e)&&!Array.isArray(e)&&"number"!==typeof e&&"boolean"!==typeof e&&"string"!==typeof e)throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(null!=t){O(t);const e=c(t),r=c(n);i(e===r,()=>`Based on the provided shape, [${t}], the tensor should have ${e} values but has ${r}`);for(let a=0;a`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `)}}return Pr(e)||Array.isArray(e)||(e=[e]),t=t||n,e="string"!==r?Or(e,r):Lr(e,[],!0),wa.makeTensor(e,t,r)}function Da(e,t,n){return Fa(e,t,Ta(e,n),n)}const Ma={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};class Pa{static join(e){return new Pa(e).slice()}constructor(e){if(this.shards=[],this.previousShardIndex=0,null==e)return;if(e instanceof Array||(e=[e]),0===(e=e.map(e=>Pr(e)?e.buffer:e)).length)return;this.bufferUniformSize=e[0].byteLength;let t=0;for(let n=0;n=this.byteLength)return-1;if(null!=this.bufferUniformSize)return this.previousShardIndex=Math.floor(e/this.bufferUniformSize),this.previousShardIndex;function t(t){return e=t.end?1:0}if(0===t(this.shards[this.previousShardIndex]))return this.previousShardIndex;const n=function(e,t){let n=0,r=e.length;for(;n<=r;){const a=Math.floor((r-n)/2)+n,s=t(e[a]);if(0===s)return a;s<0?r=a:n=a+1}return-1}(this.shards,t);return-1===n?-1:(this.previousShardIndex=n,this.previousShardIndex)}}function La(){return wa}function Ba(e,t){return wa.tidy(e,t)}function Va(e){ma(e).forEach(e=>e.dispose())}function Wa(e){return wa.keep(e)}function za(e){return wa.setBackend(e)}function Ua(){return wa.backendName}function Ga(e,t,n=1){return wa.registerBackend(e,t,n)}function Ha(){return wa.backend}function ja(e,t){const n=new Pa(e),r={};let a=0;for(const s of t){const e=qa(s,(e,t)=>n.slice(a+e,a+t));r[s.name]=Xa(s,n.slice(a,a+e)),a+=e}return r}function qa(e,t){const n=c(e.shape);let r;if("quantization"in e){const t=e.quantization;r=Ma[t.dtype]}else{if("string"===e.dtype){let e=0;for(let r=0;r{let t=e<<13,n=0;for(;0===(8388608&t);)n-=8388608,t<<=1;return t&=-8388609,n+=947912704,t|n},t=new Uint32Array(2048);t[0]=0;for(let n=1;n<1024;n++)t[n]=e(n);for(let n=1024;n<2048;n++)t[n]=939524096+(n-1024<<13);return t}(),t=function(){const e=new Uint32Array(64);e[0]=0,e[31]=1199570944,e[32]=2147483648,e[63]=3347054592;for(let t=1;t<31;t++)e[t]=t<<23;for(let t=33;t<63;t++)e[t]=2147483648+(t-32<<23);return e}(),n=function(){const e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}();return r=>{const a=new ArrayBuffer(4*r.length),s=new Uint32Array(a);for(let o=0;o>10]+(1023&a)]+t[a>>10];s[o]=i}return new Float32Array(a)}}();o=e(l)}}else{if("int32"!==r)throw new Error(`Unsupported dtype in weight '${n}': ${r}`);if("uint8"!==a.dtype&&"uint16"!==a.dtype)throw new Error(`Unsupported quantization type ${a.dtype} for weight type int32.`);o=new Int32Array(l.length);for(let e=0;e(a=await Ya(r,a,t),a.slice(e,t)));a=await Ya(r,a,e);const t=a.slice(0,e);a=a.slice(e);const o=Xa(s,t);if(n[s.name]=o,"webgpu"===Ua()){const e=Ha();"uploadToGPU"in e&&c(o.shape)>=V().get("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD")&&e.uploadToGPU(o.dataId)}}return n}function Za(e){if(null===e)throw new Error(`Invalid input value: ${JSON.stringify(e)}`);let t=0;const n=[];e.forEach(e=>{if(t+=e.byteLength,n.push(e.byteLength===e.buffer.byteLength?e:new e.constructor(e)),!(e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${e.constructor.name}`)});const r=new Uint8Array(t);let a=0;return n.forEach(e=>{r.set(new Uint8Array(e.buffer),a),a+=e.byteLength}),r.buffer}const Ja="undefined"!==typeof Buffer&&("undefined"===typeof Blob||"undefined"===typeof atob||"undefined"===typeof btoa);function es(e){return Ja?Buffer.byteLength(e,"utf8"):new Blob([e]).size}function ts(e){for(e=e.trim();e.endsWith("/");)e=e.slice(0,e.length-1);const t=e.split("/");return t[t.length-1]}function ns(e,t){const n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:t};return null!=e.signature&&(n.signature=e.signature),null!=e.userDefinedMetadata&&(n.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(n.modelInitializer=e.modelInitializer),null!=e.initializerSignature&&(n.initializerSignature=e.initializerSignature),null!=e.trainingConfig&&(n.trainingConfig=e.trainingConfig),n}function rs(e,t,n){const r={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};if(null!=e.trainingConfig&&(r.trainingConfig=e.trainingConfig),null!=e.weightsManifest){if(!t)throw new Error("modelJSON has weightsManifest but weightSpecs is null");if(!n)throw new Error("modelJSON has weightsManifest but weightData is null");r.weightSpecs=t,r.weightData=n}return null!=e.signature&&(r.signature=e.signature),null!=e.userDefinedMetadata&&(r.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(r.modelInitializer=e.modelInitializer),null!=e.initializerSignature&&(r.initializerSignature=e.initializerSignature),r}async function as(e,t){let n,r;return null!=e.weightsManifest&&([n,r]=await t(e.weightsManifest)),rs(e,n,r)}function ss(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:/* @__PURE__ */new Date,modelTopologyType:"JSON",modelTopologyBytes:null==e.modelTopology?0:es(JSON.stringify(e.modelTopology)),weightSpecsBytes:null==e.weightSpecs?0:es(JSON.stringify(e.weightSpecs)),weightDataBytes:null==e.weightData?0:new Pa(e.weightData).byteLength}}function os(e){const t=[];for(const n of e)t.push(...n.weights);return t}class is{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return null==is.instance&&(is.instance=new is),is.instance}static registerSaveRouter(e){is.getInstance().saveRouters.push(e)}static registerLoadRouter(e){is.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return is.getHandlers(e,"save")}static getLoadHandlers(e,t){return is.getHandlers(e,"load",t)}static getHandlers(e,t,n){const r=[];return("load"===t?is.getInstance().loadRouters:is.getInstance().saveRouters).forEach(t=>{const a=t(e,n);null!==a&&r.push(a)}),r}}const us="tensorflowjs",ls="models_store",cs="model_info_store";function ds(){if(!V().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");const e="undefined"===typeof window?self:window,t=e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB||e.shimIndexedDB;if(null==t)throw new Error("The current browser does not appear to support IndexedDB.");return t}function ps(e){const t=e.result;t.createObjectStore(ls,{keyPath:"modelPath"}),t.createObjectStore(cs,{keyPath:"modelPath"})}class hs{constructor(e){if(this.indexedDB=ds(),null==e||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return this.databaseAction(this.modelPath,e)}async load(){return this.databaseAction(this.modelPath)}databaseAction(e,t){return new Promise((e,n)=>{const r=this.indexedDB.open(us,1);r.onupgradeneeded=()=>ps(r),r.onsuccess=()=>{const a=r.result;if(null==t){const t=a.transaction(ls,"readonly"),r=t.objectStore(ls).get(this.modelPath);r.onsuccess=()=>{if(null==r.result)return a.close(),n(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));e(r.result.modelArtifacts)},r.onerror=e=>(a.close(),n(r.error)),t.oncomplete=()=>a.close()}else{t.weightData=Pa.join(t.weightData);const r=ss(t),o=a.transaction(cs,"readwrite");let i,u,l=o.objectStore(cs);try{i=l.put({modelPath:this.modelPath,modelArtifactsInfo:r})}catch(s){return n(s)}i.onsuccess=()=>{u=a.transaction(ls,"readwrite");const i=u.objectStore(ls);let c;try{c=i.put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:r})}catch(s){return n(s)}c.onsuccess=()=>e({modelArtifactsInfo:r}),c.onerror=e=>{l=o.objectStore(cs);const t=l.delete(this.modelPath);t.onsuccess=()=>(a.close(),n(c.error)),t.onerror=e=>(a.close(),n(c.error))}},i.onerror=e=>(a.close(),n(i.error)),o.oncomplete=()=>{null==u?a.close():u.oncomplete=()=>a.close()}}},r.onerror=e=>n(r.error)})}}hs.URL_SCHEME="indexeddb://";const fs=e=>{return V().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(hs.URL_SCHEME)?(t=e.slice(hs.URL_SCHEME.length),new hs(t)):null;var t};is.registerSaveRouter(fs),is.registerLoadRouter(fs);class ms{constructor(){this.indexedDB=ds()}async listModels(){return new Promise((e,t)=>{const n=this.indexedDB.open(us,1);n.onupgradeneeded=()=>ps(n),n.onsuccess=()=>{const r=n.result,a=r.transaction(cs,"readonly"),s=a.objectStore(cs).getAll();s.onsuccess=()=>{const t={};for(const e of s.result)t[e.modelPath]=e.modelArtifactsInfo;e(t)},s.onerror=e=>(r.close(),t(s.error)),a.oncomplete=()=>r.close()},n.onerror=e=>t(n.error)})}async removeModel(e){var t;return e=(t=e).startsWith(hs.URL_SCHEME)?t.slice(hs.URL_SCHEME.length):t,new Promise((t,n)=>{const r=this.indexedDB.open(us,1);r.onupgradeneeded=()=>ps(r),r.onsuccess=()=>{const a=r.result,s=a.transaction(cs,"readwrite"),o=s.objectStore(cs),i=o.get(e);let u;i.onsuccess=()=>{if(null==i.result)return a.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{const r=o.delete(e),s=()=>{u=a.transaction(ls,"readwrite");const r=u.objectStore(ls).delete(e);r.onsuccess=()=>t(i.result.modelArtifactsInfo),r.onerror=e=>n(i.error)};r.onsuccess=s,r.onerror=e=>(s(),a.close(),n(i.error))}},i.onerror=e=>(a.close(),n(i.error)),s.oncomplete=()=>{null==u?a.close():u.oncomplete=()=>a.close()}},r.onerror=e=>n(r.error)})}}const gs="/",ys="tensorflowjs_models",bs="info",xs="model_topology",vs="weight_specs",ws="weight_data",ks="model_metadata";function Is(e){return{info:[ys,e,bs].join(gs),topology:[ys,e,xs].join(gs),weightSpecs:[ys,e,vs].join(gs),weightData:[ys,e,ws].join(gs),modelMetadata:[ys,e,ks].join(gs)}}function Ns(e){for(const t of Object.values(e))window.localStorage.removeItem(t)}function Ss(e){const t=e.split(gs);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(gs)}class Ts{constructor(e){if(!V().getBool("IS_BROWSER")||"undefined"===typeof window||"undefined"===typeof window.localStorage)throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,null==e||!e)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=e,this.keys=Is(this.modelPath)}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");{const n=JSON.stringify(e.modelTopology),r=JSON.stringify(e.weightSpecs),a=ss(e),s=Pa.join(e.weightData);try{this.LS.setItem(this.keys.info,JSON.stringify(a)),this.LS.setItem(this.keys.topology,n),this.LS.setItem(this.keys.weightSpecs,r),this.LS.setItem(this.keys.weightData,function(e){if(Ja)return Buffer.from(e).toString("base64");const t=new Uint8Array(e);let n="";for(let r=0,a=t.length;r{return V().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Ts.URL_SCHEME)?(t=e.slice(Ts.URL_SCHEME.length),new Ts(t)):null;var t};is.registerSaveRouter(Cs),is.registerLoadRouter(Cs);class $s{constructor(){i(V().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),i("undefined"===typeof window||"undefined"!==typeof window.localStorage,()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){const e={},t=ys+gs,n=gs+bs;for(let r=0;r"scheme must not be undefined or null."),e.endsWith(Es)&&(e=e.slice(0,e.indexOf(Es))),i(e.length>0,()=>"scheme must not be an empty string.");const n=Rs.getInstance();i(null==n.managers[e],()=>`A model store manager is already registered for scheme '${e}'.`),n.managers[e]=t}static getManager(e){const t=Rs.getInstance().managers[e];if(null==t)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(Rs.getInstance().managers)}}function _s(e){if(-1===e.indexOf(Es))throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Rs.getSchemes().join(",")}`);return{scheme:e.split(Es)[0],path:e.split(Es)[1]}}async function As(e,t,n=!1){i(e!==t,()=>`Old path and new path are the same: '${e}'`);const r=is.getLoadHandlers(e);i(r.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),i(r.length<2,()=>`Copying failed because more than one (${r.length}) load handlers for source URL ${e}.`);const a=r[0],s=is.getSaveHandlers(t);i(s.length>0,()=>`Copying failed because no save handler is found for destination URL ${t}.`),i(s.length<2,()=>`Copying failed because more than one (${r.length}) save handlers for destination URL ${t}.`);const o=s[0],u=_s(e).scheme,l=_s(e).path,c=u===_s(e).scheme,d=await a.load();n&&c&&await Rs.getManager(u).removeModel(l);const p=await o.save(d);return n&&!c&&await Rs.getManager(u).removeModel(l),p.modelArtifactsInfo}class Os{constructor(){this.messageName="setTimeoutCustom",this.functionRefs=[],this.handledMessageCount=0,this.hasEventListener=!1}fetch(e,t){return fetch(e,t)}now(){return performance.now()}encode(e,t){if("utf-8"!==t&&"utf8"!==t)throw new Error(`Browser's encoder only supports utf-8, but got ${t}`);return null==this.textEncoder&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(e)}decode(e,t){return new TextDecoder(t).decode(e)}setTimeoutCustom(e,t){"undefined"!==typeof window&&V().getBool("USE_SETTIMEOUTCUSTOM")?(this.functionRefs.push(e),setTimeout(()=>{window.postMessage({name:this.messageName,index:this.functionRefs.length-1},"*")},t),this.hasEventListener||(this.hasEventListener=!0,window.addEventListener("message",e=>{if(e.source===window&&e.data.name===this.messageName){e.stopPropagation();(0,this.functionRefs[e.data.index])(),this.handledMessageCount++,this.handledMessageCount===this.functionRefs.length&&(this.functionRefs=[],this.handledMessageCount=0)}},!0))):setTimeout(e,t)}isTypedArray(e){return dr(e)}}if(V().get("IS_BROWSER")){V().setPlatform("browser",new Os);try{Rs.registerManager(Ts.URL_SCHEME,new $s)}catch(fO){}try{Rs.registerManager(hs.URL_SCHEME,new ms)}catch(fO){}}const Fs=()=>require("node-fetch");let Ds;class Ms{constructor(){this.util=require("util"),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return null!=V().global.fetch?V().global.fetch(e,t):(null==Ds&&(Ds=Fs()),Ds(e,t))}now(){const e=process.hrtime();return 1e3*e[0]+e[1]/1e6}encode(e,t){if("utf-8"!==t&&"utf8"!==t)throw new Error(`Node built-in encoder only supports utf-8, but got ${t}`);return this.textEncoder.encode(e)}decode(e,t){return 0===e.length?"":new this.util.TextDecoder(t).decode(e)}isTypedArray(e){return this.util.types.isFloat32Array(e)||this.util.types.isInt32Array(e)||this.util.types.isUint8Array(e)||this.util.types.isUint8ClampedArray(e)}}function Ps(e,t="float32",n){return t=t||"float32",O(e),new qr(e,t,n)}V().get("IS_NODE")&&!V().get("IS_BROWSER")&&V().setPlatform("node",new Ms);const Ls=/* @__PURE__ */Aa({cast_:function(e,t){const n=Ea(e,"x","cast");if(!function(e){return"bool"===e||"complex64"===e||"float32"===e||"int32"===e||"string"===e}(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if("string"===t&&"string"!==n.dtype||"string"!==t&&"string"===n.dtype)throw new Error("Only strings can be casted to strings");const r={x:n},a={dtype:t};return wa.runKernel(fe,r,a)}});const Bs=/* @__PURE__ */Aa({clone_:function(e){const t={x:Ea(e,"x","clone","string_or_numeric")};return wa.runKernel(ot,t)}});function Vs(e,t=!1){console.log(e.toString(t))}va();Xr={buffer:Ps,cast:Ls,clone:Bs,print:Vs};const Ws=/* @__PURE__ */Aa({add_:function(e,t){let n=Ea(e,"a","add"),r=Ea(t,"b","add");[n,r]=fa(n,r);const a={a:n,b:r};return wa.runKernel(K,a)}});const zs=/* @__PURE__ */Aa({floorDiv_:function(e,t){let n=Ea(e,"a","floorDiv"),r=Ea(t,"b","floorDiv");[n,r]=fa(n,r);const a={a:n,b:r};return wa.runKernel(et,a)}});const Us=/* @__PURE__ */Aa({div_:function(e,t){let n=Ea(e,"a","div"),r=Ea(t,"b","div");if([n,r]=fa(n,r),"int32"===n.dtype&&"int32"===r.dtype)return zs(n,r);const a={a:n,b:r};return wa.runKernel(We,a,{})}});const Gs=/* @__PURE__ */Aa({mul_:function(e,t){let n=Ea(e,"a","mul"),r=Ea(t,"b","mul");[n,r]=fa(n,r);const a={a:n,b:r};return wa.runKernel(Mt,a)}});const Hs=/* @__PURE__ */Aa({abs_:function(e){const t=Ea(e,"x","abs");if("complex64"===t.dtype){const e={x:t};return wa.runKernel(be,e)}{const e={x:t};return wa.runKernel(H,e)}}});const js=/* @__PURE__ */Aa({acos_:function(e){const t={x:Ea(e,"x","acos")};return wa.runKernel(j,t)}});const qs=/* @__PURE__ */Aa({acosh_:function(e){const t={x:Ea(e,"x","acosh")};return wa.runKernel(q,t)}});const Ks=/* @__PURE__ */Aa({addN_:function(e){i(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),i(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);const t=e.map((e,t)=>Ea(e,`tensors${t}`,"addN")),n=t[0];t.forEach(e=>{if(e.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(e=>{if(!d(e.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});const r=t;return wa.runKernel(X,r)}});const Xs=/* @__PURE__ */Aa({all_:function(e,t=null,n=!1){const r={x:Ea(e,"x","all","bool")},a={axis:t,keepDims:n};return wa.runKernel(Y,r,a)}});const Ys=/* @__PURE__ */Aa({any_:function(e,t=null,n=!1){const r={x:Ea(e,"x","any","bool")},a={axis:t,keepDims:n};return wa.runKernel(Q,r,a)}});const Qs=/* @__PURE__ */Aa({argMax_:function(e,t=0){const n={x:Ea(e,"x","argMax")},r={axis:t};return wa.runKernel(Z,n,r)}});const Zs=/* @__PURE__ */Aa({argMin_:function(e,t=0){const n={x:Ea(e,"x","argMin")},r={axis:t};return wa.runKernel(J,n,r)}});const Js=/* @__PURE__ */Aa({asin_:function(e){const t={x:Ea(e,"x","asin")};return wa.runKernel(ee,t)}});const eo=/* @__PURE__ */Aa({asinh_:function(e){const t={x:Ea(e,"x","asinh")};return wa.runKernel(te,t)}});const to=/* @__PURE__ */Aa({atan_:function(e){const t={x:Ea(e,"x","atan")};return wa.runKernel(ne,t)}});const no=/* @__PURE__ */Aa({atan2_:function(e,t){let n=Ea(e,"a","atan2"),r=Ea(t,"b","atan2");[n,r]=fa(n,r);const a={a:n,b:r};return wa.runKernel(ae,a)}});const ro=/* @__PURE__ */Aa({atanh_:function(e){const t={x:Ea(e,"x","atanh")};return wa.runKernel(re,t)}});function ao(e,t,n,r,a="NHWC",s){return io(e,[...t,e[3]],n,s,r,null,null,bo(a))}function so(e,t,n,r,a,s,o="channelsLast"){const[i,u]=co(t);let l;if("channelsLast"===o)l=[i,u,e[3],e[3]];else{if("channelsFirst"!==o)throw new Error(`Unknown dataFormat ${o}`);l=[i,u,e[1],e[1]]}return io(e,l,n,r,a,s,!1,o)}function oo(e,t,n,r,a,s,o="NDHWC"){const[i,u,l]=po(t);let c,d;if("NDHWC"===o)d="channelsLast",c=[i,u,l,e[4],e[4]];else{if("NCDHW"!==o)throw new Error(`Unknown dataFormat ${o}`);d="channelsFirst",c=[i,u,l,e[1],e[1]]}return uo(e,c,n,r,a,!1,d,s)}function io(e,t,n,r,a,s,o=!1,i="channelsLast"){let[u,l,c,d]=[-1,-1,-1,-1];if("channelsLast"===i)[u,l,c,d]=e;else{if("channelsFirst"!==i)throw new Error(`Unknown dataFormat ${i}`);[u,d,l,c]=e}const[p,h,,f]=t,[m,g]=co(n),[y,b]=co(r),x=ho(p,y),v=ho(h,b),{padInfo:w,outHeight:k,outWidth:I}=function(e,t,n,r,a,s,o,i,u){let l,c,d;if("number"===typeof e){l={top:e,bottom:e,left:e,right:e,type:0===e?"VALID":"NUMBER"};const a=function(e,t,n,r,a){null==r&&(r=lo(e,t,n));const s=e[0],o=e[1],i=fo((s-t+2*r)/n+1,a),u=fo((o-t+2*r)/n+1,a);return[i,u]}([t,n],s,r,e,i);c=a[0],d=a[1]}else if("same"===e){c=Math.ceil(t/r),d=Math.ceil(n/a);const e=Math.max(0,(c-1)*r+s-t),i=Math.max(0,(d-1)*a+o-n),u=Math.floor(e/2),p=e-u,h=Math.floor(i/2);l={top:u,bottom:p,left:h,right:i-h,type:"SAME"}}else if("valid"===e)l={top:0,bottom:0,left:0,right:0,type:"VALID"},c=Math.ceil((t-s+1)/r),d=Math.ceil((n-o+1)/a);else{if("object"!==typeof e)throw Error(`Unknown padding parameter: ${e}`);{const p="channelsLast"===u?e[1][0]:e[2][0],h="channelsLast"===u?e[1][1]:e[2][1],f="channelsLast"===u?e[2][0]:e[3][0],m="channelsLast"===u?e[2][1]:e[3][1];l={top:p,bottom:h,left:f,right:m,type:0===p&&0===h&&0===f&&0===m?"VALID":"EXPLICIT"},c=fo((t-s+p+h)/r+1,i),d=fo((n-o+f+m)/a+1,i)}}return{padInfo:l,outHeight:c,outWidth:d}}(a,l,c,m,g,x,v,s,i),N=o?f*d:f;let S;return"channelsFirst"===i?S=[u,N,k,I]:"channelsLast"===i&&(S=[u,k,I,N]),{batchSize:u,dataFormat:i,inHeight:l,inWidth:c,inChannels:d,outHeight:k,outWidth:I,outChannels:N,padInfo:w,strideHeight:m,strideWidth:g,filterHeight:p,filterWidth:h,effectiveFilterHeight:x,effectiveFilterWidth:v,dilationHeight:y,dilationWidth:b,inShape:e,outShape:S,filterShape:t}}function uo(e,t,n,r,a,s=!1,o="channelsLast",i){let[u,l,c,d,p]=[-1,-1,-1,-1,-1];if("channelsLast"===o)[u,l,c,d,p]=e;else{if("channelsFirst"!==o)throw new Error(`Unknown dataFormat ${o}`);[u,p,l,c,d]=e}const[h,f,m,,g]=t,[y,b,x]=po(n),[v,w,k]=po(r),I=ho(h,v),N=ho(f,w),S=ho(m,k),{padInfo:T,outDepth:C,outHeight:$,outWidth:E}=function(e,t,n,r,a,s,o,i,u,l,c){let d,p,h,f;"valid"===e&&(e=0);if("number"===typeof e){d={top:e,bottom:e,left:e,right:e,front:e,back:e,type:0===e?"VALID":"NUMBER"};const m=function(e,t,n,r,a,s){null==a&&(a=lo(e,t[0],r[0]));const o=[0,0,0,n];for(let i=0;i<3;i++)e[i]+2*a>=t[i]&&(o[i]=fo((e[i]-t[i]+2*a)/r[i]+1,s));return o}([t,n,r,1],[i,u,l],1,[a,s,o],e,c);p=m[0],h=m[1],f=m[2]}else{if("same"!==e)throw Error(`Unknown padding parameter: ${e}`);{p=Math.ceil(t/a),h=Math.ceil(n/s),f=Math.ceil(r/o);const e=(p-1)*a+i-t,c=(h-1)*s+u-n,m=(f-1)*o+l-r,g=Math.floor(e/2),y=e-g,b=Math.floor(c/2),x=c-b,v=Math.floor(m/2);d={top:b,bottom:x,left:v,right:m-v,front:g,back:y,type:"SAME"}}}return{padInfo:d,outDepth:p,outHeight:h,outWidth:f}}(a,l,c,d,y,b,x,I,N,S,i),R=s?g*p:g;let _;return"channelsFirst"===o?_=[u,R,C,$,E]:"channelsLast"===o&&(_=[u,C,$,E,R]),{batchSize:u,dataFormat:o,inDepth:l,inHeight:c,inWidth:d,inChannels:p,outDepth:C,outHeight:$,outWidth:E,outChannels:R,padInfo:T,strideDepth:y,strideHeight:b,strideWidth:x,filterDepth:h,filterHeight:f,filterWidth:m,effectiveFilterDepth:I,effectiveFilterHeight:N,effectiveFilterWidth:S,dilationDepth:v,dilationHeight:w,dilationWidth:k,inShape:e,outShape:_,filterShape:t}}function lo(e,t,n,r=1){const a=ho(t,r);return Math.floor((e[0]*(n-1)-n+a)/2)}function co(e){return"number"===typeof e?[e,e,e]:2===e.length?[e[0],e[1],1]:e}function po(e){return"number"===typeof e?[e,e,e]:e}function ho(e,t){return t<=1?e:e+(e-1)*(t-1)}function fo(e,t){if(!t)return Math.trunc(e);switch(t){case"round":return Math.round(e);case"ceil":return Math.ceil(e);case"floor":return Math.floor(e);default:throw new Error(`Unknown roundingMode ${t}`)}}function mo(e){const[t,n,r]=co(e);return 1===t&&1===n&&1===r}function go(e,t){return mo(e)||mo(t)}function yo(e){return co(e).every(e=>e>0)}function bo(e){if("NHWC"===e)return"channelsLast";if("NCHW"===e)return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function xo(e,t,n){if(null!=n){if("string"===typeof t)throw Error(`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`);if("number"===typeof t)i(p(t),()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`);else{if("object"!==typeof t)throw Error(`Error in ${e}: Unknown padding parameter: ${t}`);t.forEach(t=>{t.forEach(t=>{i(p(t),()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`)})})}}}const vo=/* @__PURE__ */Aa({reshape_:function(e,t){const n={x:Ea(e,"x","reshape","string_or_numeric")},r={shape:t};return wa.runKernel(nn,n,r)}});const wo=/* @__PURE__ */Aa({avgPool_:function(e,t,n,r,a){const s=Ea(e,"x","avgPool","float32");i(go(n,1),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`);let o=s,u=!1;3===s.rank&&(u=!0,o=vo(s,[1,s.shape[0],s.shape[1],s.shape[2]])),i(4===o.rank,()=>`Error in avgPool: x must be rank 4 but got rank ${o.rank}.`),xo("avgPool",r,a);const l={x:o},c={filterSize:t,strides:n,pad:r,dimRoundingMode:a};let d=wa.runKernel(se,l,c);return d=Ls(d,s.dtype),u?vo(d,[d.shape[1],d.shape[2],d.shape[3]]):d}});const ko=/* @__PURE__ */Aa({avgPool3d_:function(e,t,n,r,a,s="NDHWC"){const o=Ea(e,"x","avgPool3d","float32");let u=o,l=!1;4===o.rank&&(l=!0,u=vo(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),i(5===u.rank,()=>`Error in avgPool3d: x must be rank 5 but got rank ${u.rank}.`),i("NDHWC"===s,()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),i("number"===typeof n&&n>0||Array.isArray(n)&&n[0]>0&&n[1]>0&&n[2]>0,()=>`Error in avgPool3d: Stride must be > 0, but got '${n}'`),xo("avgPool3d",r,a);const c={x:u},d={filterSize:t,strides:n,pad:r,dimRoundingMode:a,dataFormat:s};let p=wa.runKernel(ie,c,d);return p=Ls(p,u.dtype),l?vo(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}});const Io=/* @__PURE__ */Aa({concat_:function(e,t=0){i(e.length>=1,()=>"Pass at least one tensor to concat");const n=Ra(e,"tensors","concat","string_or_numeric");if("complex64"===n[0].dtype&&n.forEach(e=>{if("complex64"!==e.dtype)throw new Error(`Cannot concatenate complex64 tensors with a tensor\n with dtype ${e.dtype}. `)}),1===n.length)return Bs(n[0]);const r=n,a={axis:t};return wa.runKernel(xe,r,a)}});const No=/* @__PURE__ */Aa({matMul_:function(e,t,n=!1,r=!1){let a=Ea(e,"a","matMul"),s=Ea(t,"b","matMul");[a,s]=fa(a,s);const o={a,b:s},i={transposeA:n,transposeB:r};return wa.runKernel(le,o,i)}});const So=/* @__PURE__ */Aa({sigmoid_:function(e){const t={x:Ea(e,"x","sigmoid","float32")};return wa.runKernel(wn,t)}});const To=/* @__PURE__ */Aa({slice_:function(e,t,n){const r=Ea(e,"x","slice","string_or_numeric");if(0===r.rank)throw new Error("Slicing scalar is not possible");const a={x:r},s={begin:t,size:n};return wa.runKernel(yn,a,s)}});const Co=/* @__PURE__ */Aa({tanh_:function(e){const t={x:Ea(e,"x","tanh","float32")};return wa.runKernel(zn,t)}});const $o=/* @__PURE__ */Aa({basicLSTMCell_:function(e,t,n,r,a,s){const o=Ea(e,"forgetBias","basicLSTMCell"),i=Ea(t,"lstmKernel","basicLSTMCell"),u=Ea(n,"lstmBias","basicLSTMCell"),l=Ea(r,"data","basicLSTMCell"),c=Ea(a,"c","basicLSTMCell"),d=Ea(s,"h","basicLSTMCell"),p=Io([l,d],1),h=No(p,i),f=Ws(h,u),m=f.shape[0],g=f.shape[1]/4,y=[m,g],b=To(f,[0,0],y),x=To(f,[0,g],y),v=To(f,[0,2*g],y),w=To(f,[0,3*g],y),k=Ws(Gs(So(b),Co(x)),Gs(c,So(Ws(o,v))));return[k,Gs(Co(k),So(w))]}});const Eo=/* @__PURE__ */Aa({batchToSpaceND_:function(e,t,n){const r=Ea(e,"x","batchToSpaceND"),a=t.reduce((e,t)=>e*t);i(r.rank>=1+t.length,()=>`input rank is ${r.rank} but should be > than blockShape.length ${t.length}`),i(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),i(r.shape[0]%a===0,()=>`input tensor batch is ${r.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${a}`);const s={x:r},o={blockShape:t,crops:n};return wa.runKernel(ce,s,o)}});const Ro=/* @__PURE__ */Aa({batchNorm_:function(e,t,n,r,a,s){null==s&&(s=.001);const o=Ea(e,"x","batchNorm"),u=Ea(t,"mean","batchNorm"),l=Ea(n,"variance","batchNorm");let c,d;null!=a&&(c=Ea(a,"scale","batchNorm")),null!=r&&(d=Ea(r,"offset","batchNorm")),i(u.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),i(null==d||u.rank===d.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),i(null==c||u.rank===c.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");const p={x:function(e){let t;return t=0===e.rank||1===e.rank?vo(e,[1,1,1,e.size]):2===e.rank?vo(e,[1,1,e.shape[0],e.shape[1]]):3===e.rank?vo(e,[1,e.shape[0],e.shape[1],e.shape[2]]):e,t}(o),scale:c,offset:d,mean:u,variance:l},h={varianceEpsilon:s},f=wa.runKernel(tt,p,h);return vo(f,o.shape)}});const _o=/* @__PURE__ */Aa({batchNorm2d_:function(e,t,n,r,a,s){const o=Ea(e,"x","batchNorm"),u=Ea(t,"mean","batchNorm"),l=Ea(n,"variance","batchNorm");let c,d;return null!=a&&(c=Ea(a,"scale","batchNorm")),null!=r&&(d=Ea(r,"offset","batchNorm")),i(2===o.rank,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${o.rank}.`),i(2===u.rank||1===u.rank,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${u.rank}.`),i(2===l.rank||1===l.rank,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),null!=c&&i(2===c.rank||1===c.rank,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${c.rank}.`),null!=d&&i(2===d.rank||1===d.rank,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${d.rank}.`),Ro(o,u,l,d,c,s)}});const Ao=/* @__PURE__ */Aa({batchNorm3d_:function(e,t,n,r,a,s){const o=Ea(e,"x","batchNorm"),u=Ea(t,"mean","batchNorm"),l=Ea(n,"variance","batchNorm");let c,d;return null!=a&&(c=Ea(a,"scale","batchNorm")),null!=r&&(d=Ea(r,"offset","batchNorm")),i(3===o.rank,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${o.rank}.`),i(3===u.rank||1===u.rank,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${u.rank}.`),i(3===l.rank||1===l.rank,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),null!=c&&i(3===c.rank||1===c.rank,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${c.rank}.`),null!=d&&i(3===d.rank||1===d.rank,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${d.rank}.`),Ro(o,u,l,d,c,s)}});const Oo=/* @__PURE__ */Aa({batchNorm4d_:function(e,t,n,r,a,s){const o=Ea(e,"x","batchNorm"),u=Ea(t,"mean","batchNorm"),l=Ea(n,"variance","batchNorm");let c,d;return null!=a&&(c=Ea(a,"scale","batchNorm")),null!=r&&(d=Ea(r,"offset","batchNorm")),i(4===o.rank,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${o.rank}.`),i(4===u.rank||1===u.rank,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${u.rank}.`),i(4===l.rank||1===l.rank,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),null!=c&&i(4===c.rank||1===c.rank,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${c.rank}.`),null!=d&&i(4===d.rank||1===d.rank,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${d.rank}.`),Ro(o,u,l,d,c,s)}});const Fo=/* @__PURE__ */Aa({bincount_:function(e,t,n){const r=Ea(e,"x","bincount"),a=Ea(t,"weights","bincount");i("int32"===r.dtype,()=>`Error in bincount: input dtype must be int32, but got ${r.dtype}`),i(n>=0,()=>`size must be non-negative, but got ${n}.`),i(a.size===r.size||0===a.size,()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${r.shape}, weights shape: ${a.shape}.`);const s={x:r,weights:a},o={size:n};return wa.runKernel(de,s,o)}});const Do=/* @__PURE__ */Aa({bitwiseAnd_:function(e,t){const n=Ea(e,"x","bitwiseAnd"),r=Ea(t,"y","bitwiseAnd");if(!d(n.shape,r.shape))throw new Error(`BitwiseAnd: Tensors must have the same shape. x: ${n.shape}, y: ${r.shape}`);if("int32"!==n.dtype||"int32"!==r.dtype)throw new Error(`BitwiseAnd: Only supports 'int32' values in tensor, found type of x: ${n.dtype} and type of y: ${r.dtype}`);const a={a:n,b:r};return wa.runKernel(pe,a)}});const Mo=/* @__PURE__ */Aa({broadcastArgs_:function(e,t){const n=Ea(e,"s0","broadcastArgs","int32"),r=Ea(t,"s1","broadcastArgs","int32");if(1!==n.rank)throw new Error(`broadcastArgs(): first input must be a vector (rank=1). Has rank ${n.rank}`);if(1!==r.rank)throw new Error(`broadcastArgs(): second input must be a vector (rank=1). Has rank ${r.rank}`);const a={s0:n,s1:r};return wa.runKernel(he,a)}});const Po=/* @__PURE__ */Aa({broadcastTo_:function(e,t){let n=Ea(e,"broadcastTo","x");const r=n.shape;if(O(t),t.lengthn.rank){const e=n.shape.slice();for(;e.length=0;u--)if(a[u]===t[u])s[u]=1;else if(1!==n.shape[u])throw new Error(`broadcastTo(): [${r}] cannot be broadcast to [${t}].`);if(0===s.map((e,t)=>e>1?t:-1).filter(e=>e>=0).length)return Bs(n);const o={x:n},i={reps:s};return wa.runKernel(Un,o,i)}});const Lo=/* @__PURE__ */Aa({ceil_:function(e){const t={x:Ea(e,"x","ceil","float32")};return wa.runKernel(me,t)}});function Bo(e,t,n){O(e);const r={shape:e,value:t,dtype:n=n||N(t)};return wa.runKernel(Qe,{},r)}const Vo=/* @__PURE__ */Aa({clipByValue_:function(e,t,n){const r=Ea(e,"x","clipByValue");if(i(t<=n,()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`),t===n)return Bo(r.shape,t,r.dtype);const a={x:r},s={clipValueMin:t,clipValueMax:n};return wa.runKernel(ge,a,s)}});const Wo=/* @__PURE__ */Aa({concat1d_:function(e){return Io(e,0)}});const zo=/* @__PURE__ */Aa({concat2d_:function(e,t){return Io(e,t)}});const Uo=/* @__PURE__ */Aa({concat3d_:function(e,t){return Io(e,t)}});const Go=/* @__PURE__ */Aa({concat4d_:function(e,t){return Io(e,t)}});const Ho=/* @__PURE__ */Aa({conv2d_:function(e,t,n,r,a="NHWC",s=[1,1],o){const u=Ea(e,"x","conv2d","float32"),l=Ea(t,"filter","conv2d","float32");let c=u,d=!1;3===u.rank&&(d=!0,c=vo(u,[1,u.shape[0],u.shape[1],u.shape[2]])),i(4===c.rank,()=>`Error in conv2d: input must be rank 4, but got rank ${c.rank}.`),i(4===l.rank,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),xo("conv2d",r,o);const p="NHWC"===a?c.shape[3]:c.shape[1];i(p===l.shape[2],()=>`Error in conv2d: depth of input (${p}) must match input depth for filter ${l.shape[2]}.`),i(go(n,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`),i(yo(s),()=>"Error in conv2D: Dilated rates should be larger than 0."),i(yo(n),()=>"Error in conv2D: Strides should be larger than 0.");const h={x:c,filter:l},f={strides:n,pad:r,dataFormat:a,dilations:s,dimRoundingMode:o},m=wa.runKernel(ve,h,f);return d?vo(m,[m.shape[1],m.shape[2],m.shape[3]]):m}});const jo=/* @__PURE__ */Aa({conv1d_:function(e,t,n,r,a="NWC",s=1,o){const u=Ea(e,"x","conv1d"),l=Ea(t,"filter","conv1d");let c=u,d=!1;2===u.rank&&(d=!0,c=vo(u,[1,u.shape[0],u.shape[1]])),i(3===c.rank,()=>`Error in conv1d: input must be rank 3, but got rank ${c.rank}.`),i(3===l.rank,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),xo("conv1d",r,o),i(c.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${c.shape[2]}) must match input depth for filter ${l.shape[1]}.`),i(go(n,s),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${s}'`),i(yo(s),()=>"Error in conv1D: Dilated rates should be larger than 0."),i(yo(n),()=>"Error in conv1D: Stride should be larger than 0."),i("NWC"===a,()=>`Error in conv1d: got dataFormat of ${a} but only NWC is currently supported.`);const p=vo(l,[1,l.shape[0],l.shape[1],l.shape[2]]),h=vo(c,[c.shape[0],1,c.shape[1],c.shape[2]]),f=Ho(h,p,[1,n],r,"NHWC",[1,s],o);return vo(f,d?[f.shape[2],f.shape[3]]:[f.shape[0],f.shape[2],f.shape[3]])}});const qo=/* @__PURE__ */Aa({conv2DBackpropInput_:function(e,t,n,r,a,s="NHWC",o){i(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let u=e,l=t,c=!1;3===t.rank&&(c=!0,l=vo(t,[1,t.shape[0],t.shape[1],t.shape[2]]),u=[1,e[0],e[1],e[2]]),i(4===u.length,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${u.length}.`),i(4===l.rank,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),i(4===n.rank,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`);const d="NHWC"===s?u[3]:u[1],p="NHWC"===s?l.shape[3]:l.shape[1];i(d===n.shape[2],()=>`Error in conv2dDerInput: depth of input (${d}) must match input depth for filter ${n.shape[2]}.`),i(p===n.shape[3],()=>`Error in conv2dDerInput: depth of output (${p}) must match output depth for filter ${n.shape[3]}.`),xo("conv2dDerInput",a,o);const h={dy:l,filter:n},f={strides:r,pad:a,dataFormat:s,dimRoundingMode:o,inputShape:u},m=wa.runKernel(ke,h,f);return c?vo(m,[m.shape[1],m.shape[2],m.shape[3]]):m}});const Ko=/* @__PURE__ */Aa({conv2dTranspose_:function(e,t,n,r,a,s){const o=Ea(e,"x","conv2dTranspose"),i=Ea(t,"filter","conv2dTranspose");return qo(n,o,i,r,a,"NHWC",s)}});const Xo=/* @__PURE__ */Aa({conv3d_:function(e,t,n,r,a="NDHWC",s=[1,1,1]){const o=Ea(e,"x","conv3d"),u=Ea(t,"filter","conv3d");let l=o,c=!1;4===o.rank&&(c=!0,l=vo(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),i(5===l.rank,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),i(5===u.rank,()=>`Error in conv3d: filter must be rank 5, but got rank ${u.rank}.`),i(l.shape[4]===u.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${u.shape[3]}.`),i(go(n,s),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`),i("NDHWC"===a,()=>`Error in conv3d: got dataFormat of ${a} but only NDHWC is currently supported.`),i(yo(s),()=>"Error in conv3D: Dilated rates should be larger than 0."),i(yo(n),()=>"Error in conv3D: Strides should be larger than 0.");const d={x:l,filter:u},p={strides:n,pad:r,dataFormat:a,dilations:s},h=wa.runKernel(Ie,d,p);return c?vo(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}});const Yo=/* @__PURE__ */Aa({conv3DBackpropInput_:function(e,t,n,r,a){i(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let s=e,o=t,u=!1;4===t.rank&&(u=!0,o=vo(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),s=[1,e[0],e[1],e[2],e[3]]);const l=s[4],c=o.shape[4];i(5===s.length,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${s.length}.`),i(5===o.rank,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${o.rank}`),i(5===n.rank,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`),i(l===n.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${n.shape[3]}.`),i(c===n.shape[4],()=>`Error in conv3dDerInput: depth of output (${c}) must match output depth for filter ${n.shape[4]}.`);const d={dy:o,filter:n},p={pad:a,strides:r,inputShape:s},h=wa.runKernel(Se,d,p);return u?vo(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}});const Qo=/* @__PURE__ */Aa({conv3dTranspose_:function(e,t,n,r,a){const s=Ea(e,"x","conv3dTranspose"),o=Ea(t,"filter","conv3dTranspose");return Yo(n,s,o,r,a)}});const Zo=/* @__PURE__ */Aa({cos_:function(e){const t={x:Ea(e,"x","cos","float32")};return wa.runKernel(Te,t)}});const Jo=/* @__PURE__ */Aa({cosh_:function(e){const t={x:Ea(e,"x","cosh","float32")};return wa.runKernel(Ce,t)}});const ei=/* @__PURE__ */Aa({cumprod_:function(e,t=0,n=!1,r=!1){const a={x:Ea(e,"x","cumprod")},s={axis:t,exclusive:n,reverse:r};return wa.runKernel($e,a,s)}});const ti=/* @__PURE__ */Aa({cumsum_:function(e,t=0,n=!1,r=!1){const a={x:Ea(e,"x","cumsum")},s={axis:t,exclusive:n,reverse:r};return wa.runKernel(Ee,a,s)}});const ni=/* @__PURE__ */Aa({denseBincount_:function(e,t,n,r=!1){const a=Ea(e,"x","denseBincount"),s=Ea(t,"weights","denseBincount");i("int32"===a.dtype,()=>`Error in denseBincount: input dtype must be int32, but got ${a.dtype}`),i(a.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${a.rank}.`),i(n>=0,()=>`size must be non-negative, but got ${n}.`),i(s.size===a.size||0===s.size,()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${a.shape}, weights shape: ${s.shape}.`);const o={x:a,weights:s},u={size:n,binaryOutput:r};return wa.runKernel(_e,o,u)}});const ri=/* @__PURE__ */Aa({depthToSpace_:function(e,t,n="NHWC"){const r=Ea(e,"x","depthToSpace","float32"),a="NHWC"===n?r.shape[1]:r.shape[2],s="NHWC"===n?r.shape[2]:r.shape[3],o="NHWC"===n?r.shape[3]:r.shape[1];i(t>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`),i(a*t>=0,()=>`Negative dimension size caused by overflow when multiplying\n ${a} and ${t} for depthToSpace with input shape\n ${r.shape}`),i(s*t>=0,()=>`Negative dimension size caused by overflow when multiplying\n ${s} and ${t} for depthToSpace with input shape\n ${r.shape}`),i(o%(t*t)===0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${o} for depthToSpace with input shape ${r.shape}`);const u={x:r},l={blockSize:t,dataFormat:n};return wa.runKernel(Ae,u,l)}});const ai=/* @__PURE__ */Aa({depthwiseConv2d_:function(e,t,n,r,a="NHWC",s=[1,1],o){const u=Ea(e,"x","depthwiseConv2d","float32"),l=Ea(t,"filter","depthwiseConv2d","float32");let c=u,d=!1;3===u.rank&&(d=!0,c=vo(u,[1,u.shape[0],u.shape[1],u.shape[2]])),i(4===c.rank,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${c.rank}.`),i(4===l.rank,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`);const p="NHWC"===a?c.shape[3]:c.shape[1];i(p===l.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${p}) must match the inChannels dimension in filter ${l.shape[2]}.`),xo("depthwiseConv2d",r,o);const h={x:c,filter:l},f={strides:n,pad:r,dataFormat:a,dilations:s,dimRoundingMode:o},m=wa.runKernel(Oe,h,f);return d?vo(m,[m.shape[1],m.shape[2],m.shape[3]]):m}});const si=/* @__PURE__ */Aa({diag_:function(e){const t={x:Ea(e,"x","diag")};return wa.runKernel(Me,t)}});const oi=/* @__PURE__ */Aa({dilation2d_:function(e,t,n,r,a=[1,1],s="NHWC"){const o=Ea(e,"x","dilation2d"),u=Ea(t,"filter","dilation2d");i(3===o.rank||4===o.rank,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${o.rank}.`),i(3===u.rank,()=>`Error in dilation2d: filter must be rank 3, but got rank ${u.rank}.`),i("NHWC"===s,()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${s}`);let l=o,c=!1;3===o.rank&&(l=vo(o,[1,o.shape[0],o.shape[1],o.shape[2]]),c=!0),i(l.shape[3]===u.shape[2],()=>`Error in dilation2d: input and filter must have the same depth: ${l.shape[3]} vs ${u.shape[2]}`);const d={x:l,filter:u},p={strides:n,pad:r,dilations:a},h=wa.runKernel(Pe,d,p);return c?vo(h,[h.shape[1],h.shape[2],h.shape[3]]):h}});function ii(e,t){const n=e.length,r=[];for(let a=0;a1&&1===o&&r.unshift(s)}return r}function ui(e,t){const n=[];for(let r=0;r1)&&n.unshift(s)}return n}function li(e,t){const n=Math.max(e.length,t.length),r=new Array(n);for(let a=0;a`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${r.rank}.`);const a=1===n.rank?n.size:n.shape[1],s=1===r.rank?r.size:r.shape[0];if(i(a===s,()=>`Error in dot: inner dimensions of inputs must match, but got ${a} and ${s}.`),1===n.rank&&1===r.rank){const e=vo(n,[1,-1]),t=vo(r,[-1,1]),a=No(e,t);return vo(a,[])}if(1===n.rank&&2===r.rank){const e=vo(n,[1,-1]),t=vo(r,[r.shape[0],r.shape[1]]),a=No(e,t);return vo(a,[a.size])}if(2===n.rank&&1===r.rank){const e=vo(r,[-1,1]),t=No(n,e);return vo(t,[t.size])}{const e=vo(r,[r.shape[0],r.shape[1]]);return No(n,e)}}});const mi=/* @__PURE__ */Aa({einsum_:function(e,...t){const n=t.map((e,t)=>Ea(e,`tensors${t}`,"einsum")),r={equation:e};return wa.runKernel(ze,n,r)}});const gi=/* @__PURE__ */Aa({elu_:function(e){const t={x:Ea(e,"x","elu","float32")};return wa.runKernel(Ue,t)}});const yi=/* @__PURE__ */Aa({ensureShape_:function(e,t){const n=Ea(e,"x","ensureShape","string_or_numeric");if(!function(e,t){if(e===t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;for(let n=0;n"Input dtype must be `int32` or `float32`."),"int32"===t.dtype&&(t=Ls(t,"float32"));const n={x:t};return wa.runKernel(He,n)}});function xi(e,t){for(let n=0;ne[t])]}function ki(e,t){return vi(e,t.map(e=>1),t)}function Ii(e,t,n){i(xi(t,n),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`)}function Ni(e,t){if(xi(e,t))return null;const n=[];for(let r=0;rn.push(e)),n}function Si(e){return e.map((e,t)=>[t,e]).sort((e,t)=>e[1]-t[1]).map(e=>e[0])}function Ti(e,t){const n=[];for(let r=t-e;r"Axis must be <= rank of the tensor");const r={input:n},a={dim:t};return wa.runKernel(Ke,r,a)}});const Bi=/* @__PURE__ */Aa({expm1_:function(e){const t={x:Ea(e,"x","expm1")};return wa.runKernel(Xe,t)}});const Vi=/* @__PURE__ */Aa({tile_:function(e,t){const n=Ea(e,"x","tile","string_or_numeric");i(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`);const r={x:n},a={reps:t};return wa.runKernel(Un,r,a)}});const Wi=/* @__PURE__ */Aa({eye_:function(e,t,n,r="float32"){null==t&&(t=e);const a=Ps([e,t],r),s=e<=t?e:t;for(let i=0;i`Error in localResponseNormalization: x must be rank 3 or 4 but got\n rank ${s.rank}.`),i(p(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let o=s,u=!1;3===s.rank&&(u=!0,o=vo(s,[1,s.shape[0],s.shape[1],s.shape[2]]));const l={x:o},c={depthRadius:t,bias:n,alpha:r,beta:a},d=wa.runKernel(wt,l,c);return u?vo(d,[d.shape[1],d.shape[2],d.shape[3]]):d}});const tu=/* @__PURE__ */Aa({log_:function(e){const t={x:Ea(e,"x","log","float32")};return wa.runKernel(gt,t)}});const nu=/* @__PURE__ */Aa({log1p_:function(e){const t={x:Ea(e,"x","log1p")};return wa.runKernel(yt,t)}});function ru(e,t){i(S(e),()=>"The f passed in variableGrads(f) must be a function"),i(null==t||Array.isArray(t)&&t.every(e=>e instanceof Zr),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");const n=null!=t;if(!n){t=[];for(const e in wa.registeredVariables)t.push(wa.registeredVariables[e])}const r=n?t.filter(e=>!e.trainable):null,a=t.length;i((t=t.filter(e=>e.trainable)).length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${a} variables is trainable.`);const{value:s,grads:o}=wa.gradients(e,t,null,!0);i(o.some(e=>null!=e),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),i(0===s.rank,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${s.rank} tensor`);const u={};return t.forEach((e,t)=>{null!=o[t]&&(u[e.name]=o[t])}),null!=r&&r.forEach(e=>u[e.name]=null),{value:s,grads:u}}function au(e){return wa.customGrad(e)}const su=/* @__PURE__ */Aa({neg_:function(e){const t={x:Ea(e,"x","neg")};return wa.runKernel(Pt,t)}});const ou=/* @__PURE__ */Aa({softplus_:function(e){const t={x:Ea(e,"x","softplus")};return wa.runKernel(kn,t)}});const iu=/* @__PURE__ */Aa({logSigmoid_:function(e){const t=Ea(e,"x","logSigmoid");return au(e=>({value:su(ou(su(e))),gradFunc:t=>Gs(t,So(su(e)))}))(t)}});const uu=/* @__PURE__ */Aa({sub_:function(e,t){let n=Ea(e,"a","sub"),r=Ea(t,"b","sub");[n,r]=fa(n,r);const a={a:n,b:r};return wa.runKernel(Vn,a)}});const lu=/* @__PURE__ */Aa({logSoftmax_:function(e,t=-1){const n=Ea(e,"logits","logSoftmax");if(-1===t&&(t=n.rank-1),t!==n.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and axis was ${t}`);return au((e,n)=>{const r=Ci(e,t,!0),a=uu(e,r),s=uu(Ls(a,"float32"),tu(Oi(Pi(a),t,!0)));n([s]);return{value:s,gradFunc:(e,n)=>{const[r]=n,a=Pi(r);return uu(e,Gs(Oi(e,t,!0),a))}}})(n)}});const cu=/* @__PURE__ */Aa({logSumExp_:function(e,t=null,n=!1){const r=Ea(e,"x","logSumExp"),a=y(t,r.shape),s=Ci(r,a,!0),o=uu(r,s),i=Pi(o),u=Oi(i,a),l=tu(u),c=Ws(vo(s,l.shape),l);if(n){const e=ki(c.shape,a);return vo(c,e)}return c}});const du=/* @__PURE__ */Aa({logicalAnd_:function(e,t){const n=Ea(e,"a","logicalAnd","bool"),r=Ea(t,"b","logicalAnd","bool");li(n.shape,r.shape);const a={a:n,b:r};return wa.runKernel(bt,a)}});const pu=/* @__PURE__ */Aa({logicalNot_:function(e){const t={x:Ea(e,"x","logicalNot","bool")};return wa.runKernel(xt,t)}});const hu=/* @__PURE__ */Aa({logicalOr_:function(e,t){const n=Ea(e,"a","logicalOr","bool"),r=Ea(t,"b","logicalOr","bool");li(n.shape,r.shape);const a={a:n,b:r};return wa.runKernel(vt,a)}});const fu=/* @__PURE__ */Aa({logicalXor_:function(e,t){const n=Ea(e,"a","logicalXor","bool"),r=Ea(t,"b","logicalXor","bool");return li(n.shape,r.shape),du(hu(e,t),pu(du(e,t)))}}),mu=2147483648;const gu=/* @__PURE__ */Aa({searchSorted_:function(e,t,n="left"){const r=Ea(e,"sortedSequence","searchSorted"),a=Ea(t,"values","searchSorted"),s=r.shape[r.shape.length-1],o=a.shape[a.shape.length-1],i=vo(r,[-1,s]),u=vo(a,[-1,o]);if(i.rank<2)throw new Error("Sorted input argument must be at least 2-dimensional");if(i.shape[0]!==u.shape[0])throw new Error("Leading dimension of 'sortedSequence' and 'values' must match.");if(c(u.shape)>=mu)throw new Error("values tensor size must less than 2147483648");if(i.shape[1]>=mu)throw new Error(`trailing dim_size must less than 2147483648 for int32 output type, was ${i.shape[1]}`);const l={sortedSequence:i,values:u},d={side:n};return wa.runKernel(fn,l,d)}});function yu(e,t){return gu(e,t,"left")}const bu=/* @__PURE__ */Aa({maxPool_:function(e,t,n,r,a){const s=Ea(e,"x","maxPool");let o=s,u=!1;3===s.rank&&(u=!0,o=vo(s,[1,s.shape[0],s.shape[1],s.shape[2]])),i(4===o.rank,()=>`Error in maxPool: input must be rank 4 but got rank ${o.rank}.`),i(go(n,1),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`),xo("maxPool",r,a);const l={x:o},c={filterSize:t,strides:n,pad:r,dimRoundingMode:a},d=wa.runKernel(St,l,c);return u?vo(d,[d.shape[1],d.shape[2],d.shape[3]]):d}});const xu=/* @__PURE__ */Aa({maxPool3d_:function(e,t=[1,1,1],n,r,a,s="NDHWC"){const o=Ea(e,"x","maxPool3d");let u=o,l=!1;4===o.rank&&(l=!0,u=vo(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),i(5===u.rank,()=>`Error in maxPool3d: x must be rank 5 but got rank ${u.rank}.`),i("NDHWC"===s,()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),xo("maxPool3d",r,a);const c={x:u},d={filterSize:t,strides:n,pad:r,dimRoundingMode:a,dataFormat:s},p=wa.runKernel(Ct,c,d);return l?vo(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}});const vu=/* @__PURE__ */Aa({maxPoolWithArgmax_:function(e,t,n,r,a=!1){const s={x:Ea(e,"x","maxPoolWithArgmax")},o={filterSize:t,strides:n,pad:r,includeBatchInIndex:a},i=wa.runKernel(Et,s,o);return{result:i[0],indexes:i[1]}}});const wu=/* @__PURE__ */Aa({maximum_:function(e,t){let n=Ea(e,"a","maximum"),r=Ea(t,"b","maximum");[n,r]=fa(n,r),"bool"===n.dtype&&(n=Ls(n,"int32"),r=Ls(r,"int32")),li(n.shape,r.shape);const a={a:n,b:r};return wa.runKernel(Nt,a)}});const ku=/* @__PURE__ */Aa({mean_:function(e,t=null,n=!1){const r={x:Ea(e,"x","mean")},a={axis:t,keepDims:n};return wa.runKernel(Rt,r,a)}});function Iu(e,t="float32"){if(O(e),"complex64"===t){const t=Iu(e,"float32"),n=Iu(e,"float32");return Oa(t,n)}const n=_(c(e),t);return wa.makeTensor(n,e,t)}function Nu(e,t="float32"){if(O(e),"complex64"===t){const t=Nu(e,"float32"),n=Iu(e,"float32");return Oa(t,n)}const n=R(c(e),t);return wa.makeTensor(n,e,t)}function Su(e,t,{indexing:n="xy"}={}){if("xy"!==n&&"ij"!==n)throw new TypeError(`${n} is not a valid third argument to meshgrid`);if(void 0===e)return[];let r=Ea(e,"x","meshgrid",e instanceof Yr?e.dtype:"float32");if(void 0===t)return[r];let a=Ea(t,"y","meshgrid",t instanceof Yr?t.dtype:"float32");const s=c(r.shape),o=c(a.shape);return"xy"===n?(r=vo(r,[1,-1]),a=vo(a,[-1,1]),[No(Nu([o,1],r.dtype),r),No(a,Nu([1,s],a.dtype))]):(r=vo(r,[-1,1]),a=vo(a,[1,-1]),[No(r,Nu([1,o],r.dtype)),No(Nu([s,1],a.dtype),a)])}const Tu=/* @__PURE__ */Aa({minimum_:function(e,t){let n=Ea(e,"a","minimum"),r=Ea(t,"b","minimum");[n,r]=fa(n,r),"bool"===n.dtype&&(n=Ls(n,"int32"),r=Ls(r,"int32")),li(n.shape,r.shape);const a={a:n,b:r};return wa.runKernel(At,a)}});const Cu=/* @__PURE__ */Aa({mirrorPad_:function(e,t,n){i("reflect"===n||"symmetric"===n,()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`);const r=Ea(e,"x","mirrorPad");if(0===r.rank)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");i(t.length===r.rank,()=>`Padding doesn't match input. Must be ${r.rank}. Got ${t.length}.`);const a="reflect"===n?1:0;for(let u=0;u"Invalid number of paddings. Must be length of 2 each."),i(t[u][0]>=0&&t[u][0]<=r.shape[u]-a&&t[u][1]>=0&&t[u][1]<=r.shape[u]-a,()=>`Padding in dimension ${u} cannot be greater than or equal to ${r.shape[u]-a} or less than 0 for input of shape ${r.shape}`);const s={paddings:t,mode:n},o={x:r};return wa.runKernel(Ot,o,s)}});const $u=/* @__PURE__ */Aa({mod_:function(e,t){let n=Ea(e,"a","mod"),r=Ea(t,"b","mod");[n,r]=fa(n,r);const a={a:n,b:r};return wa.runKernel(Ft,a)}});const Eu=/* @__PURE__ */Aa({moments_:function(e,t=null,n=!1){const r=y(t,(e=Ea(e,"x","moments")).shape),a=ku(e,r,n);let s=a.shape;n||(s=ki(a.shape,r));const o=Ai(uu(Ls(e,"float32"),vo(a,s)));return{mean:a,variance:ku(o,r,n)}}});const Ru=/* @__PURE__ */Aa({multiRNNCell_:function(e,t,n,r){const a=Ea(t,"data","multiRNNCell"),s=Ra(n,"c","multiRNNCell"),o=Ra(r,"h","multiRNNCell");let i=a;const u=[];for(let d=0;d2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${o}`);n=n||Math.random();const i={logits:1===o?vo(a,[1,-1]):a},u={numSamples:t,seed:n,normalized:r},l=wa.runKernel(Dt,i,u);return 1===o?vo(l,[l.size]):l}});const Au=/* @__PURE__ */Aa({notEqual_:function(e,t){let n=Ea(e,"a","notEqual","string_or_numeric"),r=Ea(t,"b","notEqual","string_or_numeric");[n,r]=fa(n,r),li(n.shape,r.shape);const a={a:n,b:r};return wa.runKernel(Lt,a)}});const Ou=/* @__PURE__ */Aa({oneHot_:function(e,t,n=1,r=0,a="int32"){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);const s={indices:Ea(e,"indices","oneHot","int32")},o={dtype:a,depth:t,onValue:n,offValue:r};return wa.runKernel(Ut,s,o)}});const Fu=/* @__PURE__ */Aa({onesLike_:function(e){const t={x:Ea(e,"x","onesLike")};return wa.runKernel(zt,t)}});const Du=/* @__PURE__ */Aa({outerProduct_:function(e,t){const n=Ea(e,"v1","outerProduct"),r=Ea(t,"v2","outerProduct");i(1===n.rank&&1===r.rank,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${r.rank}.`);const a=vo(n,[-1,1]),s=vo(r,[1,-1]);return No(a,s)}});const Mu=/* @__PURE__ */Aa({pad_:function(e,t,n=0){const r=Ea(e,"x","pad");if(0===r.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");const a={paddings:t,constantValue:n},s={x:r};return wa.runKernel(Ht,s,a)}});const Pu=/* @__PURE__ */Aa({pad1d_:function(e,t,n=0){return i(2===t.length,()=>"Invalid number of paddings. Must be length of 2."),Mu(e,[t],n)}});const Lu=/* @__PURE__ */Aa({pad2d_:function(e,t,n=0){return i(2===t.length&&2===t[0].length&&2===t[1].length,()=>"Invalid number of paddings. Must be length of 2 each."),Mu(e,t,n)}});const Bu=/* @__PURE__ */Aa({pad3d_:function(e,t,n=0){return i(3===t.length&&2===t[0].length&&2===t[1].length&&2===t[2].length,()=>"Invalid number of paddings. Must be length of 2 each."),Mu(e,t,n)}});const Vu=/* @__PURE__ */Aa({pad4d_:function(e,t,n=0){return i(4===t.length&&2===t[0].length&&2===t[1].length&&2===t[2].length&&2===t[3].length,()=>"Invalid number of paddings. Must be length of 2 each."),Mu(e,t,n)}});const Wu=/* @__PURE__ */Aa({spaceToBatchND_:function(e,t,n){const r=Ea(e,"x","spaceToBatchND");i(r.rank>=1+t.length,()=>`input rank ${r.rank} should be > than [blockShape] ${t.length}`),i(n.length===t.length,()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`),i(r.shape.reduce((e,r,a)=>a>0&&a<=t.length?e&&(r+n[a-1][0]+n[a-1][1])%t[a-1]===0:e,!0),()=>`input spatial dimensions ${r.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`);const a={x:r},s={blockShape:t,paddings:n};return wa.runKernel(Sn,a,s)}});const zu=/* @__PURE__ */Aa({pool_:function(e,t,n,r,a,s,o){null==a&&(a=[1,1]),null==s&&(s=1),0===r&&(r="valid");const u=Ea(e,"x","maxPool");let l=u,c=!1;3===u.rank&&(c=!0,l=vo(u,[1,u.shape[0],u.shape[1],u.shape[2]])),i(go(s,a),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${s} and dilations '${a}'`);const d=so(l.shape,t,s,a,r),p=[d.dilationHeight,d.dilationWidth];let h;h="same"===r?function(e,t){const n=e.map((e,n)=>e+(e-1)*(t[n]-1)),r=n.map(e=>e-1),a=r.map(e=>Math.floor(e/2)),s=r.map((e,t)=>e-a[t]);return r.map((e,t)=>[a[t],s[t]])}([d.filterHeight,d.filterWidth],p):[[0,0],[0,0]];const f=1===p[0]&&1===p[1],[m,g]=function(e,t,n){const r=n.map(e=>e[0]),a=n.map(e=>e[1]),s=e.concat(r,a),o=t.map((e,t)=>(e-s[t]%e)%e),i=a.map((e,t)=>e+o[t]),u=t.map((e,t)=>[r[t],i[t]]),l=t.map((e,t)=>[0,o[t]]);return[u,l]}([d.inHeight,d.inWidth],p,h),y=f?r:"valid",b=f?l:Wu(l,p,m),x=("avg"===n?()=>wo(b,t,s,y,o):()=>bu(b,t,s,y,o))(),v=f?x:Eo(x,p,g);return c?vo(v,[v.shape[1],v.shape[2],v.shape[3]]):v}});const Uu=/* @__PURE__ */Aa({prelu_:function(e,t){const n={x:Ea(e,"x","prelu"),alpha:Ea(t,"alpha","prelu")};return wa.runKernel(qt,n)}});const Gu=/* @__PURE__ */Aa({prod_:function(e,t=null,n=!1){let r=Ea(e,"x","prod");"bool"===r.dtype&&(r=Ls(r,"int32"));const a={x:r},s={axis:t,keepDims:n};return wa.runKernel(Kt,a,s)}});const Hu=/* @__PURE__ */Aa({raggedGather_:function(e,t,n,r){const a={paramsNestedSplits:e.map((e,t)=>Ea(e,`tensors${t}`,"raggedGather","int32")),paramsDenseValues:Ea(t,"paramsDenseValues","raggedGather"),indices:Ea(n,"indices","raggedGather","int32")},s={outputRaggedRank:r},o=wa.runKernel(Xt,a,s);return{outputNestedSplits:o.slice(0,o.length-1),outputDenseValues:o[o.length-1]}}});const ju=/* @__PURE__ */Aa({raggedRange_:function(e,t,n){const r=Ea(e,"starts","raggedRange"),a={starts:r,limits:Ea(t,"limits","raggedRange",r.dtype),deltas:Ea(n,"deltas","raggedRange",r.dtype)},s=wa.runKernel(Yt,a);return{rtNestedSplits:s[0],rtDenseValues:s[1]}}});const qu=/* @__PURE__ */Aa({raggedTensorToTensor_:function(e,t,n,r,a){const s=Ea(e,"shape","raggedTensorToTensor","int32"),o=Ea(t,"values","raggedTensorToTensor"),i={shape:s,values:o,defaultValue:Ea(n,"defaultValue","raggedTensorToTensor",o.dtype),rowPartitionTensors:r.map((e,t)=>Ea(e,`tensors${t}`,"raggedTensorToTensor","int32"))},u={rowPartitionTypes:a};return wa.runKernel(Qt,i,u)}});const Ku=/* @__PURE__ */Aa({rand_:function(e,t,n){O(e);const r=c(e);let a=null;if(null==n||"float32"===n)a=new Float32Array(r);else if("int32"===n)a=new Int32Array(r);else{if("bool"!==n)throw new Error(`Unknown data type ${n}`);a=new Uint8Array(r)}for(let s=0;s>>0,e=(r*=e)>>>0,e+=4294967296*(r-=e)}return 2.3283064365386963e-10*(e>>>0)};return t}();t.next=function(){var e=2091639*t.s0+2.3283064365386963e-10*t.c;return t.s0=t.s1,t.s1=t.s2,t.s2=e-(t.c=0|e)},t.c=1,t.s0=n(" "),t.s1=n(" "),t.s2=n(" "),t.s0-=n(e),t.s0<0&&(t.s0+=1),t.s1-=n(e),t.s1<0&&(t.s1+=1),t.s2-=n(e),t.s2<0&&(t.s2+=1),n=null}function r(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function a(e,t){var a=new n(e),s=t&&t.state,o=a.next;return o.int32=function(){return 4294967296*a.next()|0},o.double=function(){return o()+11102230246251565e-32*(2097152*o()|0)},o.quick=o,s&&("object"==typeof s&&r(s,a),o.state=function(){return r(a,{})}),o}t&&t.exports?t.exports=a:this.alea=a}(0,Yu)),Yu.exports}var Zu,Ju={exports:{}};var el,tl={exports:{}};var nl,rl={exports:{}};var al,sl={exports:{}};var ol,il={exports:{}};var ul={exports:{}};const ll=/* @__PURE__ */gr(/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));var cl,dl,pl,hl=ul.exports;function fl(){return cl||(cl=1,e=ul,function(t,n,r){var a,s=256,o="random",i=r.pow(s,6),u=r.pow(2,52),l=2*u,c=255;function d(e,c,d){var y=[],b=m(f((c=1==c?{entropy:!0}:c||{}).entropy?[e,g(n)]:e??function(){try{var e;return a&&(e=a.randomBytes)?e=e(s):(e=new Uint8Array(s),(t.crypto||t.msCrypto).getRandomValues(e)),g(e)}catch(i){var r=t.navigator,o=r&&r.plugins;return[+/* @__PURE__ */new Date,t,o,t.screen,g(n)]}}(),3),y),x=new p(y),v=function(){for(var e=x.g(6),t=i,n=0;e=l;)e/=2,t/=2,n>>>=1;return(e+n)/t};return v.int32=function(){return 0|x.g(4)},v.quick=function(){return x.g(4)/4294967296},v.double=v,m(g(x.S),n),(c.pass||d||function(e,t,n,a){return a&&(a.S&&h(a,x),e.state=function(){return h(x,{})}),n?(r[o]=e,t):e})(v,b,"global"in c?c.global:this==r,c.state)}function p(e){var t,n=e.length,r=this,a=0,o=r.i=r.j=0,i=r.S=[];for(n||(e=[n++]);a>>19^e^e>>>8},e===(0|e)?t.x=e:n+=e;for(var r=0;r>>0)/4294967296};return o.double=function(){do{var e=((a.next()>>>11)+(a.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=a.next,o.quick=o,s&&("object"==typeof s&&r(s,a),o.state=function(){return r(a,{})}),o}t&&t.exports?t.exports=a:this.xor128=a}(0,Ju)),Ju.exports),n=(el||(el=1,function(e,t){function n(e){var t=this,n="";t.next=function(){var e=t.x^t.x>>>2;return t.x=t.y,t.y=t.z,t.z=t.w,t.w=t.v,(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^e^e<<1)|0},t.x=0,t.y=0,t.z=0,t.w=0,t.v=0,e===(0|e)?t.x=e:n+=e;for(var r=0;r>>4),t.next()}function r(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t.v=e.v,t.d=e.d,t}function a(e,t){var a=new n(e),s=t&&t.state,o=function(){return(a.next()>>>0)/4294967296};return o.double=function(){do{var e=((a.next()>>>11)+(a.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=a.next,o.quick=o,s&&("object"==typeof s&&r(s,a),o.state=function(){return r(a,{})}),o}t&&t.exports?t.exports=a:this.xorwow=a}(0,tl)),tl.exports),r=(nl||(nl=1,function(e,t){function n(e){var t=this;t.next=function(){var e,n,r=t.x,a=t.i;return e=r[a],n=(e^=e>>>7)^e<<24,n^=(e=r[a+1&7])^e>>>10,n^=(e=r[a+3&7])^e>>>3,n^=(e=r[a+4&7])^e<<7,e=r[a+7&7],n^=(e^=e<<13)^e<<9,r[a]=n,t.i=a+1&7,n},function(e,t){var n,r=[];if(t===(0|t))r[0]=t;else for(t=""+t,n=0;n0;--n)e.next()}(t,e)}function r(e,t){return t.x=e.x.slice(),t.i=e.i,t}function a(e,t){null==e&&(e=+/* @__PURE__ */new Date);var a=new n(e),s=t&&t.state,o=function(){return(a.next()>>>0)/4294967296};return o.double=function(){do{var e=((a.next()>>>11)+(a.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=a.next,o.quick=o,s&&(s.x&&r(s,a),o.state=function(){return r(a,{})}),o}t&&t.exports?t.exports=a:this.xorshift7=a}(0,rl)),rl.exports),a=(al||(al=1,function(e,t){function n(e){var t=this;t.next=function(){var e,n,r=t.w,a=t.X,s=t.i;return t.w=r=r+1640531527|0,n=a[s+34&127],e=a[s=s+1&127],n^=n<<13,e^=e<<17,n^=n>>>15,e^=e>>>12,n=a[s]=n^e,t.i=s,n+(r^r>>>16)|0},function(e,t){var n,r,a,s,o,i=[],u=128;for(t===(0|t)?(r=t,t=null):(t+="\0",r=0,u=Math.max(u,t.length)),a=0,s=-32;s>>15,r^=r<<4,r^=r>>>13,s>=0&&(o=o+1640531527|0,a=0==(n=i[127&s]^=r+o)?a+1:0);for(a>=128&&(i[127&(t&&t.length||0)]=-1),a=127,s=512;s>0;--s)r=i[a+34&127],n=i[a=a+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,i[a]=r^n;e.w=o,e.X=i,e.i=a}(t,e)}function r(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function a(e,t){null==e&&(e=+/* @__PURE__ */new Date);var a=new n(e),s=t&&t.state,o=function(){return(a.next()>>>0)/4294967296};return o.double=function(){do{var e=((a.next()>>>11)+(a.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=a.next,o.quick=o,s&&(s.X&&r(s,a),o.state=function(){return r(a,{})}),o}t&&t.exports?t.exports=a:this.xor4096=a}(0,sl)),sl.exports),s=(ol||(ol=1,function(e,t){function n(e){var t=this,n="";t.next=function(){var e=t.b,n=t.c,r=t.d,a=t.a;return e=e<<25^e>>>7^n,n=n-r|0,r=r<<24^r>>>8^a,a=a-e|0,t.b=e=e<<20^e>>>12^n,t.c=n=n-r|0,t.d=r<<16^n>>>16^a,t.a=a-e|0},t.a=0,t.b=0,t.c=-1640531527,t.d=1367130551,e===Math.floor(e)?(t.a=e/4294967296|0,t.b=0|e):n+=e;for(var r=0;r>>0)/4294967296};return o.double=function(){do{var e=((a.next()>>>11)+(a.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=a.next,o.quick=o,s&&("object"==typeof s&&r(s,a),o.state=function(){return r(a,{})}),o}t&&t.exports?t.exports=a:this.tychei=a}(0,il)),il.exports),o=fl();return o.alea=e,o.xor128=t,o.xorwow=n,o.xorshift7=r,o.xor4096=a,o.tychei=s,dl=o}();class gl{constructor(e,t,n,r,a){this.mean=e,this.stdDev=t,this.dtype=n,this.nextVal=NaN,this.truncated=r,this.truncated&&(this.upper=this.mean+2*this.stdDev,this.lower=this.mean-2*this.stdDev);const s=a||Math.random();this.random=ml.alea(s.toString())}nextValue(){if(!isNaN(this.nextVal)){const e=this.nextVal;return this.nextVal=NaN,e}let e,t,n=!1;for(;!n;){let r,a,s;do{r=2*this.random()-1,a=2*this.random()-1,s=r*r+a*a}while(s>=1||0===s);const o=Math.sqrt(-2*Math.log(s)/s);e=this.mean+this.stdDev*r*o,t=this.mean+this.stdDev*a*o,this.truncated&&!this.isValidTruncated(e)||(n=!0)}return this.truncated&&!this.isValidTruncated(t)||(this.nextVal=this.convertValue(t)),this.convertValue(e)}convertValue(e){return null==this.dtype||"float32"===this.dtype?e:Math.round(e)}isValidTruncated(e){return e<=this.upper&&e>=this.lower}}class yl{constructor(e,t,n,r){this.alpha=e,this.beta=1/t,this.dtype=n;const a=r||Math.random();this.randu=ml.alea(a.toString()),this.randn=new gl(0,1,n,!1,this.randu()),this.d=e<1?e+2/3:e-1/3,this.c=1/Math.sqrt(9*this.d)}nextValue(){let e,t,n,r,a,s;for(;;){do{r=this.randn.nextValue(),s=1+this.c*r}while(s<=0);if(s*=s*s,e=r*r,t=1-.331*e*e,n=.5*e+this.d*(1-s+Math.log(s)),a=this.randu(),anull==this.dtype||"float32"===this.dtype,this.min=e,this.range=t-e,this.dtype=n,null==r&&(r=Math.random()),"number"===typeof r&&(r=r.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=ml.alea(r)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}const xl=/* @__PURE__ */Aa({randomGamma_:function(e,t,n=1,r="float32",a){if(O(e),null==n&&(n=1),null==r&&(r="float32"),"float32"!==r&&"int32"!==r)throw new Error(`Unsupported data type ${r}`);const s=new yl(t,n,r,a),o=Ps(e,r);for(let i=0;i`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),El(t,0)}});const _l=/* @__PURE__ */Aa({reverse2d_:function(e,t){const n=Ea(e,"x","reverse");return i(2===n.rank,()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`),El(n,t)}});const Al=/* @__PURE__ */Aa({reverse3d_:function(e,t){const n=Ea(e,"x","reverse");return i(3===n.rank,()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`),El(n,t)}});const Ol=/* @__PURE__ */Aa({reverse4d_:function(e,t){const n=Ea(e,"x","reverse");return i(4===n.rank,()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`),El(n,t)}});const Fl=/* @__PURE__ */Aa({round_:function(e){const t={x:Ea(e,"x","round")};return wa.runKernel(cn,t)}});const Dl=/* @__PURE__ */Aa({rsqrt_:function(e){const t={x:Ea(e,"x","rsqrt","float32")};return wa.runKernel(dn,t)}});const Ml=/* @__PURE__ */Aa({selu_:function(e){const t={x:Ea(e,"x","selu")};return wa.runKernel(gn,t)}});const Pl=/* @__PURE__ */Aa({separableConv2d_:function(e,t,n,r,a,s=[1,1],o="NHWC"){const u=Ea(e,"x","separableConv2d"),l=Ea(t,"depthwiseFilter","separableConv2d"),c=Ea(n,"pointwiseFilter","separableConv2d");let d=u,p=!1;if(3===u.rank&&(p=!0,d=vo(u,[1,u.shape[0],u.shape[1],u.shape[2]])),"NCHW"===o)throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");i(4===d.rank,()=>`Error in separableConv2d: input must be rank 4, but got rank ${d.rank}.`),i(4===l.rank,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),i(4===c.rank,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),i(1===c.shape[0],()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${c.shape[0]}.`),i(1===c.shape[1],()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${c.shape[1]}.`);const h=l.shape[2],f=l.shape[3];i(c.shape[2]===h*f,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${h*f}, but got ${c.shape[2]}.`);const m=ai(d,l,r,a,o,s),g=Ho(m,c,1,"valid",o);return p?vo(g,[g.shape[1],g.shape[2],g.shape[3]]):g}});const Ll=async function(e,t){const n=Ea(e,"x","setdiff1d"),r=Ea(t,"y","setdiff1d");i(n.dtype===r.dtype,()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${r.dtype}).`),i(1===n.rank,()=>`x should be 1D tensor, but got x (${n.shape}).`),i(1===r.rank,()=>`y should be 1D tensor, but got y (${r.shape}).`);const a=await n.data(),s=await r.data(),o=new Set(s);let u=0;for(let i=0;i`slice1d expects a rank-1 tensor, but got a rank-${r.rank} tensor`),To(r,[t],[n])}});const Ul=/* @__PURE__ */Aa({slice2d_:function(e,t,n){const r=Ea(e,"x","slice2d");return i(2===r.rank,()=>`slice2d expects a rank-2 tensor, but got a rank-${r.rank} tensor`),To(r,t,n)}});const Gl=/* @__PURE__ */Aa({slice3d_:function(e,t,n){const r=Ea(e,"x","slice3d");return i(3===r.rank,()=>`slice3d expects a rank-3 tensor, but got a rank-${r.rank} tensor`),To(r,t,n)}});const Hl=/* @__PURE__ */Aa({slice4d_:function(e,t,n){const r=Ea(e,"x","slice4d");return i(4===r.rank,()=>`slice4d expects a rank-4 tensor, but got a rank-${r.rank} tensor`),To(r,t,n)}});const jl=/* @__PURE__ */Aa({softmax_:function(e,t=-1){const n=Ea(e,"logits","softmax","float32");if(-1===t&&(t=n.rank-1),t!==n.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and dim was ${t}`);const r={logits:n},a={dim:t};return wa.runKernel(Cn,r,a)}});const ql=/* @__PURE__ */Aa({fft_:function(e){i("complex64"===e.dtype,()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);const t={input:e};return wa.runKernel(Ye,t)}});const Kl=/* @__PURE__ */Aa({ifft_:function(e){i("complex64"===e.dtype,()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);const t={input:e};return wa.runKernel(it,t)}});const Xl=/* @__PURE__ */Aa({irfft_:function(e){const t=e.shape[e.shape.length-1],n=e.size/t;let r;if(t<=2){const a=vo(e,[n,t]);r=Kl(a)}else{const a=[n,2*(t-1)],s=vo(Sl(e),[n,t]),o=vo(ji(e),[n,t]),i=El(To(s,[0,1],[n,t-2]),1),u=Gs(El(To(o,[0,1],[n,t-2]),1),Ri(-1)),l=Io([s,i],1),c=Io([o,u],1),d=vo(Oa(l,c),[a[0],a[1]]);r=Kl(d)}if(r=Sl(r),3===e.rank&&0!==e.shape[0]){const t=r,n=e.shape[0];r=vo(r,[n,r.shape[0]/n,r.shape[1]]),t.dispose()}return r}});const Yl=/* @__PURE__ */Aa({split_:function(e,t,n=0){const r={x:Ea(e,"x","split")},a={numOrSizeSplits:t,axis:n};return wa.runKernel(Tn,r,a)}});const Ql=/* @__PURE__ */Aa({rfft_:function(e,t){i("float32"===e.dtype,()=>`The dtype for rfft() must be real value but got ${e.dtype}`);let n=e.shape[e.shape.length-1];const r=e.size/n;let a;if(null!=t&&t0),s=e.shape.map(e=>e);s[e.shape.length-1]=t,a=To(e,r,s),n=t}else if(null!=t&&t>n){const r=e.shape.map(e=>e);r[e.shape.length-1]=t-n,a=Io([e,Iu(r)],e.shape.length-1),n=t}else a=e;const s=pi(a),o=vo(Oa(a,s),[r,n]),u=ql(o),l=Math.floor(n/2)+1,c=Sl(u),d=ji(u),p=Yl(c,[l,n-l],c.shape.length-1),h=Yl(d,[l,n-l],d.shape.length-1),f=a.shape.slice();return f[a.shape.length-1]=l,vo(Oa(p[0],h[0]),f)}});const Zl=/* @__PURE__ */Aa({squaredDifference_:function(e,t){let n=Ea(e,"a","squaredDifference"),r=Ea(t,"b","squaredDifference");[n,r]=fa(n,r),li(n.shape,r.shape);const a={a:n,b:r};return wa.runKernel(On,a,{})}});const Jl=/* @__PURE__ */Aa({squeeze_:function(e,t){const n=Ea(e,"x","squeeze","string_or_numeric");return vo(n,b(n.shape,t).newShape)}});const ec=/* @__PURE__ */Aa({stack_:function(e,t=0){const n=Ra(e,"tensors","stack","string_or_numeric");i(n.length>=1,()=>"Pass at least one tensor to tf.stack"),n.length>0&&i(t<=n[0].rank,()=>"Axis must be <= rank of the tensor");const r=n,a={axis:t};return wa.runKernel(Gt,r,a)}});const tc=/* @__PURE__ */Aa({step_:function(e,t=0){const n={x:Ea(e,"x","step")},r={alpha:t};return wa.runKernel(Qn,n,r)}});const nc=/* @__PURE__ */Aa({stridedSlice_:function(e,t,n,r,a=0,s=0,o=0,i=0,u=0){const l={x:Ea(e,"x","stridedSlice","string_or_numeric")},c={begin:t,end:n,strides:r,beginMask:a,endMask:s,ellipsisMask:o,newAxisMask:i,shrinkAxisMask:u};return wa.runKernel(Mn,l,c)}});const rc=/* @__PURE__ */Aa({tan_:function(e){const t={x:Ea(e,"x","tan","float32")};return wa.runKernel(Wn,t)}});function ac(e,t){l(e);const n=Ta(e,t);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return Fa(e,null,n,t)}function sc(e,t,n){if(l(e),null!=t&&2!==t.length)throw new Error("tensor2d() requires shape to have two numbers");const r=Ta(e,n);if(2!==r.length&&1!==r.length)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return Fa(e,t,r,n)}function oc(e,t,n){if(l(e),null!=t&&3!==t.length)throw new Error("tensor3d() requires shape to have three numbers");const r=Ta(e,n);if(3!==r.length&&1!==r.length)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return Fa(e,t,r,n)}function ic(e,t,n){if(l(e),null!=t&&4!==t.length)throw new Error("tensor4d() requires shape to have four numbers");const r=Ta(e,n);if(4!==r.length&&1!==r.length)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return Fa(e,t,r,n)}function uc(e,t,n){if(l(e),null!=t&&5!==t.length)throw new Error("tensor5d() requires shape to have five numbers");const r=Ta(e,n);if(5!==r.length&&1!==r.length)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return Fa(e,t,r,n)}function lc(e,t,n){if(l(e),null!=t&&6!==t.length)throw new Error("tensor6d() requires shape to have six numbers");const r=Ta(e,n);if(6!==r.length&&1!==r.length)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return Fa(e,t=t||r,r,n)}function cc(e,t,n){const r=t.rank>1?t.shape[t.rank-1]:1,a=t.rank>1?t.rank-1:1,s=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${n.shape}, indices.shape: ${t.shape}, shape: ${e}, sliceDim: ${r}, and batchDim: ${a}.`;if(n.rank1?t.shape[r-1]:1,s=n.length;let o=1;for(let u=a;u= 0 but got ${t}`);if(t>a)throw new Error(`'k' passed to topk() must be <= the last dimension (${a}) but got ${t}`);const s={x:r},o={k:t,sorted:n},[i,u]=wa.runKernel(Gn,s,o);return{values:i,indices:u}}});const mc=/* @__PURE__ */Aa({truncatedNormal_:function(e,t=0,n=1,r,a){if(O(e),null!=r&&"bool"===r)throw new Error("Unsupported data type $ { dtype }");const s=new gl(t,n,r,!0,a),o=Ps(e,r);for(let i=0;i0,()=>"The input tensor must be at least 1D");const r={x:n},a={axis:t},[s,o]=wa.runKernel(qn,r,a);return{values:s,indices:o}}});const yc=/* @__PURE__ */Aa({unsortedSegmentSum_:function(e,t,n){const r=Ea(e,"x","unsortedSegmentSum"),a=Ea(t,"segmentIds","unsortedSegmentSum","int32");i(p(n),()=>"numSegments must be of dtype int");const s={x:r,segmentIds:a},o={numSegments:n};return wa.runKernel(Xn,s,o)}});const bc=/* @__PURE__ */Aa({unstack_:function(e,t=0){const n=Ea(e,"x","unstack","string_or_numeric");i(t>=-n.shape.length&&t`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`);const r={value:n},a={axis:t};return wa.runKernel(Kn,r,a)}});function xc(e,t){return gu(e,t,"right")}function vc(e,t=!0,n,r){return wa.makeVariable(e,t,n,r)}function wc(e,t){const n=[];for(let s=0;s0,()=>"mask cannot be scalar"),u(l.slice(s,s+o),a.shape,"mask's shape must match the first K dimensions of tensor's shape,");let c=1;for(let i=s;it).reverse()),i(r.rank===t.length,()=>`Error in transpose: rank of input ${r.rank} must match length of perm ${t}.`),t.forEach(e=>{i(e>=0&&e`All entries in 'perm' must be between 0 and ${r.rank-1} but got ${t}`)}),r.rank<=1)return r.clone();const a={x:r},s={perm:t};return"complex64"===r.dtype?Ba(()=>{let e=Sl(r),t=ji(r);return e=wa.runKernel(jn,{x:e},s),t=wa.runKernel(jn,{x:t},s),n&&(t=su(t)),Oa(e,t)}):wa.runKernel(jn,a,s)}});const Sc=/* @__PURE__ */Aa({movingAverage_:function(e,t,n,r,a=!0){const s=Ea(e,"v","movingAverage"),o=Ea(t,"x","movingAverage"),u=Ea(n,"decay","movingAverage");var l,c;c=o,i((l=s).dtype===c.dtype,()=>`The dtypes of the first(${l.dtype}) and second(${c.dtype}) input must match`),i(d(s.shape,o.shape),()=>"Shape mismatch in v and x");const p=Ri(1),h=uu(p,u);let f=Gs(uu(o,s),h);if(a){i(null!=r,()=>"When using zeroDebias: true, step is required.");const e=Ea(r,"step","movingAverage");f=Us(f,uu(p,Ei(u,e)))}return Ws(s,f)}});const Tc=/* @__PURE__ */Aa({scatterND_:function(e,t,n){O(n);const r=Ea(e,"indices","scatterND","int32"),a=Ea(t,"updates","scatterND");dc(a,r,n);const s={indices:r,updates:a},o={shape:n};return wa.runKernel(pn,s,o)}});const Cc=/* @__PURE__ */Aa({sparseToDense_:function(e,t,n,r=0){O(n);const a=Ea(e,"sparseIndices","sparseToDense","int32"),s=Ea(t,"sparseValues","sparseToDense","string_or_numeric"),o=Ea(r,"defaultValue","sparseToDense",s.dtype);!function(e,t,n,r){if("int32"!==e.dtype)throw new Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was ${e.dtype}.`);if(e.rank>2)throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${e.shape}.`);const a=e.rank>0?e.shape[0]:1,s=e.rank>1?e.shape[1]:1;if(n.length!==s)throw new Error(`outputShape has incorrect number of elements:, ${n.length}, should be: ${s}.`);const o=t.size;if(0!==t.rank&&(1!==t.rank||o!==a))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${a}]`);if(t.dtype!==r.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(a,s,n,o);const i={sparseIndices:a,sparseValues:s,defaultValue:o},u={outputShape:n};return wa.runKernel(An,i,u)}});const $c=/* @__PURE__ */Aa({gatherND_:function(e,t){const n=Ea(t,"indices","gatherND","int32"),r={params:Ea(e,"x","gatherND","string_or_numeric"),indices:n};return wa.runKernel(rt,r)}});const Ec=/* @__PURE__ */Aa({dropout_:function(e,t,n,r){const a=Ea(e,"x","dropout");if(i("float32"===a.dtype,()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${a.dtype} tensor instead.`),i(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),0===t)return e instanceof Yr?a.clone():a;const s=function(e,t){if(null==t)return e.shape.slice();if(d(e.shape,t))return t;if(e.shape.length===t.length){const n=[];for(let r=0;r1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${r.rank}`),i(r.rank-1===a.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${r.rank} and targets rank ${a.rank}`),u(r.shape.slice(0,r.shape.length-1),a.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");const s=r.shape[r.shape.length-1];i(n>0&&n<=s,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${s}), but got ${n}`);const o=await r.data(),l=await a.data(),[c,d]=[o.length/s,s],p=x("bool",c);for(let i=0;it.value-e.value),p[i]=0;for(let a=0;a`Error in conv2dDerFilter: input must be rank 4, but got shape ${u.shape}.`),i(4===l.rank,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),i(4===n.length,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`);const c="NHWC"===s?u.shape[3]:u.shape[1],d="NHWC"===s?l.shape[3]:l.shape[1];i(c===n[2],()=>`Error in conv2dDerFilter: depth of input ${c}) must match input depth in filter (${n[2]}.`),i(d===n[3],()=>`Error in conv2dDerFilter: depth of dy (${d}) must match output depth for filter (${n[3]}).`),xo("conv2dDerFilter",a,o);const p={x:u,dy:l},h={strides:r,pad:a,dataFormat:s,dimRoundingMode:o,filterShape:n};return wa.runKernel(we,p,h)}});function Fc(e,t,n){if(null==n||"linear"===n)return e;if("relu"===n)return Gs(e,tc(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function Dc(e,t){let n=t;const r=ui(e.shape,t.shape);return r.length>0&&(n=Oi(n,r)),vo(n,e.shape)}function Mc(e,t,n,r){if("linear"===t)return e;if("relu"===t)return Cl(e);if("elu"===t)return gi(e);if("relu6"===t)return $l(e);if("prelu"===t)return Uu(e,n);if("leakyrelu"===t)return Yi(e,r);if("sigmoid"===t)return So(e);throw new Error(`Unknown fused activation ${t}.`)}const Pc=(e,t)=>!(e>0)||"linear"===t;const Lc=/* @__PURE__ */Aa({fusedConv2d_:function({x:e,filter:t,strides:n,pad:r,dataFormat:a="NHWC",dilations:s=[1,1],dimRoundingMode:o,bias:u,activation:l="linear",preluActivationWeights:c,leakyreluAlpha:d}){if(l=l||"linear",!1===Pc(wa.state.gradientDepth,l)){i("NHWC"===a,()=>`Error in fused conv2d: got dataFormat of ${a} but only NHWC is currently supported for the case of gradient depth is 0 and the activation is not linear.`);let p=Ho(e,t,n,r,a,s,o);return null!=u&&(p=Ws(p,u)),Mc(p,l,c,d)}const p=Ea(e,"x","conv2d","float32"),h=Ea(t,"filter","conv2d","float32");let f=p,m=!1;3===p.rank&&(m=!0,f=vo(p,[1,p.shape[0],p.shape[1],p.shape[2]])),i(4===f.rank,()=>`Error in fused conv2d: input must be rank 4, but got rank ${f.rank}.`),i(4===h.rank,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${h.rank}.`),xo("fused conv2d",r,o);const g="NHWC"===a?f.shape[3]:f.shape[1];i(h.shape[2]===g,()=>`Error in conv2d: depth of input (${g}) must match input depth for filter ${h.shape[2]}.`),i(go(n,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`);const y=io(f.shape,h.shape,n,s,r,o);let b,x;if(null!=u&&(b=Ea(u,"bias","fused conv2d"),[b]=fa(b,p),"NHWC"===a?li(y.outShape,b.shape):(i(b.shape.length<=1,()=>`Error in fused conv2d: only supports scalar or 1-D Tensor bias for NCHW format but got the bias of rank-${b.shape.length}.`),i(0===b.shape.length||b.shape[0]===y.outChannels||1===b.shape[0],()=>`Error in fused conv2d: bias shape (${b.shape}) is not compatible with the number of output channels (${y.outChannels})`))),null!=c){const e=c.shape;if(i(e.length<=1||3===e.length,()=>`Error in fused conv2d: only supports scalar, 1-D Tensor or 3-D Tensor PReLU activation weights but got a tensor of rank-${e.length}.`),1===e.length)i(1===e[0]||e[0]===y.outChannels,()=>`Error in fused conv2d: PReLU activation weights (${e}) is not compatible with the number of output channels (${y.outChannels}).`);else if(3===e.length)try{li(e,y.outShape)}catch(I){const t=`Error in fused conv2d: PReLU activation weights (${e}) is not compatible with the output shape of the conv2d (${y.outShape}).`;throw Error(t)}x=Ea(c,"prelu weights","fused conv2d")}const v=(e,t)=>{i("NHWC"===a,()=>`Error in gradient of fused conv2D: got dataFormat of ${a} but only NHWC is currently supported.`);const[o,u,c,d]=t,p=Fc(e,c,l);i(mo(s),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);const h=[qo(u.shape,p,o,n,r),Oc(u,p,o.shape,n,r)];if(null!=d){const e=Dc(d,p);h.push(e)}return h},w={x:f,filter:h,bias:b,preluActivationWeights:x},k={strides:n,pad:r,dataFormat:a,dilations:s,dimRoundingMode:o,activation:l,leakyreluAlpha:d};if(null==u){return au((e,t,n)=>{let r=wa.runKernel(tr,w,k);return n([t,e,r]),m&&(r=vo(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:v}})(f,h)}return au((e,t,n,r)=>{let a=wa.runKernel(tr,w,k);return r([t,e,a,n]),m&&(a=vo(a,[a.shape[1],a.shape[2],a.shape[3]])),{value:a,gradFunc:v}})(f,h,b)}});const Bc=Aa({depthwiseConv2dNativeBackpropFilter_:function(e,t,n,r,a,s=[1,1],o){let i=e;3===e.rank&&(i=vo(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let u=t;3===u.rank&&(u=vo(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const l={x:i,dy:u},c={strides:r,pad:a,dimRoundingMode:o,dilations:s,filterShape:n};return wa.runKernel(Fe,l,c)}});const Vc=Aa({depthwiseConv2dNativeBackpropInput_:function(e,t,n,r,a,s=[1,1],o){let i=t,u=!1;3===t.rank&&(u=!0,i=vo(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const l={dy:i,filter:n},c={strides:r,pad:a,dimRoundingMode:o,dilations:s,inputShape:e},d=wa.runKernel(De,l,c);return u?vo(d,[d.shape[1],d.shape[2],d.shape[3]]):d}});const Wc=/* @__PURE__ */Aa({fusedDepthwiseConv2d_:function({x:e,filter:t,strides:n,pad:r,dataFormat:a="NHWC",dilations:s=[1,1],dimRoundingMode:o,bias:u,activation:l="linear",preluActivationWeights:c,leakyreluAlpha:d}){if(!1===Pc(wa.state.gradientDepth,l)){let i=ai(e,t,n,r,a,s,o);return null!=u&&(i=Ws(i,u)),Mc(i,l,c,d)}const p=Ea(e,"x","depthwiseConv2d","float32"),h=Ea(t,"filter","depthwiseConv2d","float32");let f=p,m=!1;3===p.rank&&(m=!0,f=vo(p,[1,p.shape[0],p.shape[1],p.shape[2]])),i(4===f.rank,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${f.rank}.`),i(4===h.rank,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${h.rank}.`),i(f.shape[3]===h.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${f.shape[3]}) must match the inChannels dimension in filter ${h.shape[2]}.`),null==s&&(s=[1,1]),i(go(n,s),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`),xo("fused depthwiseConv2d",r,o);const g=io(f.shape,h.shape,n,s,r,o,!0);let y,b;null!=u&&(y=Ea(u,"bias","fused conv2d"),[y]=fa(y,p),li(g.outShape,y.shape)),null!=c&&(b=Ea(c,"prelu weights","fused depthwiseConv2d"));const x=(e,t)=>{i(mo(s),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${s}'`);const[a,u,c,d]=t,p=Fc(e,c,l),h=Vc(u.shape,p,a,n,r,s,o),f=Bc(u,p,a.shape,n,r,s,o);if(null!=d){return[h,f,Dc(y,p)]}return[h,f]},v={x:f,filter:h,bias:y,preluActivationWeights:b},w={strides:n,pad:r,dataFormat:a,dilations:s,dimRoundingMode:o,activation:l,leakyreluAlpha:d};if(null==u){return au((e,t,n)=>{let r=wa.runKernel(nr,v,w);return n([t,e,r]),m&&(r=vo(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:x}})(f,h)}return au((e,t,n,r)=>{let a=wa.runKernel(nr,v,w);return r([t,e,a,n]),m&&(a=vo(a,[a.shape[1],a.shape[2],a.shape[3]])),{value:a,gradFunc:x}})(f,h,y)}});const zc=/* @__PURE__ */Aa({fusedMatMul_:function({a:e,b:t,transposeA:n=!1,transposeB:r=!1,bias:a,activation:s="linear",preluActivationWeights:o,leakyreluAlpha:u=.2}){if(!1===Pc(wa.state.gradientDepth,s)){let i=No(e,t,n,r);return null!=a&&(i=Ws(i,a)),Mc(i,s,o,u)}let l=Ea(e,"a","fused matMul"),d=Ea(t,"b","fused matMul");[l,d]=fa(l,d);const p=n?l.shape[l.rank-2]:l.shape[l.rank-1],h=r?d.shape[d.rank-1]:d.shape[d.rank-2],f=n?l.shape[l.rank-1]:l.shape[l.rank-2],m=r?d.shape[d.rank-2]:d.shape[d.rank-1],g=l.shape.slice(0,-2),y=d.shape.slice(0,-2),b=c(g),x=c(y);i(p===h,()=>`Error in fused matMul: inner shapes (${p}) and (${h}) of Tensors with shapes ${l.shape} and ${d.shape} and transposeA=${n} and transposeB=${r} must match.`);const v=li(l.shape.slice(0,-2),d.shape.slice(0,-2)).concat([f,m]),w=vo(l,n?[b,p,f]:[b,f,p]),k=vo(d,r?[x,m,h]:[x,h,m]);let I,N;null!=a&&(I=Ea(a,"bias","fused matMul"),[I]=fa(I,l),li(v,I.shape)),null!=o&&(N=Ea(o,"prelu weights","fused matMul"));const S=(e,t)=>{const[o,i,u,l]=t,c=Fc(vo(e,u.shape),u,s);let d,p;if(n||r?!n&&r?(d=No(c,i,!1,!1),p=No(c,o,!0,!1)):n&&!r?(d=No(i,c,!1,!0),p=No(o,c,!1,!1)):(d=No(i,c,!0,!0),p=No(c,o,!0,!0)):(d=No(c,i,!1,!0),p=No(o,c,!0,!1)),null!=a){return[d,p,Dc(l,c)]}return[d,p]},T={a:w,b:k,bias:I,preluActivationWeights:N},C={transposeA:n,transposeB:r,activation:s,leakyreluAlpha:u};if(null==a){return au((e,t,n)=>{const r=wa.runKernel(er,T,C);return n([e,t,r]),{value:vo(r,v),gradFunc:S}})(w,k)}return au((e,t,n,r)=>{const a=wa.runKernel(er,T,C);return r([e,t,a,n]),{value:vo(a,v),gradFunc:S}})(w,k,I)}}),Uc=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,conv2d:Lc,depthwiseConv2d:Wc,matMul:zc},Symbol.toStringTag,{value:"Module"}));const Gc=/* @__PURE__ */Aa({hammingWindow_:function(e){return _c(e,.54,.46)}});const Hc=/* @__PURE__ */Aa({hannWindow_:function(e){return _c(e,.5,.5)}});const jc=/* @__PURE__ */Aa({frame_:function(e,t,n,r=!1,a=0){let s=0;const o=[];for(;s+t<=e.size;)o.push(To(e,s,t)),s+=n;if(r)for(;s`Error in cropAndResize: image must be rank 4,but got rank ${o.rank}.`),i(2===u.rank&&4===u.shape[1],()=>`Error in cropAndResize: boxes must be have size [${c},4] but had shape ${u.shape}.`),i(1===l.rank&&l.shape[0]===c,()=>`Error in cropAndResize: boxInd must be have size [${c}] but had shape ${u.shape}.`),i(2===r.length,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${r.length}.`),i(r[0]>=1&&r[1]>=1,()=>`cropSize must be atleast [1,1], but was ${r}`),i("bilinear"===a||"nearest"===a,()=>`method must be bilinear or nearest, but was ${a}`);const d={image:o,boxes:u,boxInd:l},p={method:a,extrapolationValue:s,cropSize:r};return wa.runKernel(Re,d,p)}});const Xc=/* @__PURE__ */Aa({flipLeftRight_:function(e){const t=Ea(e,"image","flipLeftRight","float32");i(4===t.rank,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);const n={image:t};return wa.runKernel(Ze,n,{})}});const Yc=/* @__PURE__ */Aa({grayscaleToRGB_:function(e){const t=Ea(e,"image","grayscaleToRGB"),n=t.rank-1,r=t.shape[n];i(t.rank>=2,()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`),i(1===r,()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${r}.`);const a=new Array(t.rank);return a.fill(1,0,n),a[n]=3,Vi(t,a)}});const Qc=/* @__PURE__ */Aa({rgbToGrayscale_:function(e){const t=Ea(e,"image","RGBToGrayscale"),n=t.rank-1,r=t.shape[n];i(t.rank>=2,()=>`Error in RGBToGrayscale: images must be at least rank 2, but got rank ${t.rank}.`),i(3===r,()=>`Error in RGBToGrayscale: last dimension of an RGB image should be size 3, but got size ${r}.`);const a=t.dtype,s=Ls(t,"float32"),o=ac([.2989,.587,.114]);let u;switch(t.rank){case 2:u=mi("ij,j->i",s,o);break;case 3:u=mi("ijk,k->ij",s,o);break;case 4:u=mi("ijkl,l->ijk",s,o);break;case 5:u=mi("ijklm,m->ijkl",s,o);break;case 6:u=mi("ijklmn,n->ijklm",s,o);break;default:throw new Error("Not a valid tensor rank.")}return u=Li(u,-1),Ls(u,a)}});const Zc=/* @__PURE__ */Aa({rotateWithOffset_:function(e,t,n=0,r=.5){const a=Ea(e,"image","rotateWithOffset","float32");i(4===a.rank,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${a.rank}.`);const s={image:a},o={radians:t,fillValue:n,center:r};return wa.runKernel(Jn,s,o)}});function Jc(e,t,n,r,a,s){null==r&&(r=.5),null==a&&(a=Number.NEGATIVE_INFINITY),null==s&&(s=0);const o=e.shape[0];return n=Math.min(n,o),i(0<=r&&r<=1,()=>`iouThreshold must be in [0, 1], but was '${r}'`),i(2===e.rank,()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`),i(4===e.shape[1],()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`),i(1===t.rank,()=>"scores must be a 1D tensor"),i(t.shape[0]===o,()=>`scores has incompatible shape with boxes. Expected ${o}, but was ${t.shape[0]}`),i(0<=s&&s<=1,()=>`softNmsSigma must be in [0, 1], but was '${s}'`),{maxOutputSize:n,iouThreshold:r,scoreThreshold:a,softNmsSigma:s}}const ed=/* @__PURE__ */Aa({nonMaxSuppression_:function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY){const s=Ea(e,"boxes","nonMaxSuppression","float32"),o=Ea(t,"scores","nonMaxSuppression","float32"),i=Jc(s,o,n,r,a),u={maxOutputSize:n=i.maxOutputSize,iouThreshold:r=i.iouThreshold,scoreThreshold:a=i.scoreThreshold};return wa.runKernel(Bt,{boxes:s,scores:o},u)}});function td(e,t,n){const r=function(e,t,n){return function(e,t,n){let r=0,a=e.length,s=0,o=!1;for(;r>>1);const i=n(t,e[s]);i>0?r=s+1:(a=s,o=!i)}return o?r:-r-1}(e,t,n||nd)}(e,t,n),a=r<0?-(r+1):r;e.splice(a,0,t)}function nd(e,t){return e>t?1:ea&&l.push({score:t[g],boxIndex:g,suppressBeginIndex:0});l.sort(ld);const c=s>0?-.5/s:0,d=[],p=[];for(;d.length0;){const t=l.pop(),{score:n,boxIndex:s,suppressBeginIndex:o}=t;if(n=o;--u){const n=id(e,s,d[u]);if(n>=r){i=!0;break}if(t.score=t.score*ud(r,c,n),t.score<=a)break}t.suppressBeginIndex=d.length,i||(t.score===n?(d.push(s),p.push(t.score)):t.score>a&&td(l,t,ld))}const h=d.length,f=n-h;i&&f>0&&(d.push(...new Array(f).fill(0)),p.push(...new Array(f).fill(0)));const m={selectedIndices:d};return o&&(m.selectedScores=p),u&&(m.validOutputs=h),m}function id(e,t,n){const r=e.subarray(4*t,4*t+4),a=e.subarray(4*n,4*n+4),s=Math.min(r[0],r[2]),o=Math.min(r[1],r[3]),i=Math.max(r[0],r[2]),u=Math.max(r[1],r[3]),l=Math.min(a[0],a[2]),c=Math.min(a[1],a[3]),d=Math.max(a[0],a[2]),p=Math.max(a[1],a[3]),h=(i-s)*(u-o),f=(d-l)*(p-c);if(h<=0||f<=0)return 0;const m=Math.max(s,l),g=Math.max(o,c),y=Math.min(i,d),b=Math.min(u,p),x=Math.max(y-m,0)*Math.max(b-g,0);return x/(h+f-x)}function ud(e,t,n){const r=Math.exp(t*n*n);return n<=e?r:0}function ld(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}const cd=async function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY){const s=Ea(e,"boxes","nonMaxSuppressionAsync"),o=Ea(t,"scores","nonMaxSuppressionAsync"),i=Jc(s,o,n,r,a);n=i.maxOutputSize,r=i.iouThreshold,a=i.scoreThreshold;const u=await Promise.all([s.data(),o.data()]),l=u[0],c=u[1],{selectedIndices:d}=rd(l,c,n,r,a);return s!==e&&s.dispose(),o!==t&&o.dispose(),ac(d,"int32")};const dd=/* @__PURE__ */Aa({nonMaxSuppressionWithScore_:function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY,s=0){const o=Ea(e,"boxes","nonMaxSuppression"),i=Ea(t,"scores","nonMaxSuppression"),u=Jc(o,i,n,r,a,s),l={boxes:o,scores:i},c={maxOutputSize:n=u.maxOutputSize,iouThreshold:r=u.iouThreshold,scoreThreshold:a=u.scoreThreshold,softNmsSigma:s=u.softNmsSigma},d=wa.runKernel(Wt,l,c);return{selectedIndices:d[0],selectedScores:d[1]}}});const pd=async function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY,s=0){const o=Ea(e,"boxes","nonMaxSuppressionAsync"),i=Ea(t,"scores","nonMaxSuppressionAsync"),u=Jc(o,i,n,r,a,s);n=u.maxOutputSize,r=u.iouThreshold,a=u.scoreThreshold,s=u.softNmsSigma;const l=await Promise.all([o.data(),i.data()]),c=l[0],d=l[1],{selectedIndices:p,selectedScores:h}=sd(c,d,n,r,a,s);return o!==e&&o.dispose(),i!==t&&i.dispose(),{selectedIndices:ac(p,"int32"),selectedScores:ac(h)}};const hd=/* @__PURE__ */Aa({nonMaxSuppressionPadded_:function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY,s=!1){const o=Ea(e,"boxes","nonMaxSuppression"),i=Ea(t,"scores","nonMaxSuppression"),u=Jc(o,i,n,r,a,null),l={boxes:o,scores:i},c={maxOutputSize:u.maxOutputSize,iouThreshold:u.iouThreshold,scoreThreshold:u.scoreThreshold,padToMaxOutputSize:s},d=wa.runKernel(Vt,l,c);return{selectedIndices:d[0],validOutputs:d[1]}}});const fd=async function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY,s=!1){const o=Ea(e,"boxes","nonMaxSuppressionAsync"),i=Ea(t,"scores","nonMaxSuppressionAsync"),u=Jc(o,i,n,r,a,null),l=u.maxOutputSize,c=u.iouThreshold,d=u.scoreThreshold,[p,h]=await Promise.all([o.data(),i.data()]),{selectedIndices:f,validOutputs:m}=ad(p,h,l,c,d,s);return o!==e&&o.dispose(),i!==t&&i.dispose(),{selectedIndices:ac(f,"int32"),validOutputs:Ri(m,"int32")}};const md=/* @__PURE__ */Aa({resizeBilinear_:function(e,t,n=!1,r=!1){const a=Ea(e,"images","resizeBilinear");i(3===a.rank||4===a.rank,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${a.rank}.`),i(2===t.length,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`),i(!1===r||!1===n,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let s=a,o=!1;3===a.rank&&(o=!0,s=vo(a,[1,a.shape[0],a.shape[1],a.shape[2]]));const u={images:s},l={alignCorners:n,halfPixelCenters:r,size:t},c=wa.runKernel(sn,u,l);return o?vo(c,[c.shape[1],c.shape[2],c.shape[3]]):c}});const gd=/* @__PURE__ */Aa({resizeNearestNeighbor_:function(e,t,n=!1,r=!1){const a=Ea(e,"images","resizeNearestNeighbor");i(3===a.rank||4===a.rank,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${a.rank}.`),i(2===t.length,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),i("float32"===a.dtype||"int32"===a.dtype,()=>"`images` must have `int32` or `float32` as dtype"),i(!1===r||!1===n,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let s=a,o=!1;3===a.rank&&(o=!0,s=vo(a,[1,a.shape[0],a.shape[1],a.shape[2]]));const u={images:s},l={alignCorners:n,halfPixelCenters:r,size:t},c=wa.runKernel(rn,u,l);return o?vo(c,[c.shape[1],c.shape[2],c.shape[3]]):c}});const yd=/* @__PURE__ */Aa({threshold_:function(e,t="binary",n=!1,r=.5){const a=Ea(e,"image","threshold"),s=a.shape[0]*a.shape[1];let o,u,l,c,d=Gs(ac([r]),255);if(i(3===a.rank,()=>`Error in threshold: image must be rank 3,but got rank ${a.rank}.`),i(3===a.shape[2]||1===a.shape[2],()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${a.shape[2]}.`),i("int32"===a.dtype||"float32"===a.dtype,()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${a.dtype}.`),i("otsu"===t||"binary"===t,()=>`Method must be binary or otsu, but was ${t}`),3===a.shape[2]){[o,u,l]=Yl(a,[1,1,1],-1);const e=Gs(o,.2989),t=Gs(u,.587),n=Gs(l,.114);c=Ws(Ws(e,t),n)}else c=e;if("otsu"===t){d=function(e,t){let n,r,a,s,o,i,u=ac([-1]),l=ac([0]),c=ac([0]);for(let d=0;d`Error in transform: image must be rank 4,but got rank ${o.rank}.`),i(2===u.rank&&(u.shape[0]===o.shape[0]||1===u.shape[0])&&8===u.shape[1],()=>"Error in transform: Input transform should be batch x 8 or 1 x 8"),i(null==s||2===s.length,()=>`Error in transform: outputShape must be [height, width] or null, but got ${s}.`);const l={image:o,transforms:u},c={interpolation:n,fillMode:r,fillValue:a,outputShape:s};return wa.runKernel(Hn,l,c)}});const xd=/* @__PURE__ */Aa({bandPart_:function(e,t,n){const r=Ea(e,"a","bandPart");i(r.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${r.rank}.`);const a=r.shape,[s,o]=r.shape.slice(-2);let u,l;"number"===typeof t?(i(t%1===0,()=>`bandPart(): numLower must be an integer, got ${t}.`),i(t<=s,()=>`bandPart(): numLower (${t}) must not be greater than the number of rows (${s}).`),u=Ea(t<0?s:t,"numLower","bandPart")):(i("int32"===t.dtype,()=>"bandPart(): numLower's dtype must be an int32."),u=di(Qi(t,0),s,Tu(t,s))),"number"===typeof n?(i(n%1===0,()=>`bandPart(): numUpper must be an integer, got ${n}.`),i(n<=o,()=>`bandPart(): numUpper (${n}) must not be greater than the number of columns (${o}).`),l=Ea(n<0?o:n,"numUpper","bandPart")):(i("int32"===n.dtype,()=>"bandPart(): numUpper's dtype must be an int32."),l=di(Qi(n,0),o,Tu(n,o)));const c=vo(Nl(0,s,1,"int32"),[-1,1]),d=Nl(0,o,1,"int32"),p=uu(c,d),h=du(Zi(p,u),Hi(p,su(l))),f=Iu([s,o],r.dtype);return vo(ec(bc(vo(r,[-1,s,o])).map(e=>di(h,e,f))),a)}});const vd=/* @__PURE__ */Aa({gramSchmidt_:function(e){let t;if(Array.isArray(e)){t=!1,i(null!=e&&e.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");const n=e[0].shape[0];for(let t=1;t`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[t].shape[0]} vs. ${n})`)}else t=!0,e=Yl(e,e.shape[0],0).map(e=>Jl(e,[0]));i(e.length<=e[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`);const n=[],r=e;for(let a=0;a{let e=r[a];if(a>0)for(let t=0;t{i(2===e.shape.length,()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`);const n=e.shape[0],r=e.shape[1];let a=Wi(n),s=Bs(e);const o=sc([[1]],[1,1]);let u=Bs(o);const l=n>=r?r:n;for(let e=0;e{const t=To(s,[e,e],[n-e,1]),i=Di(t),l=To(s,[e,e],[1,1]),c=di(Gi(l,0),sc([[-1]]),sc([[1]])),d=uu(l,Gs(c,i)),p=Us(t,d);u=1===p.shape[0]?Bs(o):Io([o,To(p,[1,0],[p.shape[0]-1,p.shape[1]])],0);const h=su(Us(No(c,d),i)),f=To(s,[e,0],[n-e,r]),m=Gs(h,u),g=Nc(u);if(0===e)s=uu(f,No(m,No(g,f)));else{const t=uu(f,No(m,No(g,f)));s=Io([To(s,[0,0],[e,r]),t],0)}const y=Nc(m),b=To(a,[0,e],[n,a.shape[1]-e]);if(0===e)a=uu(b,No(No(b,u),y));else{const t=uu(b,No(No(b,u),y));a=Io([To(a,[0,0],[n,e]),t],1)}return[u,s,a]}),Va([t,i,l])}return!t&&n>r&&(a=To(a,[0,0],[n,r]),s=To(s,[0,0],[r,r])),[a,s]})}const kd=/* @__PURE__ */Aa({qr_:function(e,t=!1){if(i(e.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`),2===e.rank)return wd(e,t);{const n=e.shape.slice(0,e.shape.length-2).reduce((e,t)=>e*t),r=bc(vo(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),a=[],s=[];r.forEach(e=>{const[n,r]=wd(e,t);a.push(n),s.push(r)});return[vo(ec(a,0),e.shape),vo(ec(s,0),e.shape)]}}});var Id,Nd;(Nd=Id||(Id={}))[Nd.NONE=0]="NONE",Nd[Nd.MEAN=1]="MEAN",Nd[Nd.SUM=2]="SUM",Nd[Nd.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS";const Sd=/* @__PURE__ */Aa({computeWeightedLoss_:function(e,t,n=Id.SUM_BY_NONZERO_WEIGHTS){const r=Ea(e,"losses","computeWeightedLoss");let a=null;null!=t&&(a=Ea(t,"weights","computeWeightedLoss"));const s=null==a?r:Gs(r,a);if(n===Id.NONE)return s;if(n===Id.SUM)return Oi(s);if(n===Id.MEAN){if(null==a)return ku(s);{const e=r.size/a.size,t=Us(Oi(s),Oi(a));return e>1?Us(t,Ri(e)):t}}if(n===Id.SUM_BY_NONZERO_WEIGHTS){if(null==a)return Us(Oi(s),Ri(r.size));{const e=Gs(a,Nu(r.shape)),t=Ls(Oi(Au(e,Ri(0))),"float32");return Us(Oi(s),t)}}throw Error(`Unknown reduction: ${n}`)}});const Td=/* @__PURE__ */Aa({absoluteDifference_:function(e,t,n,r=Id.SUM_BY_NONZERO_WEIGHTS){const a=Ea(e,"labels","absoluteDifference"),s=Ea(t,"predictions","absoluteDifference");let o=null;null!=n&&(o=Ea(n,"weights","absoluteDifference")),u(a.shape,s.shape,"Error in absoluteDifference: ");const i=Hs(uu(a,s));return Sd(i,o,r)}});const Cd=/* @__PURE__ */Aa({cosineDistance_:function(e,t,n,r,a=Id.SUM_BY_NONZERO_WEIGHTS){const s=Ea(e,"labels","cosineDistance"),o=Ea(t,"predictions","cosineDistance");let i=null;null!=r&&(i=Ea(r,"weights","cosineDistance")),u(s.shape,o.shape,"Error in cosineDistance: ");const l=Ri(1),c=uu(l,Oi(Gs(s,o),n,!0));return Sd(c,i,a)}});const $d=/* @__PURE__ */Aa({hingeLoss_:function(e,t,n,r=Id.SUM_BY_NONZERO_WEIGHTS){let a=Ea(e,"labels","hingeLoss");const s=Ea(t,"predictions","hingeLoss");let o=null;null!=n&&(o=Ea(n,"weights","hingeLoss")),u(a.shape,s.shape,"Error in hingeLoss: ");const i=Ri(1);a=uu(Gs(Ri(2),a),i);const l=Cl(uu(i,Gs(a,s)));return Sd(l,o,r)}});const Ed=/* @__PURE__ */Aa({huberLoss_:function(e,t,n,r=1,a=Id.SUM_BY_NONZERO_WEIGHTS){const s=Ea(e,"labels","huberLoss"),o=Ea(t,"predictions","huberLoss");let i=null;null!=n&&(i=Ea(n,"weights","huberLoss")),u(s.shape,o.shape,"Error in huberLoss: ");const l=Ri(r),c=Hs(uu(o,s)),d=Tu(c,l),p=uu(c,d),h=Ws(Gs(Ri(.5),Ai(d)),Gs(l,p));return Sd(h,i,a)}});const Rd=/* @__PURE__ */Aa({logLoss_:function(e,t,n,r=1e-7,a=Id.SUM_BY_NONZERO_WEIGHTS){const s=Ea(e,"labels","logLoss"),o=Ea(t,"predictions","logLoss");let i=null;null!=n&&(i=Ea(n,"weights","logLoss")),u(s.shape,o.shape,"Error in logLoss: ");const l=Ri(1),c=Ri(r),d=su(Gs(s,tu(Ws(o,c)))),p=Gs(uu(l,s),tu(Ws(uu(l,o),c))),h=uu(d,p);return Sd(h,i,a)}});const _d=/* @__PURE__ */Aa({meanSquaredError_:function(e,t,n,r=Id.SUM_BY_NONZERO_WEIGHTS){const a=Ea(e,"labels","meanSquaredError"),s=Ea(t,"predictions","meanSquaredError");let o=null;null!=n&&(o=Ea(n,"weights","meanSquaredError")),u(a.shape,s.shape,"Error in meanSquaredError: ");const i=Zl(a,s);return Sd(i,o,r)}});const Ad=/* @__PURE__ */Aa({sigmoidCrossEntropy_:function(e,t,n,r=0,a=Id.SUM_BY_NONZERO_WEIGHTS){let s=Ea(e,"multiClassLabels","sigmoidCrossEntropy");const o=Ea(t,"logits","sigmoidCrossEntropy");let i=null;if(null!=n&&(i=Ea(n,"weights","sigmoidCrossEntropy")),u(s.shape,o.shape,"Error in sigmoidCrossEntropy: "),r>0){const e=Ri(r),t=Ri(1),n=Ri(.5);s=Ws(Gs(s,uu(t,e)),Gs(n,e))}const l=function(e,t){const n=Ea(e,"labels","sigmoidCrossEntropyWithLogits"),r=Ea(t,"logits","sigmoidCrossEntropyWithLogits");u(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");const a=Cl(r),s=Gs(r,n),o=nu(Pi(su(Hs(r))));return Ws(uu(a,s),o)}(s,o);return Sd(l,i,a)}});const Od=/* @__PURE__ */Aa({softmaxCrossEntropy_:function(e,t,n,r=0,a=Id.SUM_BY_NONZERO_WEIGHTS){let s=Ea(e,"onehotLabels","softmaxCrossEntropy");const o=Ea(t,"logits","softmaxCrossEntropy");let i=null;if(null!=n&&(i=Ea(n,"weights","softmaxCrossEntropy")),u(s.shape,o.shape,"Error in softmaxCrossEntropy: "),r>0){const e=Ri(r),t=Ri(1),n=Ri(s.shape[1]);s=Ws(Gs(s,uu(t,e)),Us(e,n))}const l=function(e,t,n=-1){if(-1===n&&(n=t.rank-1),n!==t.rank-1)throw Error(`Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank ${t.rank} and dim was ${n}`);return au((e,t,r)=>{const a=cu(t,[n],!0),s=uu(Ls(t,"float32"),a);r([e,s]);const o=su(Gs(s,e));return{value:Oi(o,[n]),gradFunc:(e,t)=>{const[r,a]=t,s=ki(e.shape,[n]);return[Gs(vo(e,s),uu(Ls(r,"float32"),Pi(a))),Gs(vo(e,s),uu(Pi(a),Ls(r,"float32")))]}}})(e,t)}(s,o);return Sd(l,i,a)}});const Fd={fft:ql,ifft:Kl,rfft:Ql,irfft:Xl},Dd={hammingWindow:Gc,hannWindow:Hc,frame:jc,stft:qc},Md={flipLeftRight:Xc,grayscaleToRGB:Yc,resizeNearestNeighbor:gd,resizeBilinear:md,rgbToGrayscale:Qc,rotateWithOffset:Zc,cropAndResize:Kc,nonMaxSuppression:ed,nonMaxSuppressionAsync:cd,nonMaxSuppressionWithScore:dd,nonMaxSuppressionWithScoreAsync:pd,nonMaxSuppressionPadded:hd,nonMaxSuppressionPaddedAsync:fd,threshold:yd,transform:bd},Pd={bandPart:xd,gramSchmidt:vd,qr:kd},Ld={absoluteDifference:Td,computeWeightedLoss:Sd,cosineDistance:Cd,hingeLoss:$d,huberLoss:Ed,logLoss:Rd,meanSquaredError:_d,sigmoidCrossEntropy:Ad,softmaxCrossEntropy:Od},Bd={sparseFillEmptyRows:/* @__PURE__ */Aa({sparseFillEmptyRows_:function(e,t,n,r){const a=Ea(e,"indices","sparseFillEmptyRows","int32"),s=Ea(t,"values","sparseFillEmptyRows"),o=Ea(n,"denseShape","sparseFillEmptyRows","int32"),i=Ea(r,"defaultValue","sparseFillEmptyRows",s.dtype);if(2!==a.rank)throw new Error(`Indices should be Tensor2D but received shape\n ${a.shape}`);if(1!==s.rank)throw new Error(`Values should be Tensor1D but received shape ${s.shape}`);if(1!==o.rank)throw new Error(`Dense shape should be Tensor1D but received shape ${o.shape}`);if(0!==i.rank)throw new Error(`Default value should be a scalar but received shape ${i.shape}`);const u={indices:a,values:s,denseShape:o,defaultValue:i},l=wa.runKernel($n,u);return{outputIndices:l[0],outputValues:l[1],emptyRowIndicator:l[2],reverseIndexMap:l[3]}}}),sparseReshape:/* @__PURE__ */Aa({sparseReshape_:function(e,t,n){const r=Ea(e,"inputIndices","sparseReshape","int32"),a=Ea(t,"inputShape","sparseReshape","int32"),s=Ea(n,"newShape","sparseReshape","int32");if(2!==r.rank)throw new Error(`Input indices should be Tensor2D but received shape\n ${r.shape}`);if(1!==a.rank)throw new Error(`Input shape should be Tensor1D but received shape ${a.shape}`);if(1!==s.rank)throw new Error(`New shape should be Tensor1D but received shape ${s.shape}`);const o={inputIndices:r,inputShape:a,newShape:s},i=wa.runKernel(En,o);return{outputIndices:i[0],outputShape:i[1]}}}),sparseSegmentMean:/* @__PURE__ */Aa({sparseSegmentMean_:function(e,t,n){const r=Ea(e,"data","sparseSegmentMean"),a=Ea(t,"indices","sparseSegmentMean","int32"),s=Ea(n,"segmentIds","sparseSegmentMean","int32");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==a.rank)throw new Error(`Indices should be Tensor1D but received shape\n ${a.shape}`);if(1!==s.rank)throw new Error(`Segment ids should be Tensor1D but received shape\n ${s.shape}`);const o={data:r,indices:a,segmentIds:s};return wa.runKernel(Rn,o)}}),sparseSegmentSum:/* @__PURE__ */Aa({sparseSegmentSum_:function(e,t,n){const r=Ea(e,"data","sparseSegmentSum"),a=Ea(t,"indices","sparseSegmentSum","int32"),s=Ea(n,"segmentIds","sparseSegmentSum","int32");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==a.rank)throw new Error(`Indices should be Tensor1D but received shape\n ${a.shape}`);if(1!==s.rank)throw new Error(`Segment ids should be Tensor1D but received shape\n ${s.shape}`);const o={data:r,indices:a,segmentIds:s};return wa.runKernel(_n,o)}})},Vd={stringNGrams:/* @__PURE__ */Aa({stringNGrams_:function(e,t,n,r,a,s,o,i){const u=Ea(e,"data","stringNGrams","string");if("string"!==u.dtype)throw new Error("Data must be of datatype string");if(1!==u.shape.length)throw new Error(`Data must be a vector, saw: ${u.shape}`);const l=Ea(t,"dataSplits","stringNGrams");if("int32"!==l.dtype)throw new Error("Data splits must be of datatype int32");const c={separator:n,nGramWidths:r,leftPad:a,rightPad:s,padWidth:o,preserveShortSequences:i},d={data:u,dataSplits:l},p=wa.runKernel(Pn,d,c);return{nGrams:p[0],nGramsSplits:p[1]}}}),stringSplit:/* @__PURE__ */Aa({stringSplit_:function(e,t,n=!0){const r=Ea(e,"input","stringSplit","string"),a=Ea(t,"delimiter","stringSplit","string");if(1!==r.rank)throw new Error(`Input should be Tensor1D but received shape ${r.shape}`);if(0!==a.rank)throw new Error(`Delimiter should be a scalar but received shape ${a.shape}`);const s={skipEmpty:n},o={input:r,delimiter:a},i=wa.runKernel(Ln,o,s);return{indices:i[0],values:i[1],shape:i[2]}}}),stringToHashBucketFast:/* @__PURE__ */Aa({stringToHashBucketFast_:function(e,t){const n=Ea(e,"input","stringToHashBucketFast","string"),r={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");const a={input:n};return wa.runKernel(Bn,a,r)}}),staticRegexReplace:/* @__PURE__ */Aa({staticRegexReplace_:function(e,t,n,r=!0){const a=Ea(e,"input","staticRegexReplace","string"),s={pattern:t,rewrite:n,replaceGlobal:r};return wa.runKernel(Dn,{x:a},s)}})},Wd=/* @__PURE__ */new Map,zd=/* @__PURE__ */new Map;class Ud{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}}class Gd{constructor(){this.classNameMap={}}static getMap(){return null==Gd.instance&&(Gd.instance=new Gd),Gd.instance}static register(e){Gd.getMap().classNameMap[e.className]=[e,e.fromConfig]}}function Hd(e,t,n){i(null!=e.className,()=>"Class being registered does not have the static className property defined."),i("string"===typeof e.className,()=>"className is required to be a string, but got type "+typeof e.className),i(e.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),"undefined"===typeof t&&(t="Custom"),"undefined"===typeof n&&(n=e.className);const r=t+">"+n;return Gd.register(e),Wd.set(r,e),zd.set(e,r),e}class jd extends Ud{minimize(e,t=!1,n){const{value:r,grads:a}=this.computeGradients(e,n);if(null!=n){const e=n.map(e=>({name:e.name,tensor:a[e.name]}));this.applyGradients(e)}else this.applyGradients(a);return Va(a),t?r:(r.dispose(),null)}get iterations(){return null==this.iterations_&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return ru(e,t)}dispose(){null!=this.iterations_&&Va(this.iterations_)}async saveIterations(){return null==this.iterations_&&(this.iterations_=0),{name:"iter",tensor:Ri(this.iterations_,"int32")}}async getWeights(){throw new Error("getWeights() is not implemented for this optimizer yet.")}async setWeights(e){throw new Error(`setWeights() is not implemented for this optimizer class ${this.getClassName()}`)}async extractIterations(e){return this.iterations_=(await e[0].tensor.data())[0],e.slice(1)}}Object.defineProperty(jd,Symbol.hasInstance,{value:e=>null!=e.minimize&&null!=e.computeGradients&&null!=e.applyGradients});class qd extends jd{static get className(){return"Adadelta"}constructor(e,t,n=null){super(),this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],null==n&&(this.epsilon=wa.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(e=>e.name):Object.keys(e)).forEach((t,n)=>{const r=wa.registeredVariables[t],a=!1;null==this.accumulatedGrads[n]&&(this.accumulatedGrads[n]={originalName:`${t}/accum_grad`,variable:Ba(()=>pi(r).variable(a))}),null==this.accumulatedUpdates[n]&&(this.accumulatedUpdates[n]={originalName:`${t}/accum_var`,variable:Ba(()=>pi(r).variable(a))});const s=Array.isArray(e)?e[n].tensor:e[t];if(null==s)return;const o=this.accumulatedGrads[n].variable,i=this.accumulatedUpdates[n].variable;Ba(()=>{const e=Ws(Gs(o,this.rho),Gs(Ai(s),1-this.rho)),t=Gs(Us(_i(Ws(i,this.epsilon)),_i(Ws(o,this.epsilon))),s),n=Ws(Gs(i,this.rho),Gs(Ai(t),1-this.rho));o.assign(e),i.assign(n);const a=Ws(Gs(t,-this.learningRate),r);r.assign(a)})}),this.incrementIterations()}dispose(){null!=this.accumulatedUpdates&&(Va(this.accumulatedGrads.map(e=>e.variable)),Va(this.accumulatedUpdates.map(e=>e.variable)))}async getWeights(){const e=[...this.accumulatedGrads,...this.accumulatedUpdates];return[await this.saveIterations()].concat(e.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){const t=(e=await this.extractIterations(e)).length/2,n=!1;this.accumulatedGrads=e.slice(0,t).map(e=>({originalName:e.name,variable:e.tensor.variable(n)})),this.accumulatedUpdates=e.slice(t,2*t).map(e=>({originalName:e.name,variable:e.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}}class Kd extends jd{static get className(){return"Adagrad"}constructor(e,t=.1){super(),this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){(Array.isArray(e)?e.map(e=>e.name):Object.keys(e)).forEach((t,n)=>{const r=wa.registeredVariables[t];if(null==this.accumulatedGrads[n]){const e=!1;this.accumulatedGrads[n]={originalName:`${t}/accumulator`,variable:Ba(()=>Bo(r.shape,this.initialAccumulatorValue).variable(e))}}const a=Array.isArray(e)?e[n].tensor:e[t];if(null==a)return;const s=this.accumulatedGrads[n].variable;Ba(()=>{const e=Ws(s,Ai(a));s.assign(e);const t=Ws(Gs(Us(a,_i(Ws(e,wa.backend.epsilon()))),-this.learningRate),r);r.assign(t)})}),this.incrementIterations()}dispose(){null!=this.accumulatedGrads&&Va(this.accumulatedGrads.map(e=>e.variable))}async getWeights(){return[await this.saveIterations()].concat(this.accumulatedGrads.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);this.accumulatedGrads=e.map(e=>({originalName:e.name,variable:e.tensor.variable(false)}))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}}class Xd extends jd{static get className(){return"Adam"}constructor(e,t,n,r=null){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=r,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],Ba(()=>{this.accBeta1=Ri(t).variable(),this.accBeta2=Ri(n).variable()}),null==r&&(this.epsilon=wa.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(e=>e.name):Object.keys(e);Ba(()=>{const n=uu(1,this.accBeta1),r=uu(1,this.accBeta2);t.forEach((t,a)=>{const s=wa.registeredVariables[t],o=!1;null==this.accumulatedFirstMoment[a]&&(this.accumulatedFirstMoment[a]={originalName:`${t}/m`,variable:Ba(()=>pi(s).variable(o))}),null==this.accumulatedSecondMoment[a]&&(this.accumulatedSecondMoment[a]={originalName:`${t}/v`,variable:Ba(()=>pi(s).variable(o))});const i=Array.isArray(e)?e[a].tensor:e[t];if(null==i)return;const u=this.accumulatedFirstMoment[a].variable,l=this.accumulatedSecondMoment[a].variable,c=Ws(Gs(u,this.beta1),Gs(i,1-this.beta1)),d=Ws(Gs(l,this.beta2),Gs(Ai(i),1-this.beta2)),p=Us(c,n),h=Us(d,r);u.assign(c),l.assign(d);const f=Ws(Gs(Us(p,Ws(_i(h),this.epsilon)),-this.learningRate),s);s.assign(f)}),this.accBeta1.assign(Gs(this.accBeta1,this.beta1)),this.accBeta2.assign(Gs(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),null!=this.accumulatedFirstMoment&&Va(this.accumulatedFirstMoment.map(e=>e.variable)),null!=this.accumulatedSecondMoment&&Va(this.accumulatedSecondMoment.map(e=>e.variable))}async getWeights(){const e=[...this.accumulatedFirstMoment,...this.accumulatedSecondMoment];return[await this.saveIterations()].concat(e.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e),Ba(()=>{this.accBeta1.assign(Ei(this.beta1,this.iterations_+1)),this.accBeta2.assign(Ei(this.beta2,this.iterations_+1))});const t=e.length/2,n=!1;this.accumulatedFirstMoment=e.slice(0,t).map(e=>({originalName:e.name,variable:e.tensor.variable(n)})),this.accumulatedSecondMoment=e.slice(t,2*t).map(e=>({originalName:e.name,variable:e.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)}}class Yd extends jd{static get className(){return"Adamax"}constructor(e,t,n,r=null,a=0){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=r,this.decay=a,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],Ba(()=>{this.iteration=Ri(0).variable(),this.accBeta1=Ri(t).variable()}),null==r&&(this.epsilon=wa.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(e=>e.name):Object.keys(e);Ba(()=>{const n=uu(1,this.accBeta1),r=Us(-this.learningRate,Ws(Gs(this.iteration,this.decay),1));t.forEach((t,a)=>{const s=wa.registeredVariables[t],o=!1;null==this.accumulatedFirstMoment[a]&&(this.accumulatedFirstMoment[a]={originalName:`${t}/m`,variable:pi(s).variable(o)}),null==this.accumulatedWeightedInfNorm[a]&&(this.accumulatedWeightedInfNorm[a]={originalName:`${t}/v`,variable:pi(s).variable(o)});const i=Array.isArray(e)?e[a].tensor:e[t];if(null==i)return;const u=this.accumulatedFirstMoment[a].variable,l=this.accumulatedWeightedInfNorm[a].variable,c=Ws(Gs(u,this.beta1),Gs(i,1-this.beta1)),d=Gs(l,this.beta2),p=Hs(i),h=wu(d,p);u.assign(c),l.assign(h);const f=Ws(Gs(Us(r,n),Us(c,Ws(h,this.epsilon))),s);s.assign(f)}),this.iteration.assign(Ws(this.iteration,1)),this.accBeta1.assign(Gs(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),null!=this.accumulatedFirstMoment&&Va(this.accumulatedFirstMoment.map(e=>e.variable)),null!=this.accumulatedWeightedInfNorm&&Va(this.accumulatedWeightedInfNorm.map(e=>e.variable))}async getWeights(){throw new Error("getWeights() is not implemented for Adamax yet.")}async setWeights(e){throw new Error("setWeights() is not implemented for Adamax yet.")}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon,t.decay)}}class Qd extends jd{static get className(){return"SGD"}constructor(e){super(),this.learningRate=e,this.setLearningRate(e)}applyGradients(e){(Array.isArray(e)?e.map(e=>e.name):Object.keys(e)).forEach((t,n)=>{const r=Array.isArray(e)?e[n].tensor:e[t];if(null==r)return;const a=wa.registeredVariables[t];Ba(()=>{const e=Ws(Gs(this.c,r),a);a.assign(e)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,null!=this.c&&this.c.dispose(),this.c=Wa(Ri(-e))}dispose(){this.c.dispose()}async getWeights(){return[await this.saveIterations()]}async setWeights(e){if(0!==(e=await this.extractIterations(e)).length)throw new Error("SGD optimizer does not have settable weights.")}getConfig(){return{learningRate:this.learningRate}}static fromConfig(e,t){return new e(t.learningRate)}}class Zd extends Qd{static get className(){return"Momentum"}constructor(e,t,n=!1){super(e),this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=Ri(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(e=>e.name):Object.keys(e)).forEach((t,n)=>{const r=wa.registeredVariables[t];if(null==this.accumulations[n]){const e=!1;this.accumulations[n]={originalName:`${t}/momentum`,variable:Ba(()=>pi(r).variable(e))}}const a=this.accumulations[n].variable,s=Array.isArray(e)?e[n].tensor:e[t];null!=s&&Ba(()=>{let e;const t=Ws(Gs(this.m,a),s);e=this.useNesterov?Ws(Gs(this.c,Ws(s,Gs(t,this.m))),r):Ws(Gs(this.c,t),r),a.assign(t),r.assign(e)})}),this.incrementIterations()}dispose(){this.m.dispose(),null!=this.accumulations&&Va(this.accumulations.map(e=>e.variable))}setMomentum(e){this.momentum=e}async getWeights(){return[await this.saveIterations()].concat(this.accumulations.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);this.accumulations=e.map(e=>({originalName:e.name,variable:e.tensor.variable(false)}))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)}}class Jd extends jd{static get className(){return"RMSProp"}constructor(e,t=.9,n=0,r=null,a=!1){if(super(),this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=r,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=a,null==r&&(this.epsilon=wa.backend.epsilon()),null==e)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map(e=>e.name):Object.keys(e)).forEach((t,n)=>{const r=wa.registeredVariables[t],a=!1;null==this.accumulatedMeanSquares[n]&&(this.accumulatedMeanSquares[n]={originalName:`${t}/rms`,variable:Ba(()=>pi(r).variable(a))}),null==this.accumulatedMoments[n]&&(this.accumulatedMoments[n]={originalName:`${t}/momentum`,variable:Ba(()=>pi(r).variable(a))}),null==this.accumulatedMeanGrads[n]&&this.centered&&(this.accumulatedMeanGrads[n]={originalName:`${t}/mg`,variable:Ba(()=>pi(r).variable(a))});const s=Array.isArray(e)?e[n].tensor:e[t];if(null==s)return;const o=this.accumulatedMeanSquares[n].variable,i=this.accumulatedMoments[n].variable;Ba(()=>{const e=Ws(Gs(o,this.decay),Gs(Ai(s),1-this.decay));if(this.centered){const t=this.accumulatedMeanGrads[n].variable,a=Ws(Gs(t,this.decay),Gs(s,1-this.decay)),u=Us(Gs(s,this.learningRate),_i(uu(e,Ws(Ai(a),this.epsilon)))),l=Ws(Gs(i,this.momentum),u);o.assign(e),t.assign(a),i.assign(l);const c=uu(r,l);r.assign(c)}else{const e=Ws(Gs(o,this.decay),Gs(Ai(s),1-this.decay)),t=Ws(Gs(i,this.momentum),Us(Gs(s,this.learningRate),_i(Ws(e,this.epsilon))));o.assign(e),i.assign(t);const n=uu(r,t);r.assign(n)}})}),this.incrementIterations()}dispose(){null!=this.accumulatedMeanSquares&&Va(this.accumulatedMeanSquares.map(e=>e.variable)),null!=this.accumulatedMeanGrads&&this.centered&&Va(this.accumulatedMeanGrads.map(e=>e.variable)),null!=this.accumulatedMoments&&Va(this.accumulatedMoments.map(e=>e.variable))}async getWeights(){const e=[...this.accumulatedMeanSquares,...this.accumulatedMoments];return this.centered&&e.push(...this.accumulatedMeanGrads),[await this.saveIterations()].concat(e.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);const t=this.centered?e.length/3:e.length/2,n=!1;this.accumulatedMeanSquares=e.slice(0,t).map(e=>({originalName:e.name,variable:e.tensor.variable(n)})),this.accumulatedMoments=e.slice(t,2*t).map(e=>({originalName:e.name,variable:e.tensor.variable(n)})),this.centered&&(this.accumulatedMeanGrads=e.slice(2*t,3*t).map(e=>({originalName:e.name,variable:e.tensor.variable(n)})))}getConfig(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}}static fromConfig(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)}}const ep=[qd,Kd,Xd,Yd,Zd,Jd,Qd];function tp(e){return new Promise(e=>setTimeout(e)).then(e)}class np{constructor(e){if(!V().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(np.URL_SCHEME)&&(e=e.slice(np.URL_SCHEME.length)),null!=e&&0!==e.length||(e="model"),this.modelJsonFileName=e+".json",this.weightDataFileName=e+".weights.bin"}async save(e){if("undefined"===typeof document)throw new Error("Browser downloads are not supported in this environment since `document` is not present");const t=Pa.join(e.weightData),n=window.URL.createObjectURL(new Blob([t],{type:"application/octet-stream"}));if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");{const t=ns(e,[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}]),r=window.URL.createObjectURL(new Blob([JSON.stringify(t)],{type:"application/json"})),a=null==this.modelJsonAnchor?document.createElement("a"):this.modelJsonAnchor;if(a.download=this.modelJsonFileName,a.href=r,await tp(()=>a.dispatchEvent(new MouseEvent("click"))),null!=e.weightData){const e=null==this.weightDataAnchor?document.createElement("a"):this.weightDataAnchor;e.download=this.weightDataFileName,e.href=n,await tp(()=>e.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:ss(e)}}}}np.URL_SCHEME="downloads://";class rp{constructor(e){if(null==e||e.length<1)throw new Error(`When calling browserFiles, at least 1 file is required, but received ${e}`);this.jsonFile=e[0],this.weightsFiles=e.slice(1)}async load(){return new Promise((e,t)=>{const n=new FileReader;n.onload=n=>{const r=JSON.parse(n.target.result),a=r.modelTopology;if(null==a)return void t(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`));if(null==r.weightsManifest)return void t(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`));if(0===this.weightsFiles.length)return void e({modelTopology:a});const s=as(r,e=>this.loadWeights(e));e(s)},n.onerror=e=>t(`Failed to read model topology and weights manifest JSON from file '${this.jsonFile.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),n.readAsText(this.jsonFile)})}loadWeights(e){const t=[],n=[];for(const s of e)t.push(...s.weights),n.push(...s.paths);const r=this.checkManifestAndWeightFiles(e),a=n.map(e=>this.loadWeightsFile(e,r[e]));return Promise.all(a).then(e=>[t,e])}loadWeightsFile(e,t){return new Promise((n,r)=>{const a=new FileReader;a.onload=e=>{const t=e.target.result;n(t)},a.onerror=t=>r(`Failed to weights data from file of path '${e}'.`),a.readAsArrayBuffer(t)})}checkManifestAndWeightFiles(e){const t=[],n=this.weightsFiles.map(e=>ts(e.name)),r={};for(const a of e)a.paths.forEach(e=>{const a=ts(e);if(-1!==t.indexOf(a))throw new Error(`Duplicate file basename found in weights manifest: '${a}'`);if(t.push(a),-1===n.indexOf(a))throw new Error(`Weight file with basename '${a}' is not provided.`);r[e]=this.weightsFiles[n.indexOf(a)]});if(t.length!==this.weightsFiles.length)throw new Error(`Mismatch in the number of files in weights manifest (${t.length}) and the number of weight files provided (${this.weightsFiles.length}).`);return r}}function ap(e,t,n,r){var a,s,o;i(null!=(a=e)&&Array.isArray(a)&&a.length>0,()=>"promises must be a none empty array"),o=r=r??1,i((s=n=n??0)>=0&&s<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${s}`),i(o>=0&&o<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${o}`),i(o>=s,()=>`startFraction must be no more than endFraction, but got startFraction ${s} and endFraction ${o}`);let u=0;return Promise.all(e.map(a=>(a.then(a=>{const s=n+ ++u/e.length*(r-n);return t(s),a}),a)))}async function sp(e,t){null==t&&(t={});const n=null==t.fetchFunc?V().platform.fetch:t.fetchFunc,r=e.map(e=>n(e,t.requestInit,{isBinary:!0})),a=(null==t.onProgress?await Promise.all(r):await ap(r,t.onProgress,0,.5)).map(e=>e.arrayBuffer());return null==t.onProgress?await Promise.all(a):await ap(a,t.onProgress,.5,1)}function op(e){return async(t,n="",r)=>{const a=t.map(()=>!1),s={},o=null!=r?r.map(()=>!1):[],i=[];if(t.forEach((e,t)=>{let n=0;e.weights.forEach(e=>{const u="quantization"in e?e.quantization.dtype:e.dtype,l=Ma[u]*c(e.shape),d=()=>{a[t]=!0,null==s[t]&&(s[t]=[]),s[t].push({manifestEntry:e,groupOffset:n,sizeBytes:l})};null!=r?r.forEach((t,n)=>{t===e.name&&(d(),o[n]=!0)}):d(),i.push(e.name),n+=l})}),!o.every(e=>e)){const e=r.filter((e,t)=>!o[t]);throw new Error(`Could not find weights in manifest with names: ${e.join(", ")}. \nManifest JSON has weights with names: ${i.join(", ")}.`)}const u=a.reduce((e,t,n)=>(t&&e.push(n),e),[]),l=[];u.forEach(e=>{t[e].paths.forEach(e=>{const t=n+(n.endsWith("/")?"":"/")+e;l.push(t)})});const d=await e(l),p={};let h=0;return u.forEach(e=>{const n=t[e].paths.length,r=new Pa(d.slice(h,h+n));s[e].forEach(e=>{const t=ja(r.slice(e.groupOffset,e.groupOffset+e.sizeBytes),[e.manifestEntry]);for(const n in t)p[n]=t[n]}),h+=n}),p}}is.registerSaveRouter(e=>V().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(np.URL_SCHEME)?function(e="model"){return new np(e)}(e.slice(np.URL_SCHEME.length)):null);class ip{constructor(e,t){if(this.DEFAULT_METHOD="POST",null==t&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.weightUrlConverter=t.weightUrlConverter,null!=t.fetchFunc?(i("function"===typeof t.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=t.fetchFunc):this.fetch=V().platform.fetch,i(null!=e&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&i(2===e.length,()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`),this.path=e,null!=t.requestInit&&null!=t.requestInit.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{},this.loadOptions=t}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");const t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;const n=ns(e,[{paths:["./model.weights.bin"],weights:e.weightSpecs}]);if(t.body.append("model.json",new Blob([JSON.stringify(n)],{type:"application/json"}),"model.json"),null!=e.weightData){const n=Pa.join(e.weightData);t.body.append("model.weights.bin",new Blob([n],{type:"application/octet-stream"}),"model.weights.bin")}const r=await this.fetch(this.path,t);if(r.ok)return{modelArtifactsInfo:ss(e),responses:[r]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${r.status}.`)}async loadModelJSON(){const e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new Error(`Request to ${this.path} failed with status code ${e.status}. Please verify this URL points to the model JSON of the model to load.`);let t;try{t=await e.json()}catch(a){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=t.modelTopology,r=t.weightsManifest;if(null==n&&null==r)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);return t}async load(){if(this.loadOptions.streamWeights)return this.loadStream();return as(await this.loadModelJSON(),e=>this.loadWeights(e))}async loadStream(){const e=await this.loadModelJSON(),t=await this.getWeightUrls(e.weightsManifest),n=os(e.weightsManifest);return Object.assign(Object.assign({},e),{weightSpecs:n,getWeightStream:()=>function(e,t){var n;const r=null==t.fetchFunc?V().platform.fetch:t.fetchFunc;let a,s=0;return null===(n=t.onProgress)||void 0===n||n.call(t,0),new ReadableStream({pull:async n=>{for(var o;st?e.substring(n):"";return[r+"/",a]}(t),a=this.weightPathPrefix||n,s=[],o=[];for(const i of e)for(const e of i.paths)null!=this.weightUrlConverter?o.push(this.weightUrlConverter(e)):s.push(a+e+r);return this.weightUrlConverter&&s.push(...await Promise.all(o)),s}async loadWeights(e){const t=await this.getWeightUrls(e);return[os(e),await sp(t,this.loadOptions)]}}function up(e){return null!=e.match(ip.URL_SCHEME_REGEX)}ip.URL_SCHEME_REGEX=/^https?:\/\//;const lp=(e,t)=>{if("undefined"===typeof fetch&&(null==t||null==t.fetchFunc))return null;{let n=!0;if(n=Array.isArray(e)?e.every(e=>up(e)):up(e),n)return cp(e,t)}return null};function cp(e,t){return new ip(e,t)}is.registerSaveRouter(lp),is.registerLoadRouter(lp);class dp{constructor(e){this.modelArtifacts=e}load(){return this.modelArtifacts}}class pp{constructor(e){this.saveHandler=e}save(e){return this.saveHandler(e)}}class hp{constructor(e){e.load&&(this.load=()=>Promise.resolve(e.load())),e.save&&(this.save=t=>Promise.resolve(e.save(t)))}}function fp(e,t,n,r){if(1===arguments.length){return null!=e.modelTopology||null!=e.weightSpecs?new dp(e):(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 dp({modelTopology:e}))}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 dp({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:r})}const mp=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,CompositeArrayBuffer:Pa,browserFiles:function(e){return new rp(e)},browserHTTPRequest:function(e,t){return cp(e,t)},concatenateArrayBuffers:function(e){return Pa.join(e)},copyModel:async function(e,t){return As(e,t,!1)},decodeWeights:ja,decodeWeightsStream:Qa,encodeWeights:async function(e,t){const n=[],r=[],a=Array.isArray(e)?e.map(e=>e.name):Object.keys(e);for(let s=0;s{const t=await i.bytes(),n=t.reduce((e,t)=>e+t.length,0)+4*t.length,r=new Uint8Array(n);let a=0;for(let s=0;sis.getLoadHandlers(e,t),getModelArtifactsForJSON:as,getModelArtifactsForJSONSync:rs,getModelArtifactsInfoForJSON:ss,getSaveHandlers:e=>is.getSaveHandlers(e),getWeightSpecs:os,http:cp,isHTTPScheme:up,listModels:async function(){const e=Rs.getSchemes(),t={};for(const n of e){const e=await Rs.getManager(n).listModels();for(const r in e){t[n+Es+r]=e[r]}}return t},loadWeights:async function(e,t="",n,r){return op(e=>sp(e,{requestInit:r}))(e,t,n)},moveModel:async function(e,t){return As(e,t,!0)},registerLoadRouter:e=>is.registerLoadRouter(e),registerSaveRouter:e=>is.registerSaveRouter(e),removeModel:async function(e){const t=_s(e);return Rs.getManager(t.scheme).removeModel(t.path)},weightsLoaderFactory:op,withSaveHandler:function(e){return new pp(e)},withSaveHandlerSync:function(e){return new pp(e)}},Symbol.toStringTag,{value:"Module"}));let gp,yp=!1;async function bp(e,t){let n=Ea(e,"img","toPixels");if(!(e instanceof Yr)){const e=n;n=Ls(e,"int32"),e.dispose()}!function(e){if(2!==e.rank&&3!==e.rank)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${e.rank}.`);const t=2===e.rank?1:e.shape[2];if(t>4||2===t)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${t}`);if("float32"!==e.dtype&&"int32"!==e.dtype)throw new Error(`Unsupported type for toPixels: ${e.dtype}. Please use float32 or int32 tensors.`)}(n);const[r,a]=n.shape.slice(0,2),s=2===n.rank?1:n.shape[2],o=await n.data(),i="float32"===n.dtype?255:1,u=new Uint8ClampedArray(a*r*4);for(let l=0;l1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${t}.`)}else if("int32"===n.dtype&&(t<0||t>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${t}.`);1===s?(e[0]=t*i,e[1]=t*i,e[2]=t*i):e[r]=t*i}const t=4*l;u[t+0]=Math.round(e[0]),u[t+1]=Math.round(e[1]),u[t+2]=Math.round(e[2]),u[t+3]=Math.round(e[3])}if(null!=t){if(!yp){null!=or(Ve,wa.backendName)&&(console.warn("tf.browser.toPixels is not efficient to draw tensor on canvas. Please try tf.browser.draw instead."),yp=!0)}t.width=a,t.height=r;const e=t.getContext("2d"),n=new ImageData(u,a,r);e.putImageData(n,0,0)}return n!==e&&n.dispose(),u}const xp=/* @__PURE__ */Aa({fromPixels_:function(e,t=3){if(t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(null==e)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let n=!1,r=!1,a=!1,s=!1,o=!1,i=!1;if(e.data instanceof Uint8Array)n=!0;else if("undefined"!==typeof ImageData&&e instanceof ImageData)r=!0;else if("undefined"!==typeof HTMLVideoElement&&e instanceof HTMLVideoElement)a=!0;else if("undefined"!==typeof HTMLImageElement&&e instanceof HTMLImageElement)s=!0;else if(null!=e.getContext)o=!0;else{if(!("undefined"!==typeof ImageBitmap&&e instanceof ImageBitmap))throw new Error(`pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was ${e.constructor.name}`);i=!0}if(null!=or(Zn,wa.backendName)){const n={pixels:e},r={numChannels:t};return wa.runKernel(Zn,n,r)}const[u,l]=a?[e.videoWidth,e.videoHeight]:[e.width,e.height];let c,d;if(o)c=e.getContext("2d").getImageData(0,0,u,l).data;else if(r||n)c=e.data;else if(s||a||i){if(null==gp)if("undefined"===typeof document){if("undefined"===typeof OffscreenCanvas||"undefined"===typeof OffscreenCanvasRenderingContext2D)throw new Error("Cannot parse input in current context. Reason: OffscreenCanvas Context2D rendering is not supported.");gp=new OffscreenCanvas(1,1).getContext("2d")}else gp=document.createElement("canvas").getContext("2d",{willReadFrequently:!0});gp.canvas.width=u,gp.canvas.height=l,gp.drawImage(e,0,0,u,l),c=gp.getImageData(0,0,u,l).data}if(4===t)d=new Int32Array(c);else{const e=u*l;d=new Int32Array(e*t);for(let n=0;nn)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[r-1]} vs. ${n}`);if(0===c(e.shape))throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);const a=t.shape,s=a[a.length-1];let o=1;for(let c=0;ce/l),1].slice(0,s);return[u,o,l,d]}function wp(e,t,n){const r=e.shape.length;i(r===t.length,()=>`Error in slice${r}D: Length of begin ${t} must match the rank of the array (${r}).`),i(r===n.length,()=>`Error in slice${r}D: Length of size ${n} must match the rank of the array (${r}).`);for(let a=0;a`Error in slice${r}D: begin[${a}] + size[${a}] (${t[a]+n[a]}) would overflow input.shape[${a}] (${e.shape[a]})`)}function kp(e,t,n){const r=[];for(let a=0;a1){r=a;break}for(let a=r+1;a0||n[a]!==e[a])return!1;return!0}function Np(e,t){let n=e.length>0?e[e.length-1]:1;for(let r=0;r{i(-1!==e,()=>"slice() does not support negative begin indexing.")}),s=null==n?new Array(a).fill(-1):"number"===typeof n?[n,...new Array(a-1).fill(-1)]:n.lengtht>=0?t:(i(-1===t,()=>`Negative size values should be exactly -1 but got ${t} for the slice() size at index ${n}.`),e.shape[n]-r[n])),[r,s]}function Tp(e,t,n,r,a,s,o,i,u){let l;if(null==r?(l=new Array(t.length),l.fill(1)):l=r,null!=o&&0!==(o&o-1))throw new Error("Multiple ellipses in slice is not allowed.");let c=!1;const d={dims:l.length,numAddAxisAfterEllipsis:0,begin:t.slice(),end:n.slice(),strides:l.slice(),beginMask:a,endMask:s,ellipsisMask:o,newAxisMask:i,shrinkAxisMask:u};for(let b=0;b0?0:-1,p.strides[b]>0?n:n-1];if(t&&p.strides[b]<=0)throw Error("only stride 1 allowed on non-range indexing.");m=m&&1===p.strides[b];const s=!!(p.beginMask&1<=n)throw Error(`slice index ${p.begin[b]} of dimension ${b} out of bounds.`)}else p.begin[b]=Cp(p.begin[b],0,p.strides[b],n,r,a),p.end[b]=Cp(p.end[b],1,p.strides[b],n,r,a);const e=1===p.strides[b]&&0===p.begin[b]&&p.end[b]===n;h=h&&e,f=f&&(0===b&&1===p.strides[b]||e)}else h=h&&1===p.strides[b]&&s,f=f&&(0===b&&1===p.strides[b]||s);let o,i=!1;if(p.beginValid&&p.endValid?(o=p.end[b]-p.begin[b],i=!0):t?(o=1,i=!0):s&&n>=0&&(o=p.strides[b]<0?-n:n,i=!0),i){let e;e=0===o||o<0!==p.strides[b]<0?0:Math.trunc(o/p.strides[b])+(o%p.strides[b]!==0?1:0),g.push(e)}else g.push(-1)}for(let b=0;b=0?y.push(g[e]):-2===e&&y.push(1)}return{finalShapeSparse:y.filter((e,t)=>-2!==p.finalShapeGatherIndices[t]),finalShape:y,isIdentity:h,sliceDim0:f,isSimpleSlice:m,begin:p.begin,end:p.end,strides:p.strides}}function Cp(e,t,n,r,a,s){if(a[t])return n>0?s[t]:s[t+1&1];{const t=e<0?r+e:e;return ts[1]?s[1]:t}}const $p="undefined"!==typeof requestAnimationFrame?requestAnimationFrame:"undefined"!==typeof setImmediate?setImmediate:e=>e();function Ep(){return new Promise(e=>$p(()=>e()))}function Rp(e,t){const n=e[0].length;e.forEach((e,t)=>{i(e.length===n,()=>`Error in concat${n}D: rank of tensors[${t}] must be the same as the rank of the rest (${n})`)}),i(t>=0&&t`Error in concat${n}D: axis must be between 0 and ${n-1}.`);const r=e[0];e.forEach((e,a)=>{for(let s=0;s`Error in concat${n}D: Shape of tensors[${a}] (${e}) does not match the shape of the rest (${r}) along the non-concatenated axis ${a}.`)})}function _p(e,t){const n=e[0].slice();for(let r=1;r=0)if(i>=0){if(i!==s)throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.shape[${a+e}] = ${s} but shape[${a+e}] = ${i}`)}else r[o]=s}return r}function Dp(e){const t={FIRST_DIM_SIZE:Ap.FIRST_DIM_SIZE,VALUE_ROWIDS:Ap.VALUE_ROWIDS,ROW_LENGTHS:Ap.ROW_LENGTHS,ROW_SPLITS:Ap.ROW_SPLITS,ROW_LIMITS:Ap.ROW_LIMITS,ROW_STARTS:Ap.ROW_STARTS},n=[];for(const r of e){if(!(r in t))break;n.push(t[r])}return n}function Mp(e){return 0===e.length?0:e[0]===Ap.FIRST_DIM_SIZE?e.length-1:e.length}function Pp(e,t){if(null==e||null==t)return;const n=e.length,r=t.length;if(n>=r)throw new Error(`defaultValue.shape=${e} and ragged tensor flatValues.shape=${t}, are incompatible: defaultValue.rank = ${n} must be less than ragged tensor input flatValues.rank = ${r})`);for(let a=0;a=0&&r>=0&&1!==n&&n!==r)throw new Error(`defaultValue.shape=${e}, and ragged tensor input flatValues.shape=${t} are incompatible: defaultValue.shape[${a-e.length}] = ${n} but ragged tensor input.flatValues.shape[${a-e.length}] = ${r}`)}}(Op=Ap||(Ap={}))[Op.FIRST_DIM_SIZE=0]="FIRST_DIM_SIZE",Op[Op.VALUE_ROWIDS=1]="VALUE_ROWIDS",Op[Op.ROW_LENGTHS=2]="ROW_LENGTHS",Op[Op.ROW_SPLITS=3]="ROW_SPLITS",Op[Op.ROW_LIMITS=4]="ROW_LIMITS",Op[Op.ROW_STARTS=5]="ROW_STARTS";function Lp(e){return e<=30?e:T(e,Math.floor(Math.sqrt(e)))}function Bp(e,t,n){return[n*("number"===typeof e?e:e[0]),t*("number"===typeof e?e:e[1])]}function Vp(e,t,n,r=!0){let a=[];if(r)a=a.concat(t.slice(0)),a.push(e[0]/n),a=a.concat(e.slice(1));else{a=a.concat(e[0]);const n=t.length;for(let r=0;r=2*t+1||r%2===1?a.push(r):n.push(r);r.push(...n),r.push(0),r.push(...a)}return r}function zp(e,t,n,r=!0){const a=[];r?a.push(e[0]/n):a.push(e[0]*n);for(let s=1;s/g;function lh(e,t){const n=((e=e.replace(/\s/g,"")).length-e.replace(uh,"").length)/2;if(n<1)throw new Error("Equations without an arrow are not supported.");if(n>1)throw new Error(`Equation must contain exactly one arrow ("${ih}").`);const[r,a]=e.split(ih);i(-1===r.indexOf("..."),()=>'The ellipsis notation ("...") is not supported yet.');const s=r.split(","),o=s.length;if(t!==o)throw new Error(`Expected ${o} input tensors, received ${t}`);if(o>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");const u=[];for(let i=0;i-1!==t.indexOf(e)))throw new Error(`Output subscripts contain the label ${e} not present in the input subscripts.`);-1===u.indexOf(e)&&u.push(e)}for(let i=0;i-1!==e),{permutationIndices:n,expandDims:r}}function dh(e,t,n){const r=new Array(e);for(let a=0;a`Expected dimension ${r[t[a][n]]} at axis ${n} of input shaped ${JSON.stringify(e)}, but got dimension ${e[n]}`)}}function ph(e,t){const n=e,r=[];let a=0;0===e.length&&n.push(-1),a=e.length+1;for(let o=0;oe===t)}function fh(e,t){const n=[];for(let r=0;r"Number of splits must evenly divide the axis."),r=new Array(t).fill(e.shape[n]/t);else{i(t.reduce((e,t)=>(-1===t&&(e+=1),e),0)<=1,()=>"There should be only one negative value in split array.");const a=t.indexOf(-1);if(-1!==a){const r=t.reduce((e,t)=>t>0?e+t:e);t[a]=e.shape[n]-r}i(e.shape[n]===t.reduce((e,t)=>e+t),()=>"The sum of sizes must match the size of the axis dimension."),r=t}return r}function gh(e){return`Received SparseTensor with denseShape[0] = 0 but\n indices.shape[0] = ${e}`}function yh(e,t){return`indices(${e}, 0) is invalid: ${t} < 0`}function bh(e,t,n){return`indices(${e}, 0) is invalid: ${t} >= ${n}`}function xh(e,t){return`only one output dimension may be -1, not both ${e} and ${t}`}function vh(e,t){return`size ${e} must be non-negative, not ${t}`}function wh(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function kh(e,t){return`Input to reshape is a SparseTensor with ${c(e)}\n dense values, but the requested shape requires a multiple of ${c(t)}. inputShape=${e} outputShape= ${t}`}function Ih(e,t){return`Input to reshape is a tensor with ${c(e)} dense values, but the requested shape has ${c(t)}. inputShape=${e} outputShape=${t}`}function Nh(){return"segment ids must be >= 0"}function Sh(){return"segment ids are not increasing"}function Th(e,t){return`Segment id ${e} out of range [0, ${t}), possibly because segmentIds input is not sorted.`}function Ch(e,t,n){return`Bad: indices[${e}] == ${t} out of range [0, ${n})`}function $h(e,t,n,r){const a=t.shape.length,s=e.shape.length;if(0!==r&&(r<-a||r>a))throw new Error(`Expect batchDims in the range of [-${a}, ${a}], but got ${r}`);if(r<0&&(r+=a),r>s)throw new Error(`batchDims (${r}) must be less than rank(x) (\n ${s}).`);if(nMr(e))}catch(fO){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${fO}`)}}function Rh(e){return e.map(e=>Dr(e))}const _h=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,ERF_A1:Kp,ERF_A2:Xp,ERF_A3:Yp,ERF_A4:Qp,ERF_A5:Zp,ERF_P:qp,PARALLELIZE_THRESHOLD:30,get RowPartitionType(){return Ap},SELU_SCALE:jp,SELU_SCALEALPHA:Hp,applyActivation:Mc,assertAndGetBroadcastShape:li,assertAxesAreInnerMostDims:Ii,assertParamsConsistent:Rp,assignToTypedArray:ah,axesAreInnerMostDims:xi,calculateShapes:pc,checkEinsumDimSizes:dh,checkPadOnDimRoundingMode:xo,combineLocations:vi,combineRaggedTensorToTensorShapes:Fp,complexWithEvenIndex:th,complexWithOddIndex:nh,computeConv2DInfo:io,computeConv3DInfo:uo,computeDefaultPad:lo,computeDilation2DInfo:ao,computeOptimalWindowSize:Lp,computeOutAndReduceShapes:wi,computeOutShape:_p,computePool2DInfo:so,computePool3DInfo:oo,convertConv2DDataFormat:bo,decodeEinsumEquation:lh,eitherStridesOrDilationsAreOne:go,expandShapeToKeepDim:ki,exponent:oh,exponents:sh,fromStringArrayToUint8:Rh,fromUint8ToStringArray:Eh,getAxesPermutation:Ni,getBroadcastDims:ii,getComplexWithIndex:rh,getEinsumComputePath:ph,getEinsumPermutation:ch,getFusedBiasGradient:Dc,getFusedDyActivation:Fc,getImageCenter:Bp,getInnerMostAxes:Ti,getPermuted:Wp,getRaggedRank:Mp,getReductionAxes:ui,getReshaped:Vp,getReshapedPermuted:zp,getRowPartitionTypesHelper:Dp,getSliceBeginCoords:Up,getSliceSize:Gp,getSparseFillEmptyRowsIndicesDenseShapeMismatch:gh,getSparseFillEmptyRowsNegativeIndexErrorMessage:yh,getSparseFillEmptyRowsOutOfRangeIndexErrorMessage:bh,getSparseReshapeEmptyTensorZeroOutputDimErrorMessage:wh,getSparseReshapeInputOutputMismatchErrorMessage:Ih,getSparseReshapeInputOutputMultipleErrorMessage:kh,getSparseReshapeMultipleNegativeOneOutputDimErrorMessage:xh,getSparseReshapeNegativeOutputDimErrorMessage:vh,getSparseSegmentReductionIndicesOutOfRangeErrorMessage:Ch,getSparseSegmentReductionNegativeSegmentIdsErrorMessage:Nh,getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage:Sh,getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage:Th,getUndoAxesPermutation:Si,isIdentityPermutation:hh,mergeRealAndImagArrays:Jp,prepareAndValidate:vp,prepareSplitSize:mh,shouldFuse:Pc,splitRealAndImagArrays:eh,stridesOrDilationsArePositive:yo,tupleValuesAreOne:mo,upcastType:ca,validateDefaultValueShape:Pp,validateInput:dc,validateUpdateShape:cc,warn:rr},Symbol.toStringTag,{value:"Module"}));!function(){for(const e of ep)Hd(e)}();const Ah=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,Abs:H,Acos:j,Acosh:q,AdadeltaOptimizer:qd,AdagradOptimizer:Kd,AdamOptimizer:Xd,AdamaxOptimizer:Yd,Add:K,AddN:X,All:Y,Any:Q,ArgMax:Z,ArgMin:J,Asin:ee,Asinh:te,Atan:ne,Atan2:ae,Atanh:re,AvgPool:se,AvgPool3D:ie,AvgPool3DGrad:ue,AvgPoolGrad:oe,BatchMatMul:le,BatchToSpaceND:ce,Bincount:de,BitwiseAnd:pe,BroadcastArgs:he,Cast:fe,Ceil:me,ClipByValue:ge,Complex:ye,ComplexAbs:be,Concat:xe,Conv2D:ve,Conv2DBackpropFilter:we,Conv2DBackpropInput:ke,Conv3D:Ie,Conv3DBackpropFilterV2:Ne,Conv3DBackpropInputV2:Se,Cos:Te,Cosh:Ce,CropAndResize:Re,Cumprod:$e,Cumsum:Ee,DataStorage:t,DenseBincount:_e,DepthToSpace:Ae,DepthwiseConv2dNative:Oe,DepthwiseConv2dNativeBackpropFilter:Fe,DepthwiseConv2dNativeBackpropInput:De,Diag:Me,Dilation2D:Pe,Dilation2DBackpropFilter:Be,Dilation2DBackpropInput:Le,Draw:Ve,get ENV(){return z},Einsum:ze,Elu:Ue,EluGrad:Ge,Environment:L,Equal:je,Erf:He,Exp:qe,ExpandDims:Ke,Expm1:Xe,FFT:Ye,Fill:Qe,FlipLeftRight:Ze,Floor:Je,FloorDiv:et,FromPixels:Zn,FusedBatchNorm:tt,FusedConv2D:tr,FusedDepthwiseConv2D:nr,GatherNd:rt,GatherV2:nt,Greater:at,GreaterEqual:st,IFFT:it,Identity:ot,Imag:ut,IsFinite:lt,IsInf:ct,IsNan:dt,KernelBackend:n,LRN:wt,LRNGrad:kt,LeakyRelu:pt,Less:ht,LessEqual:ft,LinSpace:mt,Log:gt,Log1p:yt,LogicalAnd:bt,LogicalNot:xt,LogicalOr:vt,Max:It,MaxPool:St,MaxPool3D:Ct,MaxPool3DGrad:$t,MaxPoolGrad:Tt,MaxPoolWithArgmax:Et,Maximum:Nt,Mean:Rt,Min:_t,Minimum:At,MirrorPad:Ot,Mod:Ft,MomentumOptimizer:Zd,Multinomial:Dt,Multiply:Mt,Neg:Pt,NonMaxSuppressionV3:Bt,NonMaxSuppressionV4:Vt,NonMaxSuppressionV5:Wt,NotEqual:Lt,OP_SCOPE_SUFFIX:_a,OneHot:Ut,OnesLike:zt,Optimizer:jd,Pack:Gt,PadV2:Ht,Pow:jt,Prelu:qt,Prod:Kt,RMSPropOptimizer:Jd,RaggedGather:Xt,RaggedRange:Yt,RaggedTensorToTensor:Qt,Range:Zt,get Rank(){return Jr},Real:Jt,RealDiv:We,Reciprocal:en,get Reduction(){return Id},Relu:tn,Relu6:un,Reshape:nn,ResizeBilinear:sn,ResizeBilinearGrad:on,ResizeNearestNeighbor:rn,ResizeNearestNeighborGrad:an,Reverse:ln,RotateWithOffset:Jn,Round:cn,Rsqrt:dn,SGDOptimizer:Qd,ScatterNd:pn,SearchSorted:fn,Select:mn,Selu:gn,Sigmoid:wn,Sign:vn,Sin:bn,Sinh:xn,Slice:yn,Softmax:Cn,Softplus:kn,SpaceToBatchND:Sn,SparseFillEmptyRows:$n,SparseReshape:En,SparseSegmentMean:Rn,SparseSegmentSum:_n,SparseToDense:An,SplitV:Tn,Sqrt:In,Square:Fn,SquaredDifference:On,StaticRegexReplace:Dn,Step:Qn,StridedSlice:Mn,StringNGrams:Pn,StringSplit:Ln,StringToHashBucketFast:Bn,Sub:Vn,Sum:Nn,Tan:Wn,Tanh:zn,Tensor:Yr,TensorBuffer:qr,TensorScatterUpdate:hn,Tile:Un,TopK:Gn,Transform:Hn,Transpose:jn,Unique:qn,Unpack:Kn,UnsortedSegmentSum:Xn,Variable:Zr,ZerosLike:Yn,_FusedMatMul:er,abs:Hs,acos:js,acosh:qs,add:Ws,addN:Ks,all:Xs,any:Ys,argMax:Qs,argMin:Zs,asin:Js,asinh:eo,atan:to,atan2:no,atanh:ro,avgPool:wo,avgPool3d:ko,backend:Ha,backend_util:_h,basicLSTMCell:$o,batchNorm:Ro,batchNorm2d:_o,batchNorm3d:Ao,batchNorm4d:Oo,batchToSpaceND:Eo,bincount:Fo,bitwiseAnd:Do,booleanMaskAsync:Ic,broadcastArgs:Mo,broadcastTo:Po,buffer:Ps,cast:Ls,ceil:Lo,clipByValue:Vo,clone:Bs,complex:Oa,concat:Io,concat1d:Wo,concat2d:zo,concat3d:Uo,concat4d:Go,conv1d:jo,conv2d:Ho,conv2dTranspose:Ko,conv3d:Xo,conv3dTranspose:Qo,cos:Zo,cosh:Jo,cosineWindow:_c,cumprod:ei,cumsum:ti,customGrad:au,denseBincount:ni,depthToSpace:ri,depthwiseConv2d:ai,diag:si,dilation2d:oi,dispose:Va,div:Us,divNoNan:hi,dot:fi,dropout:Ec,einsum:mi,elu:gi,enclosingPowerOfTwo:Rc,engine:La,ensureShape:yi,env:V,equal:ci,erf:bi,euclideanNorm:Mi,exp:Pi,expandDims:Li,expm1:Bi,eye:Wi,fft:ql,fill:Bo,floor:zi,floorDiv:zs,fused:Uc,gather:Ui,gatherND:$c,getBackend:Ua,getGradient:ir,getKernel:or,getKernelsForBackend:ur,greater:Gi,greaterEqual:Hi,ifft:Kl,imag:ji,image:Md,inTopKAsync:Ac,io:mp,irfft:Xl,isFinite:qi,isInf:Ki,isNaN:Xi,keep:Wa,leakyRelu:Yi,less:Qi,lessEqual:Zi,linalg:Pd,linspace:Ji,localResponseNormalization:eu,log:tu,log1p:nu,logSigmoid:iu,logSoftmax:lu,logSumExp:cu,logicalAnd:du,logicalNot:pu,logicalOr:hu,logicalXor:fu,losses:Ld,lowerBound:yu,matMul:No,max:Ci,maxPool:bu,maxPool3d:xu,maxPoolWithArgmax:vu,maximum:wu,mean:ku,meshgrid:Su,min:$i,minimum:Tu,mirrorPad:Cu,mod:$u,moments:Eu,movingAverage:Sc,mul:Gs,multiRNNCell:Ru,multinomial:_u,neg:su,nextFrame:Ep,norm:Di,notEqual:Au,oneHot:Ou,ones:Nu,onesLike:Fu,op:Aa,outerProduct:Du,pad:Mu,pad1d:Pu,pad2d:Lu,pad3d:Bu,pad4d:Vu,pool:zu,pow:Ei,prelu:Uu,print:Vs,prod:Gu,raggedGather:Hu,raggedRange:ju,raggedTensorToTensor:qu,rand:Ku,randomGamma:xl,randomNormal:vl,randomStandardNormal:wl,randomUniform:kl,randomUniformInt:Il,range:Nl,real:Sl,reciprocal:Tl,registerBackend:Ga,registerKernel:lr,relu:Cl,relu6:$l,reshape:vo,reverse:El,reverse1d:Rl,reverse2d:_l,reverse3d:Al,reverse4d:Ol,rfft:Ql,round:Fl,rsqrt:Dl,scalar:Ri,scatterND:Tc,searchSorted:gu,selu:Ml,separableConv2d:Pl,setBackend:za,setdiff1dAsync:Ll,sigmoid:So,sign:Bl,signal:Dd,sin:Vl,sinh:Wl,slice:To,slice1d:zl,slice2d:Ul,slice3d:Gl,slice4d:Hl,softmax:jl,softplus:ou,spaceToBatchND:Wu,sparse:Bd,sparseToDense:Cc,spectral:Fd,split:Yl,sqrt:_i,square:Ai,squaredDifference:Zl,squeeze:Jl,stack:ec,step:tc,stridedSlice:nc,string:Vd,sub:uu,sum:Oi,sumOutType:da,tan:rc,tanh:Co,tensor:Da,tensor1d:ac,tensor2d:sc,tensor3d:oc,tensor4d:ic,tensor5d:uc,tensor6d:lc,tensorScatterUpdate:hc,tidy:Ba,tile:Vi,topk:fc,transpose:Nc,truncatedNormal:mc,unique:gc,unsortedSegmentSum:yc,unstack:bc,upcastType:ca,upperBound:xc,variable:vc,variableGrads:ru,where:di,whereAsync:kc,zeros:Iu,zerosLike:pi},Symbol.toStringTag,{value:"Module"}));var Oh,Fh,Dh;V().registerFlag("KEEP_INTERMEDIATE_TENSORS",()=>!1,e=>{e&&console.warn("Keep intermediate tensors is ON. This will print the values of all intermediate tensors during model inference. Not all models support this mode. For details, check e2e/benchmarks/ model_config.js. This significantly impacts performance.")}),(Fh=Oh||(Oh={}))[Fh.DT_INVALID=0]="DT_INVALID",Fh[Fh.DT_FLOAT=1]="DT_FLOAT",Fh[Fh.DT_DOUBLE=2]="DT_DOUBLE",Fh[Fh.DT_INT32=3]="DT_INT32",Fh[Fh.DT_UINT8=4]="DT_UINT8",Fh[Fh.DT_INT16=5]="DT_INT16",Fh[Fh.DT_INT8=6]="DT_INT8",Fh[Fh.DT_STRING=7]="DT_STRING",Fh[Fh.DT_COMPLEX64=8]="DT_COMPLEX64",Fh[Fh.DT_INT64=9]="DT_INT64",Fh[Fh.DT_BOOL=10]="DT_BOOL",Fh[Fh.DT_QINT8=11]="DT_QINT8",Fh[Fh.DT_QUINT8=12]="DT_QUINT8",Fh[Fh.DT_QINT32=13]="DT_QINT32",Fh[Fh.DT_BFLOAT16=14]="DT_BFLOAT16",Fh[Fh.DT_QINT16=15]="DT_QINT16",Fh[Fh.DT_QUINT16=16]="DT_QUINT16",Fh[Fh.DT_UINT16=17]="DT_UINT16",Fh[Fh.DT_COMPLEX128=18]="DT_COMPLEX128",Fh[Fh.DT_HALF=19]="DT_HALF",Fh[Fh.DT_RESOURCE=20]="DT_RESOURCE",Fh[Fh.DT_VARIANT=21]="DT_VARIANT",Fh[Fh.DT_UINT32=22]="DT_UINT32",Fh[Fh.DT_UINT64=23]="DT_UINT64",Fh[Fh.DT_FLOAT_REF=101]="DT_FLOAT_REF",Fh[Fh.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",Fh[Fh.DT_INT32_REF=103]="DT_INT32_REF",Fh[Fh.DT_UINT8_REF=104]="DT_UINT8_REF",Fh[Fh.DT_INT16_REF=105]="DT_INT16_REF",Fh[Fh.DT_INT8_REF=106]="DT_INT8_REF",Fh[Fh.DT_STRING_REF=107]="DT_STRING_REF",Fh[Fh.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",Fh[Fh.DT_INT64_REF=109]="DT_INT64_REF",Fh[Fh.DT_BOOL_REF=110]="DT_BOOL_REF",Fh[Fh.DT_QINT8_REF=111]="DT_QINT8_REF",Fh[Fh.DT_QUINT8_REF=112]="DT_QUINT8_REF",Fh[Fh.DT_QINT32_REF=113]="DT_QINT32_REF",Fh[Fh.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF",Fh[Fh.DT_QINT16_REF=115]="DT_QINT16_REF",Fh[Fh.DT_QUINT16_REF=116]="DT_QUINT16_REF",Fh[Fh.DT_UINT16_REF=117]="DT_UINT16_REF",Fh[Fh.DT_COMPLEX128_REF=118]="DT_COMPLEX128_REF",Fh[Fh.DT_HALF_REF=119]="DT_HALF_REF",Fh[Fh.DT_RESOURCE_REF=120]="DT_RESOURCE_REF",Fh[Fh.DT_VARIANT_REF=121]="DT_VARIANT_REF",Fh[Fh.DT_UINT32_REF=122]="DT_UINT32_REF",Fh[Fh.DT_UINT64_REF=123]="DT_UINT64_REF",function(e){var t;(t=e.CheckpointFormatVersion||(e.CheckpointFormatVersion={}))[t.LEGACY=0]="LEGACY",t[t.V1=1]="V1",t[t.V2=2]="V2"}(Dh||(Dh={}));const Mh={};function Ph(e){return Mh[e]}function Lh(e,t,n,r,a){const s=t.inputParams[e];if(s&&void 0!==s.inputIndexStart){const e=s.inputIndexStart,o=0===s.inputIndexEnd?void 0:void 0===s.inputIndexEnd?e+1:s.inputIndexEnd,i=e<0?t.inputNames.length+e:e;if("tensor"===s.type)return Bh(t.inputNames[i],n,r,a);if("tensors"===s.type){const s=t.inputs.slice(e,o);return t.inputNames.slice(e,o).filter((e,t)=>{var n;return"NoOp"!==(null===(n=s[t])||void 0===n?void 0:n.op)}).map(e=>Bh(e,n,r,a))}const u=Bh(t.inputNames[i],n,r,a),l=u.dataSync();return"number"===s.type?l[0]:E(u.shape,l)}const o=t.attrParams[e];return o&&o.value}function Bh(e,t,n,r){const[a,s]=Uh(e,n);if(null!=r){const e=r.getHashTableHandleByName(a);if(null!=e)return e}const o=n.currentContextIds.find(e=>!!t[zh(a,e)]);return void 0!==o?t[zh(a,o)][s]:void 0}function Vh(e,t,n){return t[zh(e,n.currentContextId)]}function Wh(e,t){const[n,r,a]=Uh(e,t);return[zh(n,t&&t.currentContextId),r,a]}function zh(e,t){return t?`${e}-${t}`:e}function Uh(e,t){if(""===e)return["",0,void 0];const n=null!=t&&null!=t.parseNodeNameCache;if(n){const n=t.parseNodeNameCache.get(e);if(null!=n)return n}const r=e.split(":");let a;if(1===r.length)a=[e,0,void 0];else{const e=r[0],t=3===r.length?r[1]:void 0;a=[e,Number(r[r.length-1]),t]}return n&&t.parseNodeNameCache.set(e,a),a}function Gh(e,t,n){let r=Lh("pad",e,t,n);if("explicit"===r){r=Lh("explicitPaddings",e,t,n);const a=[[0,0],[0,0],[0,0],[0,0]];for(let e=0;e<4;e++)a[e][0]=r[2*e],a[e][1]=r[2*e+1];return a}return r}function Hh(e){return e.kept?e:Bs(e)}const jh=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"Add",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddV2",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddN",category:"arithmetic",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"BiasAdd",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"Sub",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"RealDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Div",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"DivNoNan",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mul",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Maximum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Minimum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Pow",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SquaredDifference",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorMod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]},Symbol.toStringTag,{value:"Module"})),qh=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"Abs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan2",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ceil",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ClipByValue",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"clipValueMin",type:"number"},{start:2,name:"clipValueMax",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Complex",category:"basic_math",inputs:[{start:0,name:"real",type:"tensor"},{start:1,name:"imag",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ComplexAbs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Elu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Exp",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Floor",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Imag",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Neg",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Real",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Prelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"alpha",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu6",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Selu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sigmoid",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Rsqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Square",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sign",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Round",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Expm1",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log1p",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Reciprocal",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Softplus",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Erf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LeakyRelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"alpha",name:"alpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsNan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsFinite",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsInf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]},Symbol.toStringTag,{value:"Module"})),Kh=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"EmptyTensorList",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"maxNumElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"LoopCond",category:"control",inputs:[{start:0,name:"pred",type:"tensor"}]},{tfOpName:"Switch",category:"control",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"pred",type:"tensor"}]},{tfOpName:"Merge",category:"control",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"Enter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"frame_name",name:"frameName",type:"string"},{tfName:"is_constant",name:"isConstant",type:"bool"}]},{tfOpName:"Exit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NextIteration",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayV3",category:"control",inputs:[{start:0,name:"size",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"dynamic_size",name:"dynamicSize",type:"bool"},{tfName:"clear_after_read",name:"clearAfterRead",type:"bool"},{tfName:"identical_element_shapes",name:"identicalElementShapes",type:"bool"},{tfName:"tensor_array_name",name:"name",type:"string"}]},{tfOpName:"TensorArrayWriteV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayReadV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayGatherV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"}]},{tfOpName:"TensorArrayScatterV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArrayConcatV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape_except0",name:"elementShapeExcept0",type:"shape",notSupported:!0}]},{tfOpName:"TensorArraySplitV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"tensor",type:"tensor"},{start:2,name:"lengths",type:"number[]"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArraySizeV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}]},{tfOpName:"TensorArrayCloseV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"}]},{tfOpName:"StatelessIf",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"If",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"StatelessWhile",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"While",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"TensorListScatter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListScatterV2",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"},{start:3,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGather",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListSetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListReserve",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListFromTensor",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListStack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"},{tfName:"num_elements",name:"numElements",type:"dtype"}]},{tfOpName:"TensorListSplit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"},{start:2,name:"lengths",type:"number[]"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcat",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcatV2",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPopBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPushBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListLength",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}]},{tfOpName:"TensorListResize",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"size",type:"number"}]}]},Symbol.toStringTag,{value:"Module"})),Xh=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"AvgPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[],notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPoolWithArgmax",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"include_batch_in_index",name:"includeBatchInIndex",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AvgPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Conv1D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"stride",name:"stride",type:"number"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NWC"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"dilation",name:"dilation",type:"number",defaultValue:1}]},{tfOpName:"Conv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"useCudnnOnGpu",name:"useCudnnOnGpu",type:"bool"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"_FusedConv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"use_cudnn_on_gpu",name:"useCudnnOnGpu",type:"bool",defaultValue:!0},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number",defaultValue:.2}]},{tfOpName:"Conv2DBackpropInput",category:"convolution",inputs:[{start:2,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:0,name:"outputShape",type:"number[]"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]",notSupported:!0}]},{tfOpName:"DepthwiseConv2d",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"DepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"FusedDepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]}]},{tfOpName:"Conv3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"Dilation2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"rates",name:"dilations",type:"number[]"},{tfName:"padding",name:"pad",type:"string"}]}]},Symbol.toStringTag,{value:"Module"})),Yh=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"Fill",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"},{start:1,name:"value",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"LinSpace",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"num",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"OneHot",category:"creation",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"depth",type:"number"},{start:2,name:"onValue",type:"number",defaultValue:1},{start:3,name:"offValue",type:"number",defaultValue:0}],attrs:[{tfName:"axis",name:"axis",type:"number",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Ones",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"OnesLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"RandomStandardNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"RandomUniform",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number",defaultValue:0},{tfName:"maxval",name:"maxval",type:"number",defaultValue:1},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"RandomUniformInt",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number"},{tfName:"maxval",name:"maxval",type:"number"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Range",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"step",type:"number",defaultValue:0}],attrs:[{tfName:"Tidx",name:"dtype",type:"dtype"}]},{tfOpName:"TruncatedNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"means",name:"mean",type:"number",defaultValue:0},{tfName:"stddev",name:"stdDev",type:"number",defaultValue:1},{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Zeros",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"ZerosLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Multinomial",category:"creation",inputs:[{start:0,name:"logits",type:"tensor"},{start:1,name:"numSamples",type:"number"}],attrs:[{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number"},{tfName:"T",name:"dtype",type:"dtype"},{tfName:"output_dtype",name:"output_dtype",type:"dtype"}]}]},Symbol.toStringTag,{value:"Module"})),Qh=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"NonMaxSuppressionV2",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV3",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV4",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"T_threshold",name:"threshold",type:"dtype",notSupported:!0},{tfName:"pad_to_max_output_size",name:"padToMaxOutputSize",type:"bool"}]},{tfOpName:"NonMaxSuppressionV5",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"},{start:5,name:"softNmsSigma",type:"number"}]},{tfOpName:"Where",category:"dynamic",inputs:[{start:0,name:"condition",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ListDiff",category:"dynamic",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]},Symbol.toStringTag,{value:"Module"})),Zh=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"LowerBound",category:"evaluation",inputs:[{start:0,name:"sortedSequence",type:"tensor"},{start:1,name:"values",type:"tensor"}]},{tfOpName:"TopKV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"k",type:"number"}],attrs:[{tfName:"sorted",name:"sorted",type:"bool"}]},{tfOpName:"UpperBound",category:"evaluation",inputs:[{start:0,name:"sortedSequence",type:"tensor"},{start:1,name:"values",type:"tensor"}]},{tfOpName:"Unique",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"UniqueV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]}]},Symbol.toStringTag,{value:"Module"})),Jh=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"PlaceholderWithDefault",category:"graph",inputs:[{start:0,name:"default",type:"tensor"}],attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Placeholder",category:"graph",attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Const",category:"graph"},{tfOpName:"Identity",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IdentityN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Snapshot",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Rank",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Size",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Shape",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"ShapeN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Print",category:"graph",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"data",type:"tensors"}],attrs:[{tfName:"message",name:"message",type:"string"},{tfName:"first_n",name:"firstN",type:"number",notSupported:!0},{tfName:"summarize",name:"summarize",type:"number",defaultValue:3}]},{tfOpName:"NoOp",category:"graph",inputs:[]},{tfOpName:"StopGradient",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"FakeQuantWithMinMaxVars",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"min",name:"min",type:"number"},{tfName:"max",name:"max",type:"number"}]}]},Symbol.toStringTag,{value:"Module"})),ef=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"HashTable",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"HashTableV2",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"LookupTableImport",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableImportV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFind",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFindV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableSize",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]},{tfOpName:"LookupTableSizeV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]},{tfOpName:"InitializeTable",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}]},{tfOpName:"InitializeTableV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}]}]},Symbol.toStringTag,{value:"Module"})),tf=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"ResizeBilinear",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ResizeNearestNeighbor",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"CropAndResize",category:"image",inputs:[{start:0,name:"image",type:"tensor"},{start:1,name:"boxes",type:"tensor"},{start:2,name:"boxInd",type:"tensor"},{start:3,name:"cropSize",type:"number[]"}],attrs:[{tfName:"method",name:"method",type:"string"},{tfName:"extrapolation_value",name:"extrapolationValue",type:"number"}]},{tfOpName:"ImageProjectiveTransformV3",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"transforms",type:"tensor"},{start:2,name:"outputShape",type:"number[]"},{start:3,name:"fillValue",type:"number"}],attrs:[{tfName:"interpolation",name:"interpolation",type:"string"},{tfName:"fill_mode",name:"fillMode",type:"string"}]}]},Symbol.toStringTag,{value:"Module"})),nf=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"Equal",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NotEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Greater",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"GreaterEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Less",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LessEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalAnd",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalNot",category:"logical",inputs:[{start:0,name:"a",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalOr",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Select",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SelectV2",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BitwiseAnd",category:"logical",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}]}]},Symbol.toStringTag,{value:"Module"})),rf=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"_FusedMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMulV2",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Transpose",category:"matrices",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"perm",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Einsum",category:"matrices",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"equation",name:"equation",type:"string"},{tfName:"N",name:"n",type:"number",defaultValue:2},{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"MatrixBandPart",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"numLower",type:"tensor"},{start:1,name:"numUpper",type:"tensor"}]}]},Symbol.toStringTag,{value:"Module"})),af=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"EuclideanNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",defaultValue:!1}]},{tfOpName:"FusedBatchNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV2",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV3",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"LRN",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"depth_radius",name:"radius",type:"number",defaultValue:5},{tfName:"bias",name:"bias",type:"number",defaultValue:1},{tfName:"alpha",name:"alpha",type:"number",defaultValue:1},{tfName:"beta",name:"beta",type:"number",defaultValue:.5}]},{tfOpName:"Softmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"LogSoftmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]}]},Symbol.toStringTag,{value:"Module"})),sf=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"Bincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}]},{tfOpName:"DenseBincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}],attrs:[{tfName:"binary_output",name:"binaryOutput",type:"bool"}]},{tfOpName:"Max",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Mean",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Min",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Sum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"All",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Any",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"ArgMax",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"ArgMin",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Prod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cumprod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]},{tfOpName:"Cumsum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]}]},Symbol.toStringTag,{value:"Module"})),of=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"ConcatV2",category:"slice_join",inputs:[{start:0,end:-1,name:"tensors",type:"tensors"},{start:-1,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"Concat",category:"slice_join",inputs:[{start:1,end:0,name:"tensors",type:"tensors"},{start:0,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"GatherV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"axis",type:"number",defaultValue:0}],attrs:[{tfName:"batch_dims",name:"batchDims",type:"number",defaultValue:0}]},{tfOpName:"Gather",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",notSupported:!0}]},{tfOpName:"Reverse",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"dims",type:"bool[]"}]},{tfOpName:"ReverseV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}]},{tfOpName:"Slice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"size",type:"number[]"}]},{tfOpName:"StridedSlice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"end",type:"number[]"},{start:3,name:"strides",type:"number[]"}],attrs:[{tfName:"begin_mask",name:"beginMask",type:"number",defaultValue:0},{tfName:"end_mask",name:"endMask",type:"number",defaultValue:0},{tfName:"new_axis_mask",name:"newAxisMask",type:"number",defaultValue:0},{tfName:"ellipsis_mask",name:"ellipsisMask",type:"number",defaultValue:0},{tfName:"shrink_axis_mask",name:"shrinkAxisMask",type:"number",defaultValue:0}]},{tfOpName:"Pack",category:"slice_join",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Unpack",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"num",name:"num",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Tile",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"reps",type:"number[]"}]},{tfOpName:"Split",category:"slice_join",inputs:[{start:0,name:"axis",type:"number",defaultValue:0},{start:1,name:"x",type:"tensor"}],attrs:[{tfName:"num_split",name:"numOrSizeSplits",type:"number",defaultValue:1}]},{tfOpName:"SplitV",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"numOrSizeSplits",type:"number[]"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"ScatterNd",category:"slice_join",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"shape",type:"number[]"}]},{tfOpName:"GatherNd",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}]},{tfOpName:"SparseToDense",category:"slice_join",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!1,notSupported:!0}]},{tfOpName:"TensorScatterUpdate",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"values",type:"tensor"}]}]},Symbol.toStringTag,{value:"Module"})),uf=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"SparseFillEmptyRows",category:"sparse",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"denseShape",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}]},{tfOpName:"SparseReshape",category:"sparse",inputs:[{start:0,name:"inputIndices",type:"tensor"},{start:1,name:"inputShape",type:"tensor"},{start:2,name:"newShape",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SparseSegmentMean",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]},{tfOpName:"SparseSegmentSum",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]}]},Symbol.toStringTag,{value:"Module"})),lf=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"FFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"RFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]},{tfOpName:"IRFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]}]},Symbol.toStringTag,{value:"Module"})),cf=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"StaticRegexReplace",category:"string",inputs:[{start:0,name:"input",type:"tensor"}],attrs:[{tfName:"pattern",name:"pattern",type:"string"},{tfName:"rewrite",name:"rewrite",type:"string"},{tfName:"replace_global",name:"replaceGlobal",type:"bool"}]},{tfOpName:"StringNGrams",category:"string",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"dataSplits",type:"tensor"}],attrs:[{tfName:"separator",name:"separator",type:"string"},{tfName:"ngram_widths",name:"nGramWidths",type:"number[]"},{tfName:"left_pad",name:"leftPad",type:"string"},{tfName:"right_pad",name:"rightPad",type:"string"},{tfName:"pad_width",name:"padWidth",type:"number"},{tfName:"preserve_short_sequences",name:"preserveShortSequences",type:"bool"}],outputs:["ngrams","ngrams_splits"]},{tfOpName:"StringSplit",category:"string",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"delimiter",type:"tensor"}],attrs:[{tfName:"skip_empty",name:"skipEmpty",type:"bool"}],outputs:["indices","values","shape"]},{tfOpName:"StringToHashBucketFast",category:"string",inputs:[{start:0,name:"input",type:"tensor"}],attrs:[{tfName:"num_buckets",name:"numBuckets",type:"number"}]}]},Symbol.toStringTag,{value:"Module"})),df=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,json:[{tfOpName:"Cast",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"SrcT",name:"sdtype",type:"dtype",notSupported:!0},{tfName:"DstT",name:"dtype",type:"dtype"}]},{tfOpName:"ExpandDims",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"MirrorPad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"mode",name:"mode",type:"string"}]},{tfOpName:"Pad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"constant_value",name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"PadV2",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"},{start:2,name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"Reshape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"EnsureShape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"Squeeze",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"axis",tfDeprecatedName:"squeeze_dims",name:"axis",type:"number[]"}]},{tfOpName:"SpaceToBatchND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"paddings",type:"number[]"}]},{tfOpName:"BatchToSpaceND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"crops",type:"number[]"}]},{tfOpName:"DepthToSpace",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"block_size",name:"blockSize",type:"number"},{tfName:"data_format",name:"dataFormat",type:"string"}]},{tfOpName:"BroadcastTo",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}],attrs:[]},{tfOpName:"BroadcastArgs",category:"transformation",inputs:[{start:0,name:"s0",type:"tensor"},{start:1,name:"s1",type:"tensor"}],attrs:[]}]},Symbol.toStringTag,{value:"Module"}));class pf{static get Instance(){return this._instance||(this._instance=new this)}constructor(){const e=[].concat(...[jh,qh,Kh,Xh,Yh,Qh,Zh,Jh,ef,tf,nf,rf,af,sf,of,uf,lf,cf,df].map(e=>e.json));this.opMappers=e.reduce((e,t)=>(e[t.tfOpName]=t,e),{})}transformGraph(e,t={}){const n=e.node,r=[],a=[],s=[],o=n.reduce((e,t)=>(e[t.name]=this.mapNode(t),t.op.startsWith("Placeholder")?r.push(e[t.name]):"Const"===t.op?a.push(e[t.name]):null!=t.input&&0!==t.input.length||s.push(e[t.name]),e),{});let i=[];const u=[];let l={},c={};null!=t&&(l=this.mapSignatureEntries(t.inputs),c=this.mapSignatureEntries(t.outputs));const d=Object.keys(o);d.forEach(e=>{const t=o[e];t.inputNames.forEach((e,n)=>{const[r,,a]=Wh(e),s=o[r];if(null!=s.outputs){const e=s.outputs.indexOf(a);if(-1!==e){const a=`${r}:${e}`;t.inputNames[n]=a}}t.inputs.push(s),s.children.push(t)})}),0===Object.keys(c).length?d.forEach(e=>{const t=o[e];0===t.children.length&&u.push(t)}):Object.keys(c).forEach(e=>{const[t]=Wh(e),n=o[t];null!=n&&(n.signatureKey=c[e],u.push(n))}),Object.keys(l).length>0?Object.keys(l).forEach(e=>{const[t]=Wh(e),n=o[t];n&&(n.signatureKey=l[e],i.push(n))}):i=r;let p={};null!=e.library&&null!=e.library.function&&(p=e.library.function.reduce((e,t)=>(e[t.signature.name]=this.mapFunction(t),e),{}));const h={nodes:o,inputs:i,outputs:u,weights:a,placeholders:r,signature:t,functions:p};return s.length>0&&(h.initNodes=s),h}mapSignatureEntries(e){return Object.keys(e||{}).reduce((t,n)=>(t[e[n].name]=n,t),{})}mapNode(e){const t=Ph(e.op)||this.opMappers[e.op]||{};null==e.attr&&(e.attr={});const n={name:e.name,op:e.op,category:t.category,inputNames:(e.input||[]).map(e=>e.startsWith("^")?e.slice(1):e),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:e.attr,outputs:t.outputs};return null!=t.inputs&&(n.inputParams=t.inputs.reduce((e,t)=>(e[t.name]={type:t.type,inputIndexStart:t.start,inputIndexEnd:t.end},e),{})),null!=t.attrs&&(n.attrParams=t.attrs.reduce((t,n)=>{const r=n.type;let a;switch(n.type){case"string":a=ff(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=ff(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"string[]":a=Nf(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Nf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number":a=gf(e.attr,n.tfName,n.defaultValue||0),void 0===a&&n.tfDeprecatedName&&(a=gf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number[]":a=If(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=If(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool":a=mf(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=mf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool[]":a=Tf(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Tf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape":a=kf(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=kf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape[]":a=Sf(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Sf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype":a=xf(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=xf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype[]":a=vf(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=vf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"func":a=bf(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=bf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error(`Unsupported param type: ${n.type} for op: ${e.op}`)}return t[n.name]={value:a,type:r},t},{})),n}mapFunction(e){const t=e.nodeDef,n=[];let r={};null!=t&&(r=t.reduce((e,t)=>(e[t.name]=this.mapNode(t),"Const"===t.op&&n.push(e[t.name]),e),{}));const a=[],s=[];e.signature.inputArg.forEach(e=>{const[t]=Wh(e.name),n={name:t,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:yf(e.type),type:"dtype"}},children:[]};n.signatureKey=e.name,a.push(n),r[t]=n});Object.keys(r).forEach(e=>{const t=r[e];t.inputNames.forEach((e,n)=>{const[a,,s]=Wh(e),o=r[a];if(null!=o.outputs){const e=o.outputs.indexOf(s);if(-1!==e){const r=`${a}:${e}`;t.inputNames[n]=r}}t.inputs.push(o),o.children.push(t)})});const o=e.ret;e.signature.outputArg.forEach(e=>{const[t,n]=Wh(o[e.name]),a=r[t];null!=a&&(a.defaultOutput=n,s.push(a))});const i=this.mapArgsToSignature(e);return{nodes:r,inputs:a,outputs:s,weights:n,placeholders:[],signature:i}}mapArgsToSignature(e){return{methodName:e.signature.name,inputs:e.signature.inputArg.reduce((e,t)=>(e[t.name]=this.mapArgToTensorInfo(t),e),{}),outputs:e.signature.outputArg.reduce((t,n)=>(t[n.name]=this.mapArgToTensorInfo(n,e.ret),t),{})}}mapArgToTensorInfo(e,t){let n=e.name;return null!=t&&(n=t[n]),{name:n,dtype:e.type}}}function hf(e,t){const n=Array.isArray(e)?String.fromCharCode.apply(null,e):function(e){const t=V().global;if("undefined"!==typeof t.atob)return t.atob(e);if("undefined"!==typeof Buffer)return new Buffer(e,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}(e);return t?n:n.toLowerCase()}function ff(e,t,n,r=!1){const a=e[t];return null!=a?hf(a.s,r):n}function mf(e,t,n){const r=e[t];return r?r.b:n}function gf(e,t,n){const r=e[t]||{},a=null!=r.i?r.i:null!=r.f?r.f:n;return"number"===typeof a?a:parseInt(a,10)}function yf(e){switch("string"===typeof e&&(e=Oh[e]),e){case Oh.DT_FLOAT:case Oh.DT_HALF:return"float32";case Oh.DT_INT32:case Oh.DT_INT64:case Oh.DT_INT8:case Oh.DT_UINT8:return"int32";case Oh.DT_BOOL:return"bool";case Oh.DT_DOUBLE:return"float32";case Oh.DT_STRING:return"string";case Oh.DT_COMPLEX64:case Oh.DT_COMPLEX128:return"complex64";default:return null}}function bf(e,t,n){const r=e[t];return r&&r.func?r.func.name:n}function xf(e,t,n){const r=e[t];return r&&r.type?yf(r.type):n}function vf(e,t,n){const r=e[t];return r&&r.list&&r.list.type?r.list.type.map(e=>yf(e)):n}function wf(e){if(!e.unknownRank)return null!=e.dim?e.dim.map(e=>"number"===typeof e.size?e.size:parseInt(e.size,10)):[]}function kf(e,t,n){const r=e[t];return r&&r.shape?wf(r.shape):n}function If(e,t,n){const r=e[t];return r?((r.list.f&&r.list.f.length?r.list.f:r.list.i)||[]).map(e=>"number"===typeof e?e:parseInt(e,10)):n}function Nf(e,t,n,r=!1){const a=e[t];return a&&a.list&&a.list.s?a.list.s.map(e=>hf(e,r)):n}function Sf(e,t,n){const r=e[t];return r&&r.list&&r.list.shape?r.list.shape.map(e=>wf(e)):n}function Tf(e,t,n){const r=e[t];return r&&r.list&&r.list.b?r.list.b:n}class Cf{constructor(e,t,n){this.node=e,this.tensorMap=t,this.context=n,this.inputs=[],this.attrs={},this.inputs=e.inputNames.map(e=>this.getInput(e)),null!=e.rawAttrs&&(this.attrs=Object.keys(e.rawAttrs).reduce((e,t)=>(e[t]=this.getAttr(t),e),{}))}getInput(e){return Bh(e,this.tensorMap,this.context)}getAttr(e,t){const n=this.node.rawAttrs[e];if(null!=n.tensor)return Bh(e,this.tensorMap,this.context);if(null!=n.i||null!=n.f)return gf(this.node.rawAttrs,e,t);if(null!=n.s)return ff(this.node.rawAttrs,e,t);if(null!=n.b)return mf(this.node.rawAttrs,e,t);if(null!=n.shape)return kf(this.node.rawAttrs,e,t);if(null!=n.type)return xf(this.node.rawAttrs,e,t);if(null!=n.list){if(null!=n.list.i||null!=n.list.f)return If(this.node.rawAttrs,e,t);if(null!=n.list.s)return Nf(this.node.rawAttrs,e,t);if(null!=n.list.shape)return Sf(this.node.rawAttrs,e,t);if(null!=n.list.b)return Tf(this.node.rawAttrs,e,t);if(null!=n.list.type)return vf(this.node.rawAttrs,e,t)}return t}}const $f=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,OP_SCOPE_SUFFIX:_a,abs:Hs,acos:js,acosh:qs,add:Ws,addN:Ks,all:Xs,any:Ys,argMax:Qs,argMin:Zs,asin:Js,asinh:eo,atan:to,atan2:no,atanh:ro,avgPool:wo,avgPool3d:ko,basicLSTMCell:$o,batchNorm:Ro,batchNorm2d:_o,batchNorm3d:Ao,batchNorm4d:Oo,batchToSpaceND:Eo,bincount:Fo,bitwiseAnd:Do,booleanMaskAsync:Ic,broadcastArgs:Mo,broadcastTo:Po,buffer:Ps,cast:Ls,ceil:Lo,clipByValue:Vo,clone:Bs,complex:Oa,concat:Io,concat1d:Wo,concat2d:zo,concat3d:Uo,concat4d:Go,conv1d:jo,conv2d:Ho,conv2dTranspose:Ko,conv3d:Xo,conv3dTranspose:Qo,cos:Zo,cosh:Jo,cosineWindow:_c,cumprod:ei,cumsum:ti,denseBincount:ni,depthToSpace:ri,depthwiseConv2d:ai,diag:si,dilation2d:oi,div:Us,divNoNan:hi,dot:fi,dropout:Ec,einsum:mi,elu:gi,enclosingPowerOfTwo:Rc,ensureShape:yi,equal:ci,erf:bi,euclideanNorm:Mi,exp:Pi,expandDims:Li,expm1:Bi,eye:Wi,fft:ql,fill:Bo,floor:zi,floorDiv:zs,fused:Uc,gather:Ui,gatherND:$c,greater:Gi,greaterEqual:Hi,ifft:Kl,imag:ji,image:Md,inTopKAsync:Ac,irfft:Xl,isFinite:qi,isInf:Ki,isNaN:Xi,leakyRelu:Yi,less:Qi,lessEqual:Zi,linalg:Pd,linspace:Ji,localResponseNormalization:eu,log:tu,log1p:nu,logSigmoid:iu,logSoftmax:lu,logSumExp:cu,logicalAnd:du,logicalNot:pu,logicalOr:hu,logicalXor:fu,losses:Ld,lowerBound:yu,matMul:No,max:Ci,maxPool:bu,maxPool3d:xu,maxPoolWithArgmax:vu,maximum:wu,mean:ku,meshgrid:Su,min:$i,minimum:Tu,mirrorPad:Cu,mod:$u,moments:Eu,movingAverage:Sc,mul:Gs,multiRNNCell:Ru,multinomial:_u,neg:su,norm:Di,notEqual:Au,oneHot:Ou,ones:Nu,onesLike:Fu,op:Aa,outerProduct:Du,pad:Mu,pad1d:Pu,pad2d:Lu,pad3d:Bu,pad4d:Vu,pool:zu,pow:Ei,prelu:Uu,print:Vs,prod:Gu,raggedGather:Hu,raggedRange:ju,raggedTensorToTensor:qu,rand:Ku,randomGamma:xl,randomNormal:vl,randomStandardNormal:wl,randomUniform:kl,randomUniformInt:Il,range:Nl,real:Sl,reciprocal:Tl,relu:Cl,relu6:$l,reshape:vo,reverse:El,reverse1d:Rl,reverse2d:_l,reverse3d:Al,reverse4d:Ol,rfft:Ql,round:Fl,rsqrt:Dl,scalar:Ri,scatterND:Tc,searchSorted:gu,selu:Ml,separableConv2d:Pl,setdiff1dAsync:Ll,sigmoid:So,sign:Bl,signal:Dd,sin:Vl,sinh:Wl,slice:To,slice1d:zl,slice2d:Ul,slice3d:Gl,slice4d:Hl,softmax:jl,softplus:ou,spaceToBatchND:Wu,sparse:Bd,sparseToDense:Cc,spectral:Fd,split:Yl,sqrt:_i,square:Ai,squaredDifference:Zl,squeeze:Jl,stack:ec,step:tc,stridedSlice:nc,string:Vd,sub:uu,sum:Oi,tan:rc,tanh:Co,tensor:Da,tensor1d:ac,tensor2d:sc,tensor3d:oc,tensor4d:ic,tensor5d:uc,tensor6d:lc,tensorScatterUpdate:hc,tile:Vi,topk:fc,transpose:Nc,truncatedNormal:mc,unique:gc,unsortedSegmentSum:yc,unstack:bc,upperBound:xc,variable:vc,where:di,whereAsync:kc,zeros:Iu,zerosLike:pi},Symbol.toStringTag,{value:"Module"}));function Ef(e,t,n=""){if("number"!==typeof e&&"number"!==typeof t){i(e.length===t.length,()=>n+` Shapes ${e} and ${t} must match`);for(let r=0;rn+` Shapes ${e} and ${t} must match`)}}}function Rf(e){return"number"!==typeof e&&!e.some(e=>e<0)}function _f(e,t,n){let r=Af(e,n);const a=!Rf(r);if(a&&0===t.length)throw new Error(`Tried to calculate elements of an empty list with non-fully-defined elementShape: ${r}`);if(a&&t.forEach(e=>{r=Af(e.shape,r)}),!Rf(r))throw new Error(`Non-fully-defined elementShape: ${r}`);return r}function Af(e,t){if("number"===typeof e)return t;if("number"===typeof t)return e;if(e.length!==t.length)throw new Error(`Incompatible ranks during merge: ${e} vs. ${t}`);const n=[];for(let r=0;r=0&&s>=0&&a!==s)throw new Error(`Incompatible shape during merge: ${e} vs. ${t}`);n[r]=a>=0?a:s}return n}class Of{constructor(e,t,n,r,a,s,o){this.name=e,this.dtype=t,this.maxSize=n,this.elementShape=r,this.identicalElementShapes=a,this.dynamicSize=s,this.clearAfterRead=o,this.tensors=[],this.closed_=!1,this.idTensor=Ri(0),Wa(this.idTensor)}get id(){return this.idTensor.id}get closed(){return this.closed_}clearAndClose(e){this.tensors.forEach(t=>{null!=e&&e.has(t.tensor.id)||t.tensor.dispose()}),this.tensors=[],this.closed_=!0,this.idTensor.dispose()}size(){return this.tensors.length}read(e){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||e>=this.size())throw new Error(`Tried to read from index ${e}, but array size is: ${this.size()}`);const t=this.tensors[e];if(t.cleared)throw new Error(`TensorArray ${this.name}: Could not read index ${e} twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).`);return this.clearAfterRead&&(t.cleared=!0),t.read=!0,t.tensor}readMany(e){return e.map(e=>this.read(e))}write(e,t){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||!this.dynamicSize&&e>=this.maxSize)throw new Error(`Tried to write to index ${e}, but array is not resizeable and size is: ${this.maxSize}`);const n=this.tensors[e]||{};if(t.dtype!==this.dtype)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e},\n because the value dtype is ${t.dtype}, but TensorArray dtype is ${this.dtype}.`);if(0!==this.size()||null!=this.elementShape&&0!==this.elementShape.length||(this.elementShape=t.shape),Ef(this.elementShape,t.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${e}.`),n.read)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`);if(n.written)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`);n.tensor=t,Wa(t),n.written=!0,this.tensors[e]=n}writeMany(e,t){if(e.length!==t.length)throw new Error(`TensorArray ${this.name}: could not write multiple tensors,because the index size: ${e.length} is not the same as tensors size: ${t.length}.`);e.forEach((e,n)=>this.write(e,t[n]))}gather(e,t){if(t&&t!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${t}`);if(e)e=e.slice(0,this.size());else{e=[];for(let t=0;t=this.maxSize)throw new Error(`Max index must be < array size (${n} vs. ${this.maxSize})`);this.writeMany(e,bc(t,0))}split(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);let n=0;const r=e.map(e=>(n+=e,n));if(n!==t.shape[0])throw new Error(`Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n ${n}, and tensor's shape is: ${t.shape}`);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${e.length}), and the TensorArray is not marked as dynamically resizeable`);const a=0===n?0:t.size/n,s=[];Ba(()=>{t=vo(t,[1,n,a]);for(let n=0;n{if(n!==e.dtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${e.dtype}`);Ef(t,e.shape,"TensorList shape mismatch: "),Wa(e)}),this.idTensor=Ri(0),this.maxNumElements=r,Wa(this.idTensor)}copy(){return new Ff([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(e){this.tensors.forEach(t=>{null!=e&&e.has(t.id)||t.dispose()}),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(e,t,n=-1){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(-1!==n&&this.tensors.length!==n)throw new Error(`Operation expected a list with ${n} elements but got a list with ${this.tensors.length} elements.`);Ef(e,this.elementShape,"TensorList shape mismatch: ");const r=_f(this.elementShape,this.tensors,e);return Ba(()=>{const e=this.tensors.map(e=>vo(e,r));return ec(e,0)})}popBack(e,t){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(0===this.size())throw new Error("Trying to pop from an empty list.");const n=_f(this.elementShape,this.tensors,e),r=this.tensors.pop();return r.kept=!1,Ef(r.shape,e,"TensorList shape mismatch: "),vo(r,n)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(Ef(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");Wa(e),this.tensors.push(e)}resize(e){if(e<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${e}`);if(-1!==this.maxNumElements&&e>this.maxNumElements)throw new Error(`TensorListResize input size ${e} is greater maxNumElement ${this.maxNumElements}.`);const t=new Ff([],this.elementShape,this.elementDtype,this.maxNumElements);t.tensors.length=e;for(let n=0;nthis.tensors.length)throw new Error(`Trying to access element ${e} in a list with ${this.tensors.length} elements.`);if(null==this.tensors[e])throw new Error(`element at index ${e} is null.`);Ef(this.tensors[e].shape,t,"TensorList shape mismatch: ");const r=_f(this.elementShape,this.tensors,t);return vo(this.tensors[e],r)}setItem(e,t){if(t.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);if(e<0||-1!==this.maxNumElements&&e>=this.maxNumElements)throw new Error(`Trying to set element ${e} in a list with max ${this.maxNumElements} elements.`);Ef(this.elementShape,t.shape,"TensorList shape mismatch: "),Wa(t),null!=this.tensors[e]&&(this.tensors[e].kept=!1),this.tensors[e]=t}gather(e,t,n){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);Ef(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size());const r=_f(this.elementShape,this.tensors,n);return 0===e.length?Da([],[0].concat(r)):Ba(()=>{const t=e.map(e=>vo(this.tensors[e],r));return ec(t,0)})}concat(e,t){if(e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);Ef(this.elementShape,t,"TensorList shape mismatch: ");const n=_f(this.elementShape,this.tensors,t);return 0===this.size()?Da([],[0].concat(n)):Ba(()=>{const e=this.tensors.map(e=>vo(e,n));return Io(e,0)})}}const Df=async(e,t,n)=>{switch(e.op){case"If":case"StatelessIf":{const r=Lh("thenBranch",e,t,n),a=Lh("elseBranch",e,t,n),s=Lh("cond",e,t,n),o=Lh("args",e,t,n);return(await s.data())[0]?n.functionMap[r].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap):n.functionMap[a].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap)}case"While":case"StatelessWhile":{const r=Lh("body",e,t,n),a=Lh("cond",e,t,n),s=Lh("args",e,t,n),o=await n.functionMap[a].executeFunctionAsync(s,n.tensorArrayMap,n.tensorListMap),i=s.map(e=>e.id);let u=await o[0].data();o.forEach(e=>{e.kept||-1!==i.indexOf(e.id)||e.dispose()});let l=s;for(;u[0];){const e=l;l=await n.functionMap[r].executeFunctionAsync(l,n.tensorArrayMap,n.tensorListMap);const t=l.map(e=>e.id);e.forEach(e=>{e.kept||-1!==i.indexOf(e.id)||-1!==t.indexOf(e.id)||e.dispose()});const s=await n.functionMap[a].executeFunctionAsync(l,n.tensorArrayMap,n.tensorListMap);u=await s[0].data(),s.forEach(e=>{e.kept||-1!==i.indexOf(e.id)||-1!==t.indexOf(e.id)||e.dispose()})}return l}case"LoopCond":return[Hh(Lh("pred",e,t,n))];case"Switch":{const r=Lh("pred",e,t,n);let a=Lh("data",e,t,n);return a.kept||(a=Hh(a)),(await r.data())[0]?[void 0,a]:[a,void 0]}case"Merge":{const r=e.inputNames.find(e=>void 0!==Bh(e,t,n));if(r){return[Hh(Bh(r,t,n))]}return}case"Enter":{const r=Lh("frameName",e,t,n),a=Lh("tensor",e,t,n);return n.enterFrame(r),[Hh(a)]}case"Exit":{const r=Lh("tensor",e,t,n);return n.exitFrame(),[Hh(r)]}case"NextIteration":{const r=Lh("tensor",e,t,n);return n.nextIteration(),[Hh(r)]}case"TensorArrayV3":{const r=Lh("size",e,t,n),a=Lh("dtype",e,t,n),s=Lh("elementShape",e,t,n),o=Lh("dynamicSize",e,t,n),i=Lh("clearAfterRead",e,t,n),u=Lh("identicalElementShapes",e,t,n),l=Lh("name",e,t,n),c=new Of(l,a,r,s,u,o,i);return n.addTensorArray(c),[c.idTensor,Ri(1)]}case"TensorArrayWriteV3":{const r=Lh("tensorArrayId",e,t,n),a=Lh("index",e,t,n),s=Lh("tensor",e,t,n),o=n.getTensorArray(r.id);return o.write(a,s),[o.idTensor]}case"TensorArrayReadV3":{const r=Lh("tensorArrayId",e,t,n),a=Lh("index",e,t,n);return[n.getTensorArray(r.id).read(a)]}case"TensorArrayGatherV3":{const r=Lh("tensorArrayId",e,t,n),a=Lh("indices",e,t,n),s=Lh("dtype",e,t,n);return[n.getTensorArray(r.id).gather(a,s)]}case"TensorArrayScatterV3":{const r=Lh("tensorArrayId",e,t,n),a=Lh("indices",e,t,n),s=Lh("tensor",e,t,n),o=n.getTensorArray(r.id);return o.scatter(a,s),[o.idTensor]}case"TensorArrayConcatV3":{const r=Lh("tensorArrayId",e,t,n),a=n.getTensorArray(r.id),s=Lh("dtype",e,t,n);return[a.concat(s)]}case"TensorArraySplitV3":{const r=Lh("tensorArrayId",e,t,n),a=Lh("tensor",e,t,n),s=Lh("lengths",e,t,n),o=n.getTensorArray(r.id);return o.split(s,a),[o.idTensor]}case"TensorArraySizeV3":{const r=Lh("tensorArrayId",e,t,n);return[Ri(n.getTensorArray(r.id).size(),"int32")]}case"TensorArrayCloseV3":{const r=Lh("tensorArrayId",e,t,n),a=n.getTensorArray(r.id);return a.clearAndClose(),[a.idTensor]}case"TensorListSetItem":{const r=Lh("tensorListId",e,t,n),a=Lh("index",e,t,n),s=Lh("tensor",e,t,n),o=n.getTensorList(r.id);return o.setItem(a,s),[o.idTensor]}case"TensorListGetItem":{const r=Lh("tensorListId",e,t,n),a=Lh("index",e,t,n),s=Lh("elementShape",e,t,n),o=Lh("elementDType",e,t,n);return[n.getTensorList(r.id).getItem(a,s,o)]}case"TensorListScatterV2":case"TensorListScatter":{const r=Lh("indices",e,t,n),a=function(e,t,n,r){if(t.length!==e.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${t.length} vs. ${e.shape[0]}`);const a=Math.max(...t);if(null!=r&&-1!==r&&a>=r)throw new Error(`Max index must be < array size (${a} vs. ${r})`);const s=new Ff([],n,e.dtype,r),o=bc(e,0);return t.forEach((e,t)=>{s.setItem(e,o[t])}),s}(Lh("tensor",e,t,n),r,Lh("elementShape",e,t,n),Lh("numElements",e,t,n));return n.addTensorList(a),[a.idTensor]}case"TensorListReserve":case"EmptyTensorList":{const r=Lh("elementShape",e,t,n),a=Lh("elementDType",e,t,n);let s;s="TensorListReserve"===e.op?"numElements":"maxNumElements";const o=Lh(s,e,t,n),i=function(e,t,n,r){return new Ff([],e,t,r)}(r,a,0,"TensorListReserve"===e.op?-1:o);return n.addTensorList(i),[i.idTensor]}case"TensorListGather":{const r=Lh("tensorListId",e,t,n),a=Lh("indices",e,t,n),s=Lh("elementShape",e,t,n),o=Lh("elementDType",e,t,n);return[n.getTensorList(r.id).gather(a,o,s)]}case"TensorListStack":{const r=Lh("tensorListId",e,t,n),a=Lh("elementShape",e,t,n),s=Lh("elementDType",e,t,n),o=Lh("numElements",e,t,n);return[n.getTensorList(r.id).stack(a,s,o)]}case"TensorListFromTensor":{const r=function(e,t,n){const r=e.dtype;if(e.shape.length<1)throw new Error(`Tensor must be at least a vector, but saw shape: ${e.shape}`);if(e.dtype!==n)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${n}`);Ef(e.shape.slice(1),t,"TensorList shape mismatch: ");const a=bc(e);return new Ff(a,t,r)}(Lh("tensor",e,t,n),Lh("elementShape",e,t,n),Lh("elementDType",e,t,n));return n.addTensorList(r),[r.idTensor]}case"TensorListConcat":case"TensorListConcatV2":{const r=Lh("tensorListId",e,t,n),a=n.getTensorList(r.id),s=Lh("dtype",e,t,n),o=Lh("elementShape",e,t,n);return[a.concat(s,o)]}case"TensorListPushBack":{const r=Lh("tensorListId",e,t,n),a=Lh("tensor",e,t,n),s=n.getTensorList(r.id);return s.pushBack(a),[s.idTensor]}case"TensorListPopBack":{const r=Lh("tensorListId",e,t,n),a=Lh("elementShape",e,t,n),s=Lh("elementDType",e,t,n);return[n.getTensorList(r.id).popBack(a,s)]}case"TensorListSplit":{const r=Lh("tensor",e,t,n),a=Lh("elementShape",e,t,n),s=function(e,t,n){let r=0;const a=t.map(e=>(r+=e,r));if(r!==e.shape[0])throw new Error(`Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n ${r}, and tensor's shape is: ${e.shape}`);const s=Af(e.shape.slice(1),n),o=0===r?0:e.size/r,i=Ba(()=>{const n=[];e=vo(e,[1,r,o]);for(let r=0;re.dispose()),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}tensorSize(){return Ri(this.size(),"int32")}async import(e,t){this.checkKeyAndValueTensor(e,t);const n=await e.data();return this.tensorMap.forEach(e=>e.dispose()),this.tensorMap.clear(),Ba(()=>{const e=bc(t),r=n.length,a=e.length;i(r===a,()=>`The number of elements doesn't match, keys has ${r} elements, the values has ${a} elements.`);for(let t=0;t{const e=[];for(let r=0;r{switch(e.category){case"arithmetic":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[r.add(Lh("a",e,t,n),Lh("b",e,t,n))];case"AddN":return[r.addN(Lh("tensors",e,t,n))];case"FloorMod":case"Mod":return[r.mod(Lh("a",e,t,n),Lh("b",e,t,n))];case"Mul":return[r.mul(Lh("a",e,t,n),Lh("b",e,t,n))];case"RealDiv":case"Div":return[r.div(Lh("a",e,t,n),Lh("b",e,t,n))];case"DivNoNan":return[r.divNoNan(Lh("a",e,t,n),Lh("b",e,t,n))];case"FloorDiv":return[r.floorDiv(Lh("a",e,t,n),Lh("b",e,t,n))];case"Sub":return[r.sub(Lh("a",e,t,n),Lh("b",e,t,n))];case"Minimum":return[r.minimum(Lh("a",e,t,n),Lh("b",e,t,n))];case"Maximum":return[r.maximum(Lh("a",e,t,n),Lh("b",e,t,n))];case"Pow":return[r.pow(Lh("a",e,t,n),Lh("b",e,t,n))];case"SquaredDifference":return[r.squaredDifference(Lh("a",e,t,n),Lh("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"basic_math":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"Abs":case"ComplexAbs":return[r.abs(Lh("x",e,t,n))];case"Acos":return[r.acos(Lh("x",e,t,n))];case"Acosh":return[r.acosh(Lh("x",e,t,n))];case"Asin":return[r.asin(Lh("x",e,t,n))];case"Asinh":return[r.asinh(Lh("x",e,t,n))];case"Atan":return[r.atan(Lh("x",e,t,n))];case"Atan2":return[r.atan2(Lh("x",e,t,n),Lh("y",e,t,n))];case"Atanh":return[r.atanh(Lh("x",e,t,n))];case"Ceil":return[r.ceil(Lh("x",e,t,n))];case"Complex":return[r.complex(Lh("real",e,t,n),Lh("imag",e,t,n))];case"Cos":return[r.cos(Lh("x",e,t,n))];case"Cosh":return[r.cosh(Lh("x",e,t,n))];case"Elu":return[r.elu(Lh("x",e,t,n))];case"Erf":return[r.erf(Lh("x",e,t,n))];case"Exp":return[r.exp(Lh("x",e,t,n))];case"Expm1":return[r.expm1(Lh("x",e,t,n))];case"Floor":return[r.floor(Lh("x",e,t,n))];case"Log":return[r.log(Lh("x",e,t,n))];case"Log1p":return[r.log1p(Lh("x",e,t,n))];case"Imag":return[r.imag(Lh("x",e,t,n))];case"Neg":return[r.neg(Lh("x",e,t,n))];case"Reciprocal":return[r.reciprocal(Lh("x",e,t,n))];case"Real":return[r.real(Lh("x",e,t,n))];case"Relu":return[r.relu(Lh("x",e,t,n))];case"Round":return[r.round(Lh("x",e,t,n))];case"Selu":return[r.selu(Lh("x",e,t,n))];case"Sigmoid":return[r.sigmoid(Lh("x",e,t,n))];case"Sin":return[r.sin(Lh("x",e,t,n))];case"Sign":return[r.sign(Lh("x",e,t,n))];case"Sinh":return[r.sinh(Lh("x",e,t,n))];case"Softplus":return[r.softplus(Lh("x",e,t,n))];case"Sqrt":return[r.sqrt(Lh("x",e,t,n))];case"Square":return[r.square(Lh("x",e,t,n))];case"Tanh":return[r.tanh(Lh("x",e,t,n))];case"Tan":return[r.tan(Lh("x",e,t,n))];case"ClipByValue":return[r.clipByValue(Lh("x",e,t,n),Lh("clipValueMin",e,t,n),Lh("clipValueMax",e,t,n))];case"Relu6":return[r.relu6(Lh("x",e,t,n))];case"Rsqrt":return[r.rsqrt(Bh(e.inputNames[0],t,n))];case"LeakyRelu":return[r.leakyRelu(Lh("x",e,t,n),Lh("alpha",e,t,n))];case"Prelu":return[r.prelu(Lh("x",e,t,n),Lh("alpha",e,t,n))];case"IsNan":return[r.isNaN(Bh(e.inputNames[0],t,n))];case"IsInf":return[r.isInf(Bh(e.inputNames[0],t,n))];case"IsFinite":return[r.isFinite(Bh(e.inputNames[0],t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"control":return Df(e,t,n);case"convolution":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"Conv1D":{const a=Lh("stride",e,t,n),s=Lh("pad",e,t,n),o=Lh("dataFormat",e,t,n).toUpperCase(),i=Lh("dilation",e,t,n);return[r.conv1d(Lh("x",e,t,n),Lh("filter",e,t,n),a,s,o,i)]}case"Conv2D":{const a=Lh("strides",e,t,n),s=Gh(e,t,n),o=Lh("dataFormat",e,t,n).toUpperCase(),i=Lh("dilations",e,t,n);return[r.conv2d(Lh("x",e,t,n),Lh("filter",e,t,n),[a[1],a[2]],s,o,[i[1],i[2]])]}case"_FusedConv2D":{const{stride:a,pad:s,dataFormat:o,dilations:i,biasArg:u,preluArg:l,activationFunc:c,leakyreluAlpha:d}=Mf(e,t,n);return[r.fused.conv2d({x:Lh("x",e,t,n),filter:Lh("filter",e,t,n),strides:[a[1],a[2]],pad:s,dataFormat:o,dilations:[i[1],i[2]],bias:u,activation:c,preluActivationWeights:l,leakyreluAlpha:d})]}case"FusedDepthwiseConv2dNative":{const{stride:a,pad:s,dataFormat:o,dilations:i,biasArg:u,preluArg:l,activationFunc:c,leakyreluAlpha:d}=Mf(e,t,n);return[r.fused.depthwiseConv2d({x:Lh("x",e,t,n),filter:Lh("filter",e,t,n),strides:[a[1],a[2]],pad:s,dataFormat:o,dilations:[i[1],i[2]],bias:u,activation:c,preluActivationWeights:l,leakyreluAlpha:d})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{const a=Lh("outputShape",e,t,n),s=Lh("strides",e,t,n),o=Gh(e,t,n);return[r.conv2dTranspose(Lh("x",e,t,n),Lh("filter",e,t,n),a,[s[1],s[2]],o)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{const a=Lh("strides",e,t,n),s=Gh(e,t,n),o=Lh("dilations",e,t,n),i=Lh("dataFormat",e,t,n).toUpperCase();return[r.depthwiseConv2d(Lh("input",e,t,n),Lh("filter",e,t,n),[a[1],a[2]],s,i,[o[1],o[2]])]}case"Conv3D":{const a=Lh("strides",e,t,n),s=Lh("pad",e,t,n),o=Lh("dataFormat",e,t,n).toUpperCase(),i=Lh("dilations",e,t,n);return[r.conv3d(Lh("x",e,t,n),Lh("filter",e,t,n),[a[1],a[2],a[3]],s,o,[i[1],i[2],i[3]])]}case"AvgPool":{const a=Lh("strides",e,t,n),s=Lh("pad",e,t,n),o=Lh("kernelSize",e,t,n);return[r.avgPool(Lh("x",e,t,n),[o[1],o[2]],[a[1],a[2]],s)]}case"MaxPool":{const a=Lh("strides",e,t,n),s=Lh("pad",e,t,n),o=Lh("kernelSize",e,t,n);return[r.maxPool(Lh("x",e,t,n),[o[1],o[2]],[a[1],a[2]],s)]}case"MaxPoolWithArgmax":{const a=Lh("strides",e,t,n),s=Lh("pad",e,t,n),o=Lh("kernelSize",e,t,n),i=Lh("includeBatchInIndex",e,t,n),{result:u,indexes:l}=r.maxPoolWithArgmax(Lh("x",e,t,n),[o[1],o[2]],[a[1],a[2]],s,i);return[u,l]}case"AvgPool3D":{const a=Lh("strides",e,t,n),s=Lh("pad",e,t,n),o=Lh("kernelSize",e,t,n);return[r.avgPool3d(Lh("x",e,t,n),[o[1],o[2],o[3]],[a[1],a[2],a[3]],s)]}case"MaxPool3D":{const a=Lh("strides",e,t,n),s=Lh("pad",e,t,n),o=Lh("kernelSize",e,t,n);return[r.maxPool3d(Lh("x",e,t,n),[o[1],o[2],o[3]],[a[1],a[2],a[3]],s)]}case"Dilation2D":{const a=Lh("strides",e,t,n),s=Lh("pad",e,t,n),o=Lh("dilations",e,t,n),i=a[1],u=a[2],l=o[1],c=o[2];return[r.dilation2d(Lh("x",e,t,n),Lh("filter",e,t,n),[i,u],s,[l,c],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"creation":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"Fill":{const a=Lh("shape",e,t,n),s=Lh("dtype",e,t,n),o=Lh("value",e,t,n);return[r.fill(a,o,s)]}case"LinSpace":{const a=Lh("start",e,t,n),s=Lh("stop",e,t,n),o=Lh("num",e,t,n);return[r.linspace(a,s,o)]}case"Multinomial":{const a=Lh("logits",e,t,n),s=Lh("numSamples",e,t,n),o=Lh("seed",e,t,n);return[r.multinomial(a,s,o)]}case"OneHot":{const a=Lh("indices",e,t,n),s=Lh("depth",e,t,n),o=Lh("onValue",e,t,n),i=Lh("offValue",e,t,n),u=Lh("dtype",e,t,n);return[r.oneHot(a,s,o,i,u)]}case"Ones":return[r.ones(Lh("shape",e,t,n),Lh("dtype",e,t,n))];case"OnesLike":return[r.onesLike(Lh("x",e,t,n))];case"RandomStandardNormal":return[r.randomStandardNormal(Lh("shape",e,t,n),Lh("dtype",e,t,n),Lh("seed",e,t,n))];case"RandomUniform":return[r.randomUniform(Lh("shape",e,t,n),Lh("minval",e,t,n),Lh("maxval",e,t,n),Lh("dtype",e,t,n))];case"RandomUniformInt":return[r.randomUniformInt(Lh("shape",e,t,n),Lh("minval",e,t,n),Lh("maxval",e,t,n),Lh("seed",e,t,n))];case"Range":{const a=Lh("start",e,t,n),s=Lh("stop",e,t,n),o=Lh("step",e,t,n);return[r.range(a,s,o,Lh("dtype",e,t,n))]}case"TruncatedNormal":{const a=Lh("shape",e,t,n),s=Lh("mean",e,t,n),o=Lh("stdDev",e,t,n),i=Lh("seed",e,t,n);return[r.truncatedNormal(a,s,o,Lh("dtype",e,t,n),i)]}case"Zeros":return[r.zeros(Lh("shape",e,t,n),Lh("dtype",e,t,n))];case"ZerosLike":return[r.zerosLike(Lh("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"dynamic":return(async(e,t,n,r,a=$f)=>{switch(e.op){case"NonMaxSuppressionV5":{const{boxes:r,scores:s,maxOutputSize:o,iouThreshold:i,scoreThreshold:u,softNmsSigma:l}=Pf(e,t,n),c=await a.image.nonMaxSuppressionWithScoreAsync(r,s,o,i,u,l);return[c.selectedIndices,c.selectedScores]}case"NonMaxSuppressionV4":{const{boxes:r,scores:s,maxOutputSize:o,iouThreshold:i,scoreThreshold:u}=Pf(e,t,n),l=Lh("padToMaxOutputSize",e,t,n),c=await a.image.nonMaxSuppressionPaddedAsync(r,s,o,i,u,l);return[c.selectedIndices,c.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{const{boxes:r,scores:s,maxOutputSize:o,iouThreshold:i,scoreThreshold:u}=Pf(e,t,n);return[await a.image.nonMaxSuppressionAsync(r,s,o,i,u)]}case"Where":{const r=a.cast(Lh("condition",e,t,n),"bool"),s=[await a.whereAsync(r)];return r.dispose(),s}case"ListDiff":return a.setdiff1dAsync(Lh("x",e,t,n),Lh("y",e,t,n));default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n);case"evaluation":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"LowerBound":{const a=Lh("sortedSequence",e,t,n),s=Lh("values",e,t,n);return[r.lowerBound(a,s)]}case"TopKV2":{const a=Lh("x",e,t,n),s=Lh("k",e,t,n),o=Lh("sorted",e,t,n),i=r.topk(a,s,o);return[i.values,i.indices]}case"UpperBound":{const a=Lh("sortedSequence",e,t,n),s=Lh("values",e,t,n);return[r.upperBound(a,s)]}case"Unique":{const a=Lh("x",e,t,n),s=r.unique(a);return[s.values,s.indices]}case"UniqueV2":{const a=Lh("x",e,t,n),s=Lh("axis",e,t,n),o=r.unique(a,s);return[o.values,o.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"image":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"ResizeBilinear":{const a=Lh("images",e,t,n),s=Lh("size",e,t,n),o=Lh("alignCorners",e,t,n),i=Lh("halfPixelCenters",e,t,n);return[r.image.resizeBilinear(a,[s[0],s[1]],o,i)]}case"ResizeNearestNeighbor":{const a=Lh("images",e,t,n),s=Lh("size",e,t,n),o=Lh("alignCorners",e,t,n),i=Lh("halfPixelCenters",e,t,n);return[r.image.resizeNearestNeighbor(a,[s[0],s[1]],o,i)]}case"CropAndResize":{const a=Lh("image",e,t,n),s=Lh("boxes",e,t,n),o=Lh("boxInd",e,t,n),i=Lh("cropSize",e,t,n),u=Lh("method",e,t,n),l=Lh("extrapolationValue",e,t,n);return[r.image.cropAndResize(a,s,o,i,u,l)]}case"ImageProjectiveTransformV3":{const a=Lh("images",e,t,n),s=Lh("transforms",e,t,n),o=Lh("outputShape",e,t,n),i=Lh("fillValue",e,t,n),u=Lh("interpolation",e,t,n),l=Lh("fillMode",e,t,n);return[r.image.transform(a,s,u.toLowerCase(),l.toLowerCase(),i,o)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"graph":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":const a=Lh("default",e,t,n);return[Bh(e.name,t,n)||a];case"Placeholder":return[Bh(e.name,t,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":case"Snapshot":return[Hh(Lh("x",e,t,n))];case"IdentityN":return Lh("x",e,t,n).map(e=>Hh(e));case"Shape":return[r.tensor1d(Lh("x",e,t,n).shape,"int32")];case"ShapeN":return Lh("x",e,t,n).map(e=>r.tensor1d(e.shape));case"Size":return[r.scalar(Lh("x",e,t,n).size,"int32")];case"Rank":return[r.scalar(Lh("x",e,t,n).rank,"int32")];case"NoOp":return[r.scalar(1)];case"Print":const s=Lh("x",e,t,n),o=Lh("data",e,t,n),i=Lh("message",e,t,n),u=Lh("summarize",e,t,n);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(i);for(let e=0;e((e,t,n,r=$f)=>{switch(e.op){case"Equal":return[r.equal(Lh("a",e,t,n),Lh("b",e,t,n))];case"NotEqual":return[r.notEqual(Lh("a",e,t,n),Lh("b",e,t,n))];case"Greater":return[r.greater(Lh("a",e,t,n),Lh("b",e,t,n))];case"GreaterEqual":return[r.greaterEqual(Lh("a",e,t,n),Lh("b",e,t,n))];case"Less":return[r.less(Lh("a",e,t,n),Lh("b",e,t,n))];case"LessEqual":return[r.lessEqual(Lh("a",e,t,n),Lh("b",e,t,n))];case"LogicalAnd":return[r.logicalAnd(Lh("a",e,t,n),Lh("b",e,t,n))];case"LogicalNot":return[r.logicalNot(Lh("a",e,t,n))];case"LogicalOr":return[r.logicalOr(Lh("a",e,t,n),Lh("b",e,t,n))];case"Select":case"SelectV2":return[r.where(Lh("condition",e,t,n),Lh("a",e,t,n),Lh("b",e,t,n))];case"BitwiseAnd":return[r.bitwiseAnd(Lh("a",e,t,n),Lh("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"matrices":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[r.matMul(Lh("a",e,t,n),Lh("b",e,t,n),Lh("transposeA",e,t,n),Lh("transposeB",e,t,n))];case"Einsum":return[r.einsum(Lh("equation",e,t,n),...Lh("tensors",e,t,n))];case"Transpose":return[r.transpose(Lh("x",e,t,n),Lh("perm",e,t,n))];case"_FusedMatMul":const[a,s]=Lh("fusedOps",e,t,n),o="biasadd"===a,i="prelu"===s,u=Lh("numArgs",e,t,n),l=Lh("leakyreluAlpha",e,t,n);if(o){if(i&&2!==u)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!i&&1!==u)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}const[c,d]=Lh("args",e,t,n);return[r.fused.matMul({a:Lh("a",e,t,n),b:Lh("b",e,t,n),transposeA:Lh("transposeA",e,t,n),transposeB:Lh("transposeB",e,t,n),bias:c,activation:s,preluActivationWeights:d,leakyreluAlpha:l})];case"MatrixBandPart":return[r.linalg.bandPart(Lh("a",e,t,n),Lh("numLower",e,t,n),Lh("numUpper",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"normalization":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"EuclideanNorm":return[r.euclideanNorm(Lh("x",e,t,n),Lh("axis",e,t,n),Lh("keepDims",e,t,n))];case"FusedBatchNorm":case"FusedBatchNormV2":case"FusedBatchNormV3":return[r.batchNorm(Lh("x",e,t,n),Lh("mean",e,t,n),Lh("variance",e,t,n),Lh("offset",e,t,n),Lh("scale",e,t,n),Lh("epsilon",e,t,n))];case"LRN":return[r.localResponseNormalization(Lh("x",e,t,n),Lh("radius",e,t,n),Lh("bias",e,t,n),Lh("alpha",e,t,n),Lh("beta",e,t,n))];case"Softmax":return[r.softmax(Lh("x",e,t,n))];case"LogSoftmax":return[r.logSoftmax(Lh("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"ragged":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"RaggedGather":{const{outputNestedSplits:a,outputDenseValues:s}=r.raggedGather(Lh("paramsNestedSplits",e,t,n),Lh("paramsDenseValues",e,t,n),Lh("indices",e,t,n),Lh("outputRaggedRank",e,t,n));return a.concat(s)}case"RaggedRange":{const{rtNestedSplits:a,rtDenseValues:s}=r.raggedRange(Lh("starts",e,t,n),Lh("limits",e,t,n),Lh("splits",e,t,n));return[a,s]}case"RaggedTensorToTensor":return[r.raggedTensorToTensor(Lh("shape",e,t,n),Lh("values",e,t,n),Lh("defaultValue",e,t,n),Lh("rowPartitionTensors",e,t,n),Lh("rowPartitionTypes",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"reduction":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"Max":{const a=Lh("axis",e,t,n),s=Lh("keepDims",e,t,n);return[r.max(Lh("x",e,t,n),a,s)]}case"Mean":{const a=Lh("axis",e,t,n),s=Lh("keepDims",e,t,n);return[r.mean(Lh("x",e,t,n),a,s)]}case"Min":{const a=Lh("axis",e,t,n),s=Lh("keepDims",e,t,n);return[r.min(Lh("x",e,t,n),a,s)]}case"Sum":{const a=Lh("axis",e,t,n),s=Lh("keepDims",e,t,n);return[r.sum(Lh("x",e,t,n),a,s)]}case"All":{const a=Lh("axis",e,t,n),s=Lh("keepDims",e,t,n);return[r.all(Lh("x",e,t,n),a,s)]}case"Any":{const a=Lh("axis",e,t,n),s=Lh("keepDims",e,t,n);return[r.any(Lh("x",e,t,n),a,s)]}case"ArgMax":{const a=Lh("axis",e,t,n);return[r.argMax(Lh("x",e,t,n),a)]}case"ArgMin":{const a=Lh("axis",e,t,n);return[r.argMin(Lh("x",e,t,n),a)]}case"Prod":{const a=Lh("axis",e,t,n),s=Lh("keepDims",e,t,n);return[r.prod(Lh("x",e,t,n),a,s)]}case"Cumprod":{const a=Lh("axis",e,t,n),s=Lh("exclusive",e,t,n),o=Lh("reverse",e,t,n);return[r.cumprod(Lh("x",e,t,n),a,s,o)]}case"Cumsum":{const a=Lh("axis",e,t,n),s=Lh("exclusive",e,t,n),o=Lh("reverse",e,t,n);return[r.cumsum(Lh("x",e,t,n),a,s,o)]}case"Bincount":const a=Lh("x",e,t,n),s=Lh("weights",e,t,n),o=Lh("size",e,t,n);return[r.bincount(a,s,o)];case"DenseBincount":{const a=Lh("x",e,t,n),s=Lh("weights",e,t,n),o=Lh("size",e,t,n),i=Lh("binaryOutput",e,t,n);return[r.denseBincount(a,s,o,i)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"slice_join":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"ConcatV2":case"Concat":{const a=Lh("n",e,t,n),s=Lh("axis",e,t,n);let o=Lh("tensors",e,t,n);return o=o.slice(0,a),[r.concat(o,s)]}case"Gather":{const a=Lh("x",e,t,n),s=Lh("indices",e,t,n);return[r.gather(a,r.cast(s,"int32"),0)]}case"GatherV2":{const a=Lh("axis",e,t,n),s=Lh("batchDims",e,t,n),o=Lh("x",e,t,n),i=Lh("indices",e,t,n);return[r.gather(o,r.cast(i,"int32"),a,s)]}case"Reverse":{const a=Lh("dims",e,t,n),s=[];for(let e=0;e{const a=Lh("axis",e,t,n),s=Lh("tensors",e,t,n),o=s[0].shape,i=r.squeeze(s[0]).shape,u=s.map(e=>{const t=d(e.shape,o);if(!t&&!d(r.squeeze(e).shape,i))throw new Error("the input tensors shape does not match");return t?e:r.reshape(e,o)});return[r.stack(u,a)]});case"Unpack":{const a=Lh("axis",e,t,n),s=Lh("tensor",e,t,n);return r.unstack(s,a)}case"Tile":{const a=Lh("reps",e,t,n);return[r.tile(Lh("x",e,t,n),a)]}case"Split":case"SplitV":{const a=Lh("axis",e,t,n),s=Lh("numOrSizeSplits",e,t,n),o=Lh("x",e,t,n);return r.split(o,s,a)}case"ScatterNd":{const a=Lh("indices",e,t,n),s=Lh("values",e,t,n),o=Lh("shape",e,t,n);return[r.scatterND(a,s,o)]}case"GatherNd":{const a=Lh("x",e,t,n),s=Lh("indices",e,t,n);return[r.gatherND(a,s)]}case"SparseToDense":{const a=Lh("sparseIndices",e,t,n),s=Lh("outputShape",e,t,n),o=Lh("sparseValues",e,t,n),i=Lh("defaultValue",e,t,n);return[r.sparseToDense(a,o,s,o.dtype===i.dtype?i:r.cast(i,o.dtype))]}case"TensorScatterUpdate":{const a=Lh("indices",e,t,n),s=Lh("values",e,t,n),o=Lh("tensor",e,t,n);return[r.tensorScatterUpdate(o,a,s)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"sparse":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"SparseFillEmptyRows":{const{outputIndices:a,outputValues:s,emptyRowIndicator:o,reverseIndexMap:i}=r.sparse.sparseFillEmptyRows(Lh("indices",e,t,n),Lh("values",e,t,n),Lh("denseShape",e,t,n),Lh("defaultValue",e,t,n));return[a,s,o,i]}case"SparseReshape":{const{outputIndices:a,outputShape:s}=r.sparse.sparseReshape(Lh("inputIndices",e,t,n),Lh("inputShape",e,t,n),Lh("newShape",e,t,n));return[a,s]}case"SparseSegmentMean":return[r.sparse.sparseSegmentMean(Lh("data",e,t,n),Lh("indices",e,t,n),Lh("segmentIds",e,t,n))];case"SparseSegmentSum":return[r.sparse.sparseSegmentSum(Lh("data",e,t,n),Lh("indices",e,t,n),Lh("segmentIds",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"spectral":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"FFT":return[r.fft(Lh("x",e,t,n))];case"IFFT":return[r.ifft(Lh("x",e,t,n))];case"RFFT":return[r.rfft(Lh("x",e,t,n))];case"IRFFT":return[r.irfft(Lh("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"string":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"StaticRegexReplace":return[r.string.staticRegexReplace(Lh("input",e,t,n),Lh("pattern",e,t,n),Lh("rewrite",e,t,n),Lh("replaceGlobal",e,t,n))];case"StringNGrams":{const{nGrams:a,nGramsSplits:s}=r.string.stringNGrams(Lh("data",e,t,n),Lh("dataSplits",e,t,n),Lh("separator",e,t,n),Lh("nGramWidths",e,t,n),Lh("leftPad",e,t,n),Lh("rightPad",e,t,n),Lh("padWidth",e,t,n),Lh("preserveShortSequences",e,t,n));return[a,s]}case"StringSplit":{const{indices:a,values:s,shape:o}=r.string.stringSplit(Lh("input",e,t,n),Lh("delimiter",e,t,n),Lh("skipEmpty",e,t,n));return[a,s,o]}case"StringToHashBucketFast":return[r.string.stringToHashBucketFast(Lh("input",e,t,n),Lh("numBuckets",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"transformation":return a(()=>((e,t,n,r=$f)=>{switch(e.op){case"Cast":return[r.cast(Lh("x",e,t,n),Lh("dtype",e,t,n))];case"ExpandDims":{const a=Lh("axis",e,t,n);return[r.expandDims(Lh("x",e,t,n),a)]}case"Squeeze":{const a=Lh("axis",e,t,n);return[r.squeeze(Lh("x",e,t,n),a)]}case"Reshape":return[r.reshape(Lh("x",e,t,n),Lh("shape",e,t,n))];case"EnsureShape":return[r.ensureShape(Lh("x",e,t,n),Lh("shape",e,t,n))];case"MirrorPad":return[r.mirrorPad(Lh("x",e,t,n),Lh("padding",e,t,n),Lh("mode",e,t,n))];case"PadV2":case"Pad":return[r.pad(Lh("x",e,t,n),Lh("padding",e,t,n),Lh("constantValue",e,t,n))];case"SpaceToBatchND":{const a=Lh("blockShape",e,t,n),s=Lh("paddings",e,t,n);return[r.spaceToBatchND(Lh("x",e,t,n),a,s)]}case"BatchToSpaceND":{const a=Lh("blockShape",e,t,n),s=Lh("crops",e,t,n);return[r.batchToSpaceND(Lh("x",e,t,n),a,s)]}case"DepthToSpace":{const a=Lh("blockSize",e,t,n),s=Lh("dataFormat",e,t,n).toUpperCase();return[r.depthToSpace(Lh("x",e,t,n),a,s)]}case"BroadcastTo":return[r.broadcastTo(Lh("x",e,t,n),Lh("shape",e,t,n))];case"BroadcastArgs":return[r.broadcastArgs(Lh("s0",e,t,n),Lh("s1",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n));case"hash_table":return(async(e,t,n,r)=>{switch(e.op){case"HashTable":case"HashTableV2":{const a=r.getHashTableHandleByName(e.name);if(null!=a)return[a];{const a=Lh("keyDType",e,t,n),s=Lh("valueDType",e,t,n),o=new Lf(a,s);return r.addHashTable(e.name,o),[o.handle]}}case"InitializeTable":case"InitializeTableV2":case"LookupTableImport":case"LookupTableImportV2":{const a=Lh("tableHandle",e,t,n,r),s=Lh("keys",e,t,n),o=Lh("values",e,t,n),i=r.getHashTableById(a.id);return[await i.import(s,o)]}case"LookupTableFind":case"LookupTableFindV2":{const a=Lh("tableHandle",e,t,n,r),s=Lh("keys",e,t,n),o=Lh("defaultValue",e,t,n),i=r.getHashTableById(a.id);return[await i.find(s,o)]}case"LookupTableSize":case"LookupTableSizeV2":{const a=Lh("tableHandle",e,t,n,r);return[r.getHashTableById(a.id).tensorSize()]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n,r);case"custom":const s=Ph(e.op);if(s&&s.customExecutor)return s.customExecutor(new Cf(e,t,n));throw TypeError(`Custom op ${e.op} is not registered.`);default:throw TypeError(`Unknown op '${e.op}'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()`)}})(e,t,n);return M(s)?s.then(e=>[].concat(e)):[].concat(s)}class Vf{constructor(e={},t={},n={},r={},a){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=n,this.functionMap=r,this.parseNodeNameCache=a,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds()}newFrame(e,t){return{id:e,frameName:t,iterationId:0}}set currentContext(e){this.contexts!==e&&(this.contexts=e,this.generateCurrentContextIds())}get currentContext(){return this.contexts}get currentContextId(){return this._currentContextIds[0]}get currentContextIds(){return this._currentContextIds}generateCurrentContextIds(){const e=[];for(let t=0;t0===e.id&&0===e.iterationId?"":`${e.frameName}-${e.iterationId}`).join("/"):""}enterFrame(e){this.contexts&&(this.lastId++,this.contexts=this.contexts.slice(),this.contexts.push(this.newFrame(this.lastId,e)),this._currentContextIds.unshift(this.contextIdforContexts(this.contexts)))}exitFrame(){if(!(this.contexts&&this.contexts.length>1))throw new Error("Cannot exit frame, the context is empty");this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift()}nextIteration(){if(!(this.contexts&&this.contexts.length>0))throw new Error("Cannot increase frame iteration, the context is empty");{this.contexts=this.contexts.slice(),this.lastId++;const e=Object.assign({},this.contexts[this.contexts.length-1]);e.iterationId+=1,e.id=this.lastId,this.contexts.splice(-1,1,e),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))}}getWeight(e){return this.weightMap[e]}addTensorArray(e){this.tensorArrayMap[e.id]=e}getTensorArray(e){return this.tensorArrayMap[e]}addTensorList(e){this.tensorListMap[e.id]=e}getTensorList(e){return this.tensorListMap[e]}dispose(e){for(const t in this.tensorArrayMap)this.tensorArrayMap[t].clearAndClose(e);for(const t in this.tensorListMap)this.tensorListMap[t].clearAndClose(e)}}function Wf(e,t,n,r){const a=/* @__PURE__ */new Set,s=[];let o=null,i=null;const u=/* @__PURE__ */new Set,l=new Set(Object.keys(e).map(e=>Uh(e)[0]));r=r||[];const c=new Set(r.map(e=>Uh(e.name)[0])),d=[...t];for(;d.length>0;){const e=d.pop();(qf(e)||Kf(e)||Xf(e))&&null==o&&(o=e,i=o.children.map(e=>e.name).filter(e=>a.has(e))),a.add(e.name),null==n[e.name]&&(l.has(e.name)||c.has(e.name)||(0!==e.inputs.length?e.inputs.forEach(e=>{u.has(e.name)||(u.add(e.name),d.push(e))}):s.push(e.name)))}return{inputs:e,outputs:t,usedNodes:a,missingInputs:s,dynamicNode:o,syncInputs:i}}function zf(e,t){const{usedNodes:n,inputs:r}=t,a=Object.keys(r).map(e=>Uh(e)[0]).map(t=>e.nodes[t]),s=e.initNodes||[],o=e=>n.has("string"===typeof e?e:e.name);function i(e){return[...new Map(e.map(e=>[e.name,e])).values()]}const u=i([...a,...e.weights,...s]).filter(o),l=i([...u,...Object.values(e.nodes)]).filter(o),c=new Map(l.map(e=>[e.name,e])),d={};for(const m of l){d[m.name]=d[m.name]||0;for(const e of m.children)o(e)||(d[e.name]=Number.POSITIVE_INFINITY),d[e.name]=(d[e.name]||0)+1}const p=Object.entries(d).filter(([,e])=>0===e).map(([e])=>e),h=[...p];for(;p.length>0;){const e=p.pop(),t=c.get(e);for(const n of t.children.filter(o))0===--d[n.name]&&(h.push(n.name),p.push(n.name))}const f=function(e,t){const n=new Map(e.map(e=>[e.name,e])),r=t.map(e=>e.name),a=new Set(r);for(;r.length>0;){const e=r.pop(),t=n.get(e);for(const s of t.children)n.has(s.name)&&!a.has(s.name)&&(a.add(s.name),r.push(s.name))}const s=e.filter(e=>a.has(e.name));return s}(h.map(e=>c.get(e)),u);return function(e,t){const n=new Map(e.map((e,t)=>[e.name,t])),r=new Set(t.map(e=>e.name)),a=e=>r.has("string"===typeof e?e:e.name),s=new Set(e.map(e=>e.name)),o=e=>s.has("string"===typeof e?e:e.name);for(const i of e){for(const e of i.children.filter(o)){if(!n.has(e.name))throw new Uf(`Child ${e.name} of node ${i.name} is unreachable.`);if(n.get(i.name)>n.get(e.name))throw new Uf(`Node ${i.name} is scheduled to run after its child ${e.name}.`)}if(!a(i))for(const e of i.inputs){if(!n.has(e.name))throw new Uf(`Input ${e.name} of node ${i.name} is unreachable.`);if(n.get(e.name)>n.get(i.name))throw new Uf(`Node ${i.name} is scheduled to run before its input ${e.name}.`)}}}(f,u),f}class Uf extends Error{constructor(e){super(`NodesExecutionOrderError: ${e}`)}}const Gf=/* @__PURE__ */new Set(["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"]),Hf=/* @__PURE__ */new Set(["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"]),jf=/* @__PURE__ */new Set(["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"]);function qf(e){return Gf.has(e.op)}function Kf(e){return Hf.has(e.op)}function Xf(e){return jf.has(e.op)}class Yf{get weightIds(){return this.parent?this.parent.weightIds:this._weightIds}get functionExecutorMap(){return this.parent?this.parent.functionExecutorMap:this._functionExecutorMap}get weightMap(){return this.parent?this.parent.weightMap:this._weightMap}set weightMap(e){const t=Object.keys(e).map(t=>e[t].map(e=>e.id));this._weightIds=[].concat(...t),this._weightMap=e}set resourceManager(e){this._resourceManager=e}get inputs(){return this._inputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get outputs(){return this._outputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get inputNodes(){return this._inputs.map(e=>e.signatureKey||e.name)}get outputNodes(){return this._outputs.map(e=>{const t=e.signatureKey||e.name;return e.defaultOutput?`${t}:${e.defaultOutput}`:t})}get functions(){return Object.keys(this._functions).reduce((e,t)=>(e[t]=this._functions[t].signature,e),{})}constructor(e,t){this.graph=e,this.parent=t,this.compiledMap=/* @__PURE__ */new Map,this.parseNodeNameCache=/* @__PURE__ */new Map,this._weightMap={},this.SEPARATOR=",",this._functions={},this._functionExecutorMap={},this.keepIntermediateTensors=!1,this._outputs=e.outputs,this._inputs=e.inputs,this._initNodes=e.initNodes,this._signature=e.signature,this._functions=e.functions,null!=e.functions&&Object.keys(e.functions).forEach(t=>{this._functionExecutorMap[t]=new Yf(e.functions[t],this)})}getCompilationKey(e,t){const n=e.map(e=>e.name).sort(),r=t.map(e=>e.name).sort();return n.join(this.SEPARATOR)+"--"+r.join(this.SEPARATOR)}compile(e,t){const n=Wf(e,t,this.weightMap,this._initNodes),{missingInputs:r,dynamicNode:a,syncInputs:s}=n;if(null!=a)throw new Error(`This execution contains the node '${a.name}', which has the dynamic op '${a.op}'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs [${s}]`);if(r.length>0){const n=t.map(e=>e.name),a=Object.keys(e);throw new Error(`Cannot compute the outputs [${n}] from the provided inputs [${a}]. Missing the following inputs: [${r}]`)}const o=zf(this.graph,n),i=function(e){const t=new Map(e.map((e,t)=>[e.name,t])),n=Number.MAX_SAFE_INTEGER,r=e.map((e,t)=>qf(e)?n:t),a=e=>r[t.get(e.name)]??-1,s=e.map((e,t)=>e.children.map(a).reduce((e,t)=>Math.max(e,t),r[t])),o=/* @__PURE__ */new Map;for(let i=0;ithis.cloneAndKeepTensor(e))}cloneTensorMap(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,this.cloneTensorList(t)]))}execute(e,t){this.disposeIntermediateTensors(),e=this.mapInputs(e);const n=Object.keys(e).sort();this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t);const r=n.map(e=>this.graph.nodes[Uh(e)[0]]),a=t.map(e=>Uh(e)[0]),s=new Set(a);let o=a.map(e=>this.graph.nodes[e]);0===o.length&&(o=this._outputs);const i=this.getCompilationKey(r,o);let u=this.compiledMap.get(i);null==u&&(u=this.compile(e,o),this.compiledMap.set(i,u));try{this.keepIntermediateTensors=V().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(d){this.keepIntermediateTensors=!1,console.warn(d.message)}const l={},c={};return Ba(()=>{const n=new Vf(this.weightMap,l,c,this.functionExecutorMap,this.parseNodeNameCache),r=Object.assign({},this.weightMap);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap)),Object.keys(e).forEach(t=>{const[a,s]=Uh(t,n),o=[];o[s]=e[t],r[a]=o,this.keepIntermediateTensors&&(this.clonedTensorsMap[a]=this.cloneTensorList(o))});const a=this.getFrozenTensorIds(r),{orderedNodes:o,nodeLiveUntilMap:i}=u;for(const e of o){if(r[e.name])continue;const t=Bf(e,r,n,this._resourceManager);if(M(t))throw new Error(`The execution of the op '${e.op}' returned a promise. Please use model.executeAsync() instead.`);r[e.name]=t,this.keepIntermediateTensors&&(this.clonedTensorsMap[e.name]=this.cloneTensorList(t)),this.checkTensorForDisposalWithNodeLiveUntilInfo(e,r,n,a,s,i.get(e.name))}return null==this.parent&&n.dispose(a),t.map(e=>Bh(e,r,n))})}getFrozenTensorIds(e){const t=[].concat.apply([],Object.keys(e).map(t=>e[t]).map(e=>e.map(e=>e.id)));return new Set(t)}checkTensorForDisposal(e,t,n,r,a,s,o){if(!qf(t)&&!s.has(e)){for(const r of n[e])null!=r&&(o[r.id]=(o[r.id]||0)+t.children.length);for(const e of t.inputs){if(qf(e))continue;const t=Vh(e.name,n,r);if(null!=t)for(const e of t){if(!e||e.kept||a.has(e.id))continue;const t=o[e.id];1===t?(e.dispose(),delete o[e.id]):null!=t&&o[e.id]--}}}}checkTensorForDisposalWithNodeLiveUntilInfo(e,t,n,r,a,s){function o(e){return qf(e)||a.has(e.name)}if(!qf(e)&&null!=s)for(const i of s){if(o(i))continue;const e=Vh(i.name,t,n);for(const t of e)!t||t.kept||r.has(t.id)||t.dispose()}}async executeAsync(e,t){return this._executeAsync(e,t)}disposeIntermediateTensors(){this.clonedTensorsMap&&(Object.values(this.clonedTensorsMap).forEach(e=>{for(const t of e)t&&!t.isDisposed&&t.dispose()}),this.clonedTensorsMap=null)}getIntermediateTensors(){return this.clonedTensorsMap}async _executeAsync(e,t,n=!1,r={},a={}){this.disposeIntermediateTensors(),n||(e=this.mapInputs(e),this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t));try{this.keepIntermediateTensors=V().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(d){this.keepIntermediateTensors=!1,console.warn(d.message)}const s=new Vf(this.weightMap,r,a,this.functionExecutorMap,this.parseNodeNameCache);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap));const o=await this.executeWithControlFlow(e,s,t,n),i=t.map(e=>Bh(e,o,s)),u=i.map(e=>e.id),l=Object.keys(e).map(t=>e[t].id),c=/* @__PURE__ */new Set([...u,...l,...this.weightIds]);return Object.values(o).forEach(e=>{e.forEach(e=>{!e||e.isDisposed||c.has(e.id)||e.dispose()})}),null==this.parent&&s.dispose(c),i}async executeFunctionAsync(e,t,n){const r=e.reduce((e,t,n)=>(e[this.inputs[n].name]=t,e),{});return this._executeAsync(r,this.outputNodes,!0,t,n)}async executeWithControlFlow(e,t,n,r){const a=Object.keys(e),s=a.map(e=>this.graph.nodes[Uh(e)[0]]),o=n.map(e=>Uh(e)[0]),i=new Set(o);let u=o.map(e=>this.graph.nodes[e]);0===u.length&&(u=this._outputs);const{usedNodes:l,missingInputs:c,dynamicNode:d,syncInputs:p}=Wf(e,u,this.weightMap,this._initNodes),h=[...s,...this.graph.weights,...this._initNodes||[]].map(e=>({node:e,contexts:t.currentContext})),f=Object.assign({},this.weightMap);Object.keys(e).forEach(t=>{const[n,r]=Uh(t),a=[];a[r]=e[t],f[n]=a});const m={},g=this.getFrozenTensorIds(f),y={};for(;h.length>0;){const e=this.processStack(s,h,t,f,y,g,i,m,l);await Promise.all(e)}null!=d||r||console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");const b=u.filter(e=>!qf(e)&&!Bh(e.name,f,t)).map(e=>e.name);if(b.length>0){let e="";throw null!=d&&(e=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${p}]`),new Error(`Cannot compute the outputs [${b}] from the provided inputs [${a}]. Consider providing the following inputs: [${c}]. ${e}`)}return f}processStack(e,t,n,r,a,s,o,i,u){const l=[];for(;t.length>0;){const e=t.pop();n.currentContext=e.contexts;let c="";if("Enter"===e.node.op&&Lh("isConstant",e.node,r,n)&&([c]=Wh(e.node.name,n)),null==r[e.node.name]){const d=Bf(e.node,r,n,this._resourceManager);c||([c]=Wh(e.node.name,n));const p=n.currentContext;M(d)?l.push(d.then(l=>(r[c]=l,this.keepIntermediateTensors&&(this.clonedTensorsMap[c]=this.cloneTensorList(l)),n.currentContext=p,this.checkTensorForDisposal(c,e.node,r,n,s,o,i),this.processChildNodes(e.node,t,n,r,a,u),l))):(r[c]=d,this.keepIntermediateTensors&&(this.clonedTensorsMap[c]=this.cloneTensorList(d)),this.checkTensorForDisposal(c,e.node,r,n,s,o,i),this.processChildNodes(e.node,t,n,r,a,u))}else this.processChildNodes(e.node,t,n,r,a,u)}return l}processChildNodes(e,t,n,r,a,s){e.children.forEach(e=>{const[o]=Wh(e.name,n);!a[o]&&s.has(e.name)&&("Merge"===e.op?e.inputNames.some(e=>!!Bh(e,r,n))&&(a[o]=!0,t.push({contexts:n.currentContext,node:e})):e.inputNames.every(e=>!!Bh(e,r,n))&&(a[o]=!0,t.push({contexts:n.currentContext,node:e})))})}dispose(){Object.keys(this.weightMap).forEach(e=>this.weightMap[e].forEach(e=>e.dispose()))}checkInputShapeAndType(e){Object.keys(e).forEach(t=>{const n=e[t],[r]=Uh(t),a=this.graph.nodes[r];if(a.attrParams.shape&&a.attrParams.shape.value){const e=a.attrParams.shape.value;i(e.length===n.shape.length&&n.shape.every((t,n)=>-1===e[n]||e[n]===t),()=>`The shape of dict['${a.name}'] provided in model.execute(dict) must be [${e}], but was [${n.shape}]`)}a.attrParams.dtype&&a.attrParams.dtype.value&&i(n.dtype===a.attrParams.dtype.value,()=>`The dtype of dict['${a.name}'] provided in model.execute(dict) must be ${a.attrParams.dtype.value}, but was ${n.dtype}`)})}mapInputs(e){var t,n;const r={};for(const a in e){const s=null===(n=null===(t=this._signature)||void 0===t?void 0:t.inputs)||void 0===n?void 0:n[a];null!=s?r[s.name]=e[a]:r[a]=e[a]}return r}checkInputs(e){const t=Object.keys(e).filter(e=>{const[t]=Uh(e);return null==this.graph.nodes[t]});if(t.length>0)throw new Error(`The dict provided in model.execute(dict) has keys: [${t}] that are not part of graph`)}mapOutputs(e){return e.map(e=>{var t,n;const r=null===(n=null===(t=this._signature)||void 0===t?void 0:t.outputs)||void 0===n?void 0:n[e];return null!=r?r.name:e},{})}checkOutputs(e){e.forEach(e=>{const[t]=Uh(e);if(!this.graph.nodes[t])throw new Error(`The output '${e}' is not found in the graph`)})}}class Qf{constructor(e={},t={}){this.hashTableNameToHandle=e,this.hashTableMap=t}addHashTable(e,t){this.hashTableNameToHandle[e]=t.handle,this.hashTableMap[t.id]=t}getHashTableHandleByName(e){return this.hashTableNameToHandle[e]}getHashTableById(e){return this.hashTableMap[e]}dispose(){for(const e in this.hashTableMap)this.hashTableMap[e].clearAndClose(),delete this.hashTableMap[e];for(const e in this.hashTableNameToHandle)this.hashTableNameToHandle[e].dispose(),delete this.hashTableNameToHandle[e]}}const Zf="?tfjs-format=file",Jf="model.json";class em{get modelVersion(){return this.version}get inputNodes(){return this.executor.inputNodes}get outputNodes(){return this.executor.outputNodes}get inputs(){return this.executor.inputs}get outputs(){return this.executor.outputs}get weights(){return this.executor.weightMap}get metadata(){return this.artifacts.userDefinedMetadata}get modelSignature(){return this.signature}get modelStructuredOutputKeys(){return this.structuredOutputKeys}constructor(e,t={},n=mp){this.modelUrl=e,this.loadOptions=t,this.version="n/a",this.io=n,null==t&&(this.loadOptions={}),this.resourceManager=new Qf}findIOHandler(){const e=this.modelUrl;if(null!=e.load)this.handler=e;else if(null!=this.loadOptions.requestInit)this.handler=this.io.browserHTTPRequest(e,this.loadOptions);else{const t=this.io.getLoadHandlers(e,this.loadOptions);if(0===t.length)t.push(this.io.browserHTTPRequest(e,this.loadOptions));else if(t.length>1)throw new Error(`Found more than one (${t.length}) load handlers for URL '${[e]}'`);this.handler=t[0]}}load(){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.");const e=this.handler.load();return M(e)?e.then(e=>null==e.getWeightStream?this.loadSync(e):this.loadStreaming(e)):this.loadSync(e)}loadSync(e){const t=this.io.decodeWeights(e.weightData,e.weightSpecs);return this.loadWithWeightMap(e,t)}async loadStreaming(e){if(null==e.getWeightStream)throw new Error("Model artifacts missing streamWeights function");const t=await Qa(e.getWeightStream(),e.weightSpecs);return this.loadWithWeightMap(e,t)}loadWithWeightMap(e,t){this.artifacts=e;const n=this.artifacts.modelTopology;let r=this.artifacts.signature;if(null!=this.artifacts.userDefinedMetadata){const e=this.artifacts.userDefinedMetadata;null!=e.signature&&(r=e.signature),null!=e.structuredOutputKeys&&(this.structuredOutputKeys=e.structuredOutputKeys)}if(this.signature=r,this.version=`${n.versions.producer}.${n.versions.minConsumer}`,this.executor=new Yf(pf.Instance.transformGraph(n,this.signature)),this.executor.weightMap=this.convertTensorMapToTensorsMap(t),this.executor.resourceManager=this.resourceManager,null!=e.modelInitializer&&null!=e.modelInitializer.node){const t=pf.Instance.transformGraph(e.modelInitializer);this.initializer=new Yf(t),this.initializer.weightMap=this.executor.weightMap,this.initializer.resourceManager=this.resourceManager,this.initializerSignature=e.initializerSignature}return!0}async save(e,t){if("string"===typeof e){const t=this.io.getSaveHandlers(e);if(0===t.length)throw new Error(`Cannot find any save handlers for URL '${e}'`);if(t.length>1)throw new Error(`Found more than one (${t.length}) save handlers for URL '${e}'`);e=t[0]}if(null==e.save)throw new Error("GraphModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return e.save(this.artifacts)}addStructuredOutputNames(e){if(this.structuredOutputKeys){const t={};return(e instanceof Yr?[e]:e).forEach((e,n)=>t[this.structuredOutputKeys[n]]=e),t}return e}predict(e,t){const n=this.execute(e,this.outputNodes);return this.addStructuredOutputNames(n)}async predictAsync(e,t){const n=await this.executeAsync(e,this.outputNodes);return this.addStructuredOutputNames(n)}normalizeInputs(e){var t;if(!(e instanceof Yr)&&!Array.isArray(e)){const n=null===(t=this.signature)||void 0===t?void 0:t.inputs;if(null!=n)for(const t in n){const r=n[t];null!=r.resourceId&&(e[t]=this.resourceIdToCapturedInput[r.resourceId])}return e}e=Array.isArray(e)?e:[e];const n=Object.keys(this.resourceIdToCapturedInput).length;if(e.length+n!==this.inputNodes.length)throw new Error(`Input tensor count mismatch, the graph model has ${this.inputNodes.length-n} non-resource placeholders, while there are ${e.length} input tensors provided.`);let r=0;return this.inputNodes.reduce((t,n)=>{var a,s,o;const i=null===(o=null===(s=null===(a=this.signature)||void 0===a?void 0:a.inputs)||void 0===s?void 0:s[n])||void 0===o?void 0:o.resourceId;return t[n]=null!=i?this.resourceIdToCapturedInput[i]:e[r++],t},{})}normalizeOutputs(e){return e=e||this.outputNodes,Array.isArray(e)?e:[e]}executeInitializerGraph(){return null==this.initializer?[]:null==this.initializerSignature?this.initializer.execute({},[]):this.initializer.execute({},Object.keys(this.initializerSignature.outputs))}async executeInitializerGraphAsync(){return null==this.initializer?[]:null==this.initializerSignature?this.initializer.executeAsync({},[]):this.initializer.executeAsync({},Object.keys(this.initializerSignature.outputs))}setResourceIdToCapturedInput(e){if(this.resourceIdToCapturedInput={},this.initializerSignature){const t=this.initializerSignature.outputs,n=Object.keys(t);for(let r=0;r1?n:n[0]}async executeAsync(e,t){null==this.resourceIdToCapturedInput&&this.setResourceIdToCapturedInput(await this.executeInitializerGraphAsync()),e=this.normalizeInputs(e),t=this.normalizeOutputs(t);const n=await this.executor.executeAsync(e,t);return n.length>1?n:n[0]}getIntermediateTensors(){return this.executor.getIntermediateTensors()}disposeIntermediateTensors(){this.executor.disposeIntermediateTensors()}convertTensorMapToTensorsMap(e){return Object.keys(e).reduce((t,n)=>(t[n]=[e[n]],t),{})}dispose(){this.executor.dispose(),this.initializer&&(this.initializer.dispose(),this.resourceIdToCapturedInput&&Va(this.resourceIdToCapturedInput)),this.resourceManager.dispose()}}async function tm(e,t={},n=mp){if(null==e)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");null==t&&(t={}),t.fromTFHub&&"string"===typeof e&&(e=function(e){e.endsWith("/")||(e+="/");return`${e}${Jf}${Zf}`}(e));const r=new em(e,t,n);return await r.load(),r}var nm,rm={};function am(){return nm||(nm=1,function(){var e;function t(e){var t=0;return function(){return t>>0)+"_",a=0;return function e(n){if(this instanceof e)throw new TypeError("Symbol is not a constructor");return new t(r+(n||"")+"_"+a++,n)}}),a("Symbol.iterator",function(e){if(e)return e;e=/* @__PURE__ */Symbol("Symbol.iterator");for(var a="Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".split(" "),o=0;ot&&(t=Math.max(0,r+t)),(null==n||n>r)&&(n=r),0>(n=Number(n))&&(n=Math.max(0,r+n)),t=Number(t||0);t(t=t||0)&&(t=Math.max(t+r,0));t>4),64!=o&&(t(s<<4&240|o>>2),64!=i&&t(o<<6&192|i))}}(e,function(e){r[a++]=e}),a!==n?r.subarray(0,a):r}function A(){if(!R){R={};for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),t=["+/=","+/","-_=","-_.","-_"],n=0;5>n;n++){var r=e.concat(t[n].split(""));E[n]=r;for(var a=0;a>2];o=t[(3&o)<<4|i>>4],i=t[(15&i)<<2|u>>6],u=t[63&u],n[s++]=l+o+i+u}switch(l=0,u=r,e.length-a){case 2:u=t[(15&(l=e[a+1]))<<2]||r;case 1:e=e[a],n[s]=t[e>>2]+t[(3&e)<<4|l>>4]+u+r}return n.join("")}for(t="";10240e,n=(e=Math.abs(e))>>>0;e=Math.floor((e-n)/4294967296),t&&(t=(n=o(K(n,e))).next().value,e=n.next().value,n=t),U=n>>>0,G=e>>>0}var j,q="function"===typeof BigInt;function K(e,t){return t=~t,e?e=1+~e:t+=1,[e,t]}function X(e,t){this.i=e>>>0,this.h=t>>>0}function Y(e){if(!e)return j||(j=new X(0,0));if(!/^-?\d+$/.test(e))return null;if(16>e.length)H(Number(e));else if(q)e=BigInt(e),U=Number(e&BigInt(4294967295))>>>0,G=Number(e>>BigInt(32)&BigInt(4294967295));else{var t=+("-"===e[0]);G=U=0;for(var n=e.length,r=t,a=(n-t)%6+t;a<=n;r=a,a+=6)r=Number(e.slice(r,a)),G*=1e6,4294967296<=(U=1e6*U+r)&&(G+=U/4294967296|0,U%=4294967296);t&&(e=(t=o(K(U,G))).next().value,t=t.next().value,U=e,G=t)}return new X(U,G)}function Q(e,t){return Error("Invalid wire type: "+e+" (at position "+t+")")}function Z(){return Error("Failed to read varint, encoding is invalid.")}function J(e,t){return Error("Tried to read past the end of the data "+t+" > "+e)}function ee(){throw Error("Invalid UTF8")}function te(e,t){return t=String.fromCharCode.apply(null,t),null==e?t:e+t}var ne,re,ae,se=void 0,oe="undefined"!==typeof TextDecoder,ie="undefined"!==typeof TextEncoder;function ue(e){if(e!==W)throw Error("illegal external caller")}function le(e,t){if(ue(t),this.V=e,null!=e&&0===e.length)throw Error("ByteString should be constructed with non-empty values")}function ce(){return ae||(ae=new le(null,W))}function de(e){ue(W);var t=e.V;return null==(t=null==t||O&&null!=t&&t instanceof Uint8Array?t:"string"===typeof t?B(t):null)?t:e.V=t}function pe(e,t){this.i=null,this.m=!1,this.h=this.j=this.l=0,he(this,e,t)}function he(e,t,n){n=void 0===n?{}:n,e.S=void 0!==n.S&&n.S,t&&(t=function(e){if("string"===typeof e)return{buffer:B(e),C:!1};if(Array.isArray(e))return{buffer:new Uint8Array(e),C:!1};if(e.constructor===Uint8Array)return{buffer:e,C:!1};if(e.constructor===ArrayBuffer)return{buffer:new Uint8Array(e),C:!1};if(e.constructor===le)return{buffer:de(e)||V(),C:!0};if(e instanceof Uint8Array)return{buffer:new Uint8Array(e.buffer,e.byteOffset,e.byteLength),C:!1};throw Error("Type not convertible to a Uint8Array, expected a Uint8Array, an ArrayBuffer, a base64 encoded string, a ByteString or an Array of numbers")}(t),e.i=t.buffer,e.m=t.C,e.l=0,e.j=e.i.length,e.h=e.l)}function fe(e,t){if(e.h=t,t>e.j)throw J(e.j,t)}function me(e){var t=e.i,n=e.h,r=t[n++],a=127&r;if(128&r&&(a|=(127&(r=t[n++]))<<7,128&r&&(a|=(127&(r=t[n++]))<<14,128&r&&(a|=(127&(r=t[n++]))<<21,128&r&&(a|=(r=t[n++])<<28,128&r&&128&t[n++]&&128&t[n++]&&128&t[n++]&&128&t[n++]&&128&t[n++])))))throw Z();return fe(e,n),a}function ge(e,t){if(0>t)throw Error("Tried to read a negative byte length: "+t);var n=e.h,r=n+t;if(r>e.j)throw J(t,e.j-n);return e.h=r,n}pe.prototype.reset=function(){this.h=this.l};var ye=[];function be(){this.h=[]}function xe(e,t,n){for(;0>>7|n<<25)>>>0,n>>>=7;e.h.push(t)}function ve(e,t){for(;127>>=7;e.h.push(t)}function we(e,t){if(ye.length){var n=ye.pop();he(n,e,t),e=n}else e=new pe(e,t);this.h=e,this.j=this.h.h,this.i=this.l=-1,this.setOptions(t)}function ke(e){var t=e.h;if(t.h==t.j)return!1;e.j=e.h.h;var n=me(e.h)>>>0;if(t=n>>>3,!(0<=(n&=7)&&5>=n))throw Q(n,e.j);if(1>t)throw Error("Invalid field number: "+t+" (at position "+e.j+")");return e.l=t,e.i=n,!0}function Ie(e){switch(e.i){case 0:if(0!=e.i)Ie(e);else e:{for(var t=(e=e.h).h,n=t+10,r=e.i;t>>0,fe(e=e.h,e.h+t));break;case 5:fe(e=e.h,e.h+4);break;case 3:for(t=e.l;;){if(!ke(e))throw Error("Unmatched start-group tag: stream EOF");if(4==e.i){if(e.l!=t)throw Error("Unmatched end-group tag");break}Ie(e)}break;default:throw Q(e.i,e.j)}}be.prototype.length=function(){return this.h.length},be.prototype.end=function(){var e=this.h;return this.h=[],e},we.prototype.setOptions=function(e){e=void 0===e?{}:e,this.ca=void 0!==e.ca&&e.ca},we.prototype.reset=function(){this.h.reset(),this.j=this.h.h,this.i=this.l=-1};var Ne=[];function Se(){this.j=[],this.i=0,this.h=new be}function Te(e,t){0!==t.length&&(e.j.push(t),e.i+=t.length)}var Ce="function"===typeof Symbol&&"symbol"===typeof/* @__PURE__ */Symbol()?/* @__PURE__ */Symbol():void 0;function $e(e,t){return Ce?e[Ce]|=t:void 0!==e.A?e.A|=t:(Object.defineProperties(e,{A:{value:t,configurable:!0,writable:!0,enumerable:!1}}),t)}function Ee(e,t){Ce?e[Ce]&&(e[Ce]&=~t):void 0!==e.A&&(e.A&=~t)}function Re(e){return(Ce?e[Ce]:e.A)??0}function _e(e,t){Ce?e[Ce]=t:void 0!==e.A?e.A=t:Object.defineProperties(e,{A:{value:t,configurable:!0,writable:!0,enumerable:!1}})}function Ae(e){return $e(e,1),e}function Oe(e,t){_e(t,-51&e)}function Fe(e,t){_e(t,-41&e|18)}var De={};function Me(e){return null!==e&&"object"===typeof e&&!Array.isArray(e)&&e.constructor===Object}var Pe,Le,Be=[];function Ve(e){if(2&Re(e.o))throw Error("Cannot mutate an immutable Message")}function We(e){var t=e.length;(t=t?e[t-1]:void 0)&&Me(t)?t.g=1:(t={},e.push((t.g=1,t)))}function ze(e){var t=e.i+e.G;return e.B||(e.B=e.o[t]={})}function Ue(e,t){return-1===t?null:t>=e.i?e.B?e.B[t]:void 0:e.o[t+e.G]}function Ge(e,t,n,r){Ve(e),He(e,t,n,r)}function He(e,t,n,r){e.j&&(e.j=void 0),t>=e.i||r?ze(e)[t]=n:(e.o[t+e.G]=n,(e=e.B)&&t in e&&delete e[t])}function je(e,t,n,r){var a=Ue(e,t);Array.isArray(a)||(a=Pe);var s=Re(a);if(1&s||Ae(a),r)2&s||$e(a,2),1&n||Object.freeze(a);else{r=!(2&n);var o=2&s;1&n||!o?r&&16&s&&!o&&Ee(a,16):He(e,t,a=Ae(Array.prototype.slice.call(a)))}return a}function qe(e,t){var n=Ue(e,t),r=null==n?n:"number"===typeof n||"NaN"===n||"Infinity"===n||"-Infinity"===n?Number(n):void 0;return null!=r&&r!==n&&He(e,t,r),r}function Ke(e,t,n,r,a){e.h||(e.h={});var s=e.h[n],o=je(e,n,3,a);if(!s){var i=o;s=[];var u=!!(16&Re(e.o));o=!!(2&Re(i));var l=i;!a&&o&&(i=Array.prototype.slice.call(i));for(var c=o,d=0;do&&"number"!==typeof e[o]){var i=e[o++];n(t,i)}for(;o>>0)>>31)+1,s=o>>>23&255,o&=8388607,Ge(t,n,255==s?o?NaN:1/0*e:0==s?e*Math.pow(2,-149)*o:e*Math.pow(2,s-150)*(o+Math.pow(2,23))),!0},function(e,t,n){if(null!=(t=qe(t,n))){ve(e.h,8*n+5),e=e.h;var r=+t;0===r?0<1/r?U=G=0:(G=0,U=2147483648):isNaN(r)?(G=0,U=2147483647):34028234663852886e22<(r=(n=0>r?-2147483648:0)?-r:r)?(G=0,U=(2139095040|n)>>>0):11754943508222875e-54>r?(r=Math.round(r/Math.pow(2,-149)),G=0,U=(n|r)>>>0):(t=Math.floor(Math.log(r)/Math.LN2),r*=Math.pow(2,-t),16777216<=(r=Math.round(8388608*r))&&++t,G=0,U=(n|t+127<<23|8388607&r)>>>0),n=U,e.h.push(n>>>0&255),e.h.push(n>>>8&255),e.h.push(n>>>16&255),e.h.push(n>>>24&255)}}),Mt=Ft(function(e,t,n){if(0!==e.i)return!1;var r=e.h,a=0,s=e=0,o=r.i,i=r.h;do{var u=o[i++];a|=(127&u)<s&&128&u);for(32>4),s=3;32>s&&128&u;s+=7)e|=(127&(u=o[i++]))<u))throw Z();return r=a>>>0,(e=2147483648&(u=e>>>0))&&(u=~u>>>0,0==(r=1+~r>>>0)&&(u=u+1>>>0)),r=4294967296*u+(r>>>0),Ge(t,n,e?-r:r),!0},function(e,t,n){null!=(t=Ue(t,n))&&("string"===typeof t&&Y(t),null!=t&&(ve(e.h,8*n),"number"===typeof t?(e=e.h,H(t),xe(e,U,G)):(n=Y(t),xe(e.h,n.i,n.h))))}),Pt=Ft(function(e,t,n){return 0===e.i&&(Ge(t,n,me(e.h)),!0)},function(e,t,n){if(null!=(t=Ue(t,n))&&null!=t)if(ve(e.h,8*n),e=e.h,0<=(n=t))ve(e,n);else{for(t=0;9>t;t++)e.h.push(127&n|128),n>>=7;e.h.push(1)}}),Lt=Ft(function(e,t,n){if(2!==e.i)return!1;var r=me(e.h)>>>0,a=ge(e=e.h,r);if(e=e.i,oe){var s,o=e;(s=ne)||(s=ne=new TextDecoder("utf-8",{fatal:!0})),e=a+r,o=0===a&&e===o.length?o:o.subarray(a,e);try{var i=s.decode(o)}catch(d){if(void 0===se){try{s.decode(new Uint8Array([128]))}catch(p){}try{s.decode(new Uint8Array([97])),se=!0}catch(p){se=!1}}throw!se&&(ne=void 0),d}}else{r=(i=a)+r,a=[];for(var u,l,c=null;i(u=e[i++])?a.push(u):224>u?i>=r?ee():(l=e[i++],194>u||128!==(192&l)?(i--,ee()):a.push((31&u)<<6|63&l)):240>u?i>=r-1?ee():128!==(192&(l=e[i++]))||224===u&&160>l||237===u&&160<=l||128!==(192&(o=e[i++]))?(i--,ee()):a.push((15&u)<<12|(63&l)<<6|63&o):244>=u?i>=r-2?ee():128!==(192&(l=e[i++]))||0!==l-144+(u<<28)>>30||128!==(192&(o=e[i++]))||128!==(192&(s=e[i++]))?(i--,ee()):(u=(7&u)<<18|(63&l)<<12|(63&o)<<6|63&s,u-=65536,a.push(55296+(u>>10&1023),56320+(1023&u))):ee(),8192<=a.length&&(c=te(c,a),a.length=0);i=te(c,a)}return Ge(t,n,i),!0},function(e,t,n){if(null!=(t=Ue(t,n))){var r=!1;if(r=void 0!==r&&r,ie){if(r&&/(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])/.test(t))throw Error("Found an unpaired surrogate");t=(re||(re=new TextEncoder)).encode(t)}else{for(var a=0,s=new Uint8Array(3*t.length),o=0;oi)s[a++]=i;else{if(2048>i)s[a++]=i>>6|192;else{if(55296<=i&&57343>=i){if(56319>=i&&o=u){i=1024*(i-55296)+u-56320+65536,s[a++]=i>>18|240,s[a++]=i>>12&63|128,s[a++]=i>>6&63|128,s[a++]=63&i|128;continue}o--}if(r)throw Error("Found an unpaired surrogate");i=65533}s[a++]=i>>12|224,s[a++]=i>>6&63|128}s[a++]=63&i|128}}t=a===s.length?s:s.subarray(0,a)}ve(e.h,8*n+2),ve(e.h,t.length),Te(e,e.h.end()),Te(e,t)}}),Bt=Ft(function(e,t,n,r,a){if(2!==e.i)return!1;t=Qe(t,n,r),n=e.h.j,r=me(e.h)>>>0;var s=e.h.h+r,o=s-n;if(0>=o&&(e.h.j=s,a(t,e,void 0,void 0,void 0),o=s-e.h.h),o)throw Error("Message parsing ended unexpectedly. Expected to read "+r+" bytes, instead read "+(r-o)+" bytes, either the data ended unexpectedly or the message misreported its own length");return e.h.h=s,e.h.j=n,!0},function(e,t,n,r,a){if(null!=(t=Xe(t,r,n)))for(r=0;r>>=7,o.i++;s.push(i),o.i++}});function Vt(e){return function(t,n){e:{if(Ne.length){var r=Ne.pop();r.setOptions(n),he(r.h,t,n),t=r}else t=new we(t,n);try{var a=_t(e),s=At(new a.P,t,a);break e}finally{(a=t.h).i=null,a.m=!1,a.l=0,a.j=0,a.h=0,a.S=!1,t.l=-1,t.i=-1,100>Ne.length&&Ne.push(t)}s=void 0}return s}}function Wt(e){return function(){var t=new Se;Ot(this,t,St(e)),Te(t,t.h.end());for(var n=new Uint8Array(t.i),r=t.j,a=r.length,s=0,o=0;o0&&a[a.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!a||s[1]>a[0]&&s[1]=256)throw new Error("Mask value must be in range [0, 255] but got "+e);if(!Number.isInteger(e))throw new Error("Mask value must be an integer but got "+e)}function gm(e){var t=e.shape[2],n=Qs(e,2),r=vo(n,[-1]);return Ou(r,t)}function ym(e,t){return Ba(function(){return Ls(Gi(e,Ri(t)),"int32")})}function bm(e,t){var n=t.shape,r=n[0],a=n[1],s=n[2];return Ba(function(){var n=gm(t),o=Li(Nl(0,s,1,"int32"),1),i=Ls(No(n,o),"int32"),u=vo(i,[r,a]),l=Ws(u,Ri(1,"int32"));return uu(Gs(l,e),Ri(1,"int32"))})}var xm=function(){function e(e,t){this.model=e,this.outputStride=t;var n=this.model.inputs[0].shape;i(-1===n[1]&&-1===n[2],function(){return"Input shape ["+n[1]+", "+n[2]+"] must both be equal to or -1"})}return e.prototype.predict=function(e){var t=this;return Ba(function(){var n=t.preprocessInput(Ls(e,"float32")),r=Li(n,0),a=t.model.predict(r).map(function(e){return Jl(e,[0])}),s=t.nameOutputResults(a);return{heatmapScores:So(s.heatmap),offsets:s.offsets,displacementFwd:s.displacementFwd,displacementBwd:s.displacementBwd,segmentation:s.segmentation,partHeatmaps:s.partHeatmaps,longOffsets:s.longOffsets,partOffsets:s.partOffsets}})},e.prototype.dispose=function(){this.model.dispose()},e}(),vm=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return im(t,e),t.prototype.preprocessInput=function(e){return Ba(function(){return uu(Us(e,127.5),1)})},t.prototype.nameOutputResults=function(e){return{offsets:e[0],segmentation:e[1],partHeatmaps:e[2],longOffsets:e[3],heatmap:e[4],displacementFwd:e[5],displacementBwd:e[6],partOffsets:e[7]}},t}(xm),wm=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"],km=wm.length,Im=wm.reduce(function(e,t,n){return e[t]=n,e},{});function Nm(e,t,n){var r=e[0],a=e[1],s=t[0],o=t[1],i=n.top,u=n.bottom;return[o/(n.left+n.right+a),s/(i+u+r)]}function Sm(e,t,n,r){return{y:r.get(e,t,n),x:r.get(e,t,n+km)}}function Tm(e,t,n){var r=Sm(e.heatmapY,e.heatmapX,e.id,n),a=r.y,s=r.x;return{x:e.heatmapX*t+s,y:e.heatmapY*t+a}}function Cm(e,t,n){return en?n:e}function $m(e,t){return{x:e.x+t.x,y:e.y+t.y}}function Em(e,t,n){void 0===n&&(n=.3);for(var r=0,a=0,s=0;sn&&(a+=1,r+=Math.pow(e[s].x-t.keypoints[s].position.x,2)+Math.pow(e[s].y-t.keypoints[s].position.y,2));return 0===a?r=1/0:r/=a,r}function Rm(e,t,n,r,a,s,o){for(var i=o[0],u=o[1],l=n(e),c=l.y*r+l.x,d=a[km*(2*c)+t],p=a[km*(2*c+1)+t],h=e.y+d,f=e.x+p,m=0;m "+l+") {\n numKpt = numKpt + 1;\n curDistSum = curDistSum + dist(x, y, poseX, poseY);\n }\n }\n if (numKpt > 0 && curDistSum / float(numKpt) < minDist) {\n minDist = curDistSum / float(numKpt);\n iMin = i;\n }\n }\n return iMin;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int nearestPose = findNearestPose(coords[0], coords[1]);\n setOutput(float(nearestPose));\n }\n "};return Ha().compileAndRun(O,[e,x,R])}function Fm(){return"webgl"===Ua()}function Dm(e,t,n,r,a,s,o,i,u,l,c,d){var p=o[0],h=o[1];return void 0===u&&(u=.2),void 0===l&&(l=8),void 0===c&&(c=.3),void 0===d&&(d=10),lm(this,0,void 0,function(){var o,f,m,g,y;return cm(this,function(b){switch(b.label){case 0:return o=n.filter(function(e){return e.score>=u}),Fm()?(m=Ba(function(){var n=Om(e,t,o,r,a,s,[p,h],i,l,c,d),u=La().makeTensorFromDataId(n.dataId,n.shape,n.dtype);return o.map(function(e,t){return n=u,r=t,Ba(function(){return Ls(ci(n,Ri(r)),"int32")});var n,r})}),[4,Promise.all(m.map(function(e){return e.data()}))]):[3,2];case 1:return f=b.sent(),m.forEach(function(e){return e.dispose()}),[3,5];case 2:return[4,e.data()];case 3:return g=b.sent(),[4,t.data()];case 4:y=b.sent(),f=function(e,t,n,r,a,s,o,i,u,l){var c=o[0],d=o[1];void 0===l&&(l=5);for(var p=n.map(function(e){return new Uint8Array(r*a).fill(0)}),h=i.top,f=i.left,m=Nm([r,a],[c,d],i),g=m[0],y=m[1],b=Am([c,d],s)[0],x=0;x=0&&(p[k][w]=1)}}return p}(g,y,o,r,a,s,[p,h],i,l),b.label=5;case 5:return[2,f.map(function(e,t){return{data:e,pose:o[t],width:a,height:r}})]}})})}function Mm(e,t,n,r,a,s,o,i,u,l,c,d,p){var h=i[0],f=i[1];return void 0===l&&(l=.2),void 0===c&&(c=8),void 0===d&&(d=.3),void 0===p&&(p=10),lm(this,0,void 0,function(){var i,m,g,y,b,x;return cm(this,function(v){switch(v.label){case 0:return i=r.filter(function(e){return e.score>=l}),Fm()?(g=Ba(function(){var r=Om(e,t,i,a,s,o,[h,f],u,c,d,p),l=La().makeTensorFromDataId(r.dataId,r.shape,r.dtype);return i.map(function(e,t){return r=l,a=n,s=t,Ba(function(){return uu(Gs(Ls(ci(r,Ri(s)),"int32"),Ws(a,1)),1)});var r,a,s})}),[4,Promise.all(g.map(function(e){return e.data()}))]):[3,2];case 1:return m=v.sent(),g.forEach(function(e){return e.dispose()}),[3,6];case 2:return[4,e.data()];case 3:return y=v.sent(),[4,t.data()];case 4:return b=v.sent(),[4,n.data()];case 5:x=v.sent(),m=function(e,t,n,r,a,s,o,i,u,l,c){var d=i[0],p=i[1];void 0===c&&(c=5);for(var h=r.map(function(e){return new Int32Array(a*s).fill(-1)}),f=u.top,m=u.left,g=Nm([a,s],[d,p],u),y=g[0],b=g[1],x=Am([d,p],o)[0],v=0;v=0&&(h[I][k]=n[k])}}return h}(y,b,x,i,a,s,o,[h,f],u,c),v.label=6;case 6:return[2,m.map(function(e,t){return{pose:i[t],data:e,height:a,width:s}})]}})})}function Pm(e){return Math.floor(e/2)}[["leftHip","leftShoulder"],["leftElbow","leftShoulder"],["leftElbow","leftWrist"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["rightHip","rightShoulder"],["rightElbow","rightShoulder"],["rightElbow","rightWrist"],["rightHip","rightKnee"],["rightKnee","rightAnkle"],["leftShoulder","rightShoulder"],["leftHip","rightHip"]].map(function(e){var t=e[0],n=e[1];return[Im[t],Im[n]]});var Lm=function(){function e(e,t){this.priorityQueue=new Array(e),this.numberOfElements=-1,this.getElementValue=t}return e.prototype.enqueue=function(e){this.priorityQueue[++this.numberOfElements]=e,this.swim(this.numberOfElements)},e.prototype.dequeue=function(){var e=this.priorityQueue[0];return this.exchange(0,this.numberOfElements--),this.sink(0),this.priorityQueue[this.numberOfElements+1]=null,e},e.prototype.empty=function(){return-1===this.numberOfElements},e.prototype.size=function(){return this.numberOfElements+1},e.prototype.all=function(){return this.priorityQueue.slice(0,this.numberOfElements+1)},e.prototype.max=function(){return this.priorityQueue[0]},e.prototype.swim=function(e){for(;e>0&&this.less(Pm(e),e);)this.exchange(e,Pm(e)),e=Pm(e)},e.prototype.sink=function(e){for(;2*e<=this.numberOfElements;){var t=2*e;if(tt){l=!1;break}if(!l)break}return l}var Vm=[["nose","leftEye"],["leftEye","leftEar"],["nose","rightEye"],["rightEye","rightEar"],["nose","leftShoulder"],["leftShoulder","leftElbow"],["leftElbow","leftWrist"],["leftShoulder","leftHip"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["nose","rightShoulder"],["rightShoulder","rightElbow"],["rightElbow","rightWrist"],["rightShoulder","rightHip"],["rightHip","rightKnee"],["rightKnee","rightAnkle"]].map(function(e){var t=e[0],n=e[1];return[Im[t],Im[n]]}),Wm=Vm.map(function(e){return e[1]}),zm=Vm.map(function(e){return e[0]});function Um(e,t,n,r){return{y:Cm(Math.round(e.y/t),0,n-1),x:Cm(Math.round(e.x/t),0,r-1)}}function Gm(e,t,n,r,a,s,o,i){void 0===i&&(i=2);for(var u=r.shape,l=u[0],c=u[1],d=function(e,t,n){var r=n.shape[2]/2;return{y:n.get(t.y,t.x,e),x:n.get(t.y,t.x,r+e)}}(e,Um(t.position,s,l,c),o),p=$m(t.position,d),h=0;h=0;--p){var h=Wm[p],f=zm[p];u[h]&&!u[f]&&(u[f]=Gm(p,u[h],f,t,n,r,s))}for(p=0;p=.1,function(){return"inputResolution must be a string or number between 0.1 and 2, but was "+e}),e}(e);return[tg(r*s,t),tg(a*s,t)]}function sg(e,t,n,r,a){var s=t[0],o=t[1],i=n[0],u=n[1],l=r[0],c=l[0],d=l[1],p=r[1],h=p[0],f=p[1];return Ba(function(){var t=Md.resizeBilinear(e,[i,u],!0);return function(e,t,n){var r=t[0],a=t[1],s=n[0],o=s[0],i=s[1],u=n[1],l=u[0],c=u[1];return Ba(function(){var t=Li(e);return Jl(Md.cropAndResize(t,[[o/(r+o+i-1),l/(a+l+c-1),(o+r-1)/(r+o+i-1),(l+a-1)/(a+l+c-1)]],[0],[r,a]),[0])})}(t=So(t),[s,o],[[c,d],[h,f]])})}function og(e,t){var n=t[0],r=t[1],a=eg(e),s=a[0],o=a[1],i=r/n,u=[0,0,0,0],l=u[0],c=u[1],d=u[2],p=u[3];return o/s1)throw new Error("segmentationThreshold "+t+". Should be in range [0.0, 1.0]");if(n<=0)throw new Error("Invalid maxDetections "+n+". Should be > 0");if(r<0||r>1)throw new Error("Invalid scoreThreshold "+r+". Should be in range [0.0, 1.0]");if(a<=0)throw new Error("Invalid nmsRadius "+a+".")}function yg(e){var t=e.segmentationThreshold,n=e.maxDetections,r=e.scoreThreshold,a=e.nmsRadius,s=e.minKeypointScore,o=e.refineSteps;if(t<0||t>1)throw new Error("segmentationThreshold "+t+". Should be in range [0.0, 1.0]");if(n<=0)throw new Error("Invalid maxDetections "+n+". Should be > 0");if(r<0||r>1)throw new Error("Invalid scoreThreshold "+r+". Should be in range [0.0, 1.0]");if(a<=0)throw new Error("Invalid nmsRadius "+a+".");if(s<0||s>1)throw new Error("Invalid minKeypointScore "+s+".Should be in range [0.0, 1.0]");if(o<=0||o>20)throw new Error("Invalid refineSteps "+o+".Should be in range [1, 20]")}var bg=function(){function e(e){this.baseModel=e}return e.prototype.predictForPersonSegmentation=function(e){var t=this.baseModel.predict(e);return{segmentLogits:t.segmentation,heatmapScores:t.heatmapScores,offsets:t.offsets,displacementFwd:t.displacementFwd,displacementBwd:t.displacementBwd}},e.prototype.predictForPersonSegmentationAndPart=function(e){var t=this.baseModel.predict(e);return{segmentLogits:t.segmentation,partHeatmapLogits:t.partHeatmaps,heatmapScores:t.heatmapScores,offsets:t.offsets,displacementFwd:t.displacementFwd,displacementBwd:t.displacementBwd}},e.prototype.predictForMultiPersonInstanceSegmentationAndPart=function(e){var t=this.baseModel.predict(e);return{segmentLogits:t.segmentation,longOffsets:t.longOffsets,heatmapScores:t.heatmapScores,offsets:t.offsets,displacementFwd:t.displacementFwd,displacementBwd:t.displacementBwd,partHeatmaps:t.partHeatmaps}},e.prototype.segmentPersonActivation=function(e,t,n){var r=this;void 0===n&&(n=.5);var a=eg(e),s=a[0],o=a[1],i=ag(t,this.baseModel.outputStride,[s,o]),u=og(e,i),l=u.resized,c=u.padding,d=Ba(function(){var e=r.predictForPersonSegmentation(l),t=e.segmentLogits,a=e.heatmapScores,i=e.offsets,u=e.displacementFwd,d=e.displacementBwd,p=l.shape,h=p[0],f=p[1],m=sg(t,[s,o],[h,f],[[c.top,c.bottom],[c.left,c.right]]);return{segmentation:ym(Jl(m),n),heatmapScores:a,offsets:i,displacementFwd:u,displacementBwd:d}}),p=d.segmentation,h=d.heatmapScores,f=d.offsets,m=d.displacementFwd,g=d.displacementBwd;return l.dispose(),{segmentation:p,heatmapScores:h,offsets:f,displacementFwd:m,displacementBwd:g,padding:c,internalResolutionHeightAndWidth:i}},e.prototype.segmentPerson=function(e,t){return void 0===t&&(t=fg),lm(this,0,void 0,function(){var n,r,a,s,o,i,u,l,c,d,p,h,f,m,g,y,b,x;return cm(this,function(v){switch(v.label){case 0:return gg(t=um(um({},fg),t)),n=this.segmentPersonActivation(e,t.internalResolution,t.segmentationThreshold),r=n.segmentation,a=n.heatmapScores,s=n.offsets,o=n.displacementFwd,i=n.displacementBwd,u=n.padding,l=n.internalResolutionHeightAndWidth,c=r.shape,d=c[0],p=c[1],[4,r.data()];case 1:return h=v.sent(),r.dispose(),[4,ig([a,s,o,i])];case 2:return f=v.sent(),m=f[0],g=f[1],y=f[2],b=f[3],x=ug(x=Km(m,g,y,b,this.baseModel.outputStride,t.maxDetections,t.scoreThreshold,t.nmsRadius),[d,p],l,u,!1),a.dispose(),s.dispose(),o.dispose(),i.dispose(),[2,{height:d,width:p,data:h,allPoses:x}]}})})},e.prototype.segmentMultiPerson=function(e,t){return void 0===t&&(t=mg),lm(this,0,void 0,function(){var n,r,a,s,o,i,u,l,c,d,p,h,f,m,g,y,b,x,v,w,k,I=this;return cm(this,function(N){switch(N.label){case 0:return yg(t=um(um({},mg),t)),n=eg(e),r=n[0],a=n[1],s=ag(t.internalResolution,this.baseModel.outputStride,[r,a]),o=og(e,s),i=o.resized,u=o.padding,l=Ba(function(){var e,n=I.predictForMultiPersonInstanceSegmentationAndPart(i),o=n.segmentLogits,l=n.longOffsets,c=n.heatmapScores,d=n.offsets,p=n.displacementFwd,h=n.displacementBwd,f=sg(o,[r,a],s,[[u.top,u.bottom],[u.left,u.right]]);return e=l,{segmentation:ym(Jl(f),t.segmentationThreshold),longOffsets:e,heatmapScoresRaw:c,offsetsRaw:d,displacementFwdRaw:p,displacementBwdRaw:h}}),c=l.segmentation,d=l.longOffsets,p=l.heatmapScoresRaw,h=l.offsetsRaw,f=l.displacementFwdRaw,m=l.displacementBwdRaw,[4,ig([p,h,f,m])];case 1:return g=N.sent(),y=g[0],b=g[1],x=g[2],v=g[3],w=ug(w=Km(y,b,x,v,this.baseModel.outputStride,t.maxDetections,t.scoreThreshold,t.nmsRadius),[r,a],s,u,!1),[4,Dm(c,d,w,r,a,this.baseModel.outputStride,s,u,t.scoreThreshold,t.refineSteps,t.minKeypointScore,t.maxDetections)];case 2:return k=N.sent(),i.dispose(),c.dispose(),d.dispose(),p.dispose(),h.dispose(),f.dispose(),m.dispose(),[2,k]}})})},e.prototype.segmentPersonPartsActivation=function(e,t,n){var r=this;void 0===n&&(n=.5);var a=eg(e),s=a[0],o=a[1],i=ag(t,this.baseModel.outputStride,[s,o]),u=og(e,i),l=u.resized,c=u.padding,d=Ba(function(){var e=r.predictForPersonSegmentationAndPart(l),t=e.segmentLogits,a=e.partHeatmapLogits,i=e.heatmapScores,u=e.offsets,d=e.displacementFwd,p=e.displacementBwd,h=l.shape,f=h[0],m=h[1],g=sg(t,[s,o],[f,m],[[c.top,c.bottom],[c.left,c.right]]),y=sg(a,[s,o],[f,m],[[c.top,c.bottom],[c.left,c.right]]);return{partSegmentation:bm(ym(Jl(g),n),y),heatmapScores:i,offsets:u,displacementFwd:d,displacementBwd:p}}),p=d.partSegmentation,h=d.heatmapScores,f=d.offsets,m=d.displacementFwd,g=d.displacementBwd;return l.dispose(),{partSegmentation:p,heatmapScores:h,offsets:f,displacementFwd:m,displacementBwd:g,padding:c,internalResolutionHeightAndWidth:i}},e.prototype.segmentPersonParts=function(e,t){return void 0===t&&(t=fg),lm(this,0,void 0,function(){var n,r,a,s,o,i,u,l,c,d,p,h,f,m,g,y,b,x;return cm(this,function(v){switch(v.label){case 0:return gg(t=um(um({},fg),t)),n=this.segmentPersonPartsActivation(e,t.internalResolution,t.segmentationThreshold),r=n.partSegmentation,a=n.heatmapScores,s=n.offsets,o=n.displacementFwd,i=n.displacementBwd,u=n.padding,l=n.internalResolutionHeightAndWidth,c=r.shape,d=c[0],p=c[1],[4,r.data()];case 1:return h=v.sent(),r.dispose(),[4,ig([a,s,o,i])];case 2:return f=v.sent(),m=f[0],g=f[1],y=f[2],b=f[3],x=ug(x=Km(m,g,y,b,this.baseModel.outputStride,t.maxDetections,t.scoreThreshold,t.nmsRadius),[d,p],l,u,!1),a.dispose(),s.dispose(),o.dispose(),i.dispose(),[2,{height:d,width:p,data:h,allPoses:x}]}})})},e.prototype.segmentMultiPersonParts=function(e,t){return void 0===t&&(t=mg),lm(this,0,void 0,function(){var n,r,a,s,o,i,u,l,c,d,p,h,f,m,g,y,b,x,v,w,k,I,N=this;return cm(this,function(S){switch(S.label){case 0:return yg(t=um(um({},mg),t)),n=eg(e),r=n[0],a=n[1],s=ag(t.internalResolution,this.baseModel.outputStride,[r,a]),o=og(e,s),i=o.resized,u=o.padding,l=Ba(function(){var e=N.predictForMultiPersonInstanceSegmentationAndPart(i),n=e.segmentLogits,o=e.longOffsets,l=e.heatmapScores,c=e.offsets,d=e.displacementFwd,p=e.displacementBwd,h=e.partHeatmaps,f=sg(n,[r,a],s,[[u.top,u.bottom],[u.left,u.right]]),m=sg(h,[r,a],s,[[u.top,u.bottom],[u.left,u.right]]),g=o;return{segmentation:ym(Jl(f),t.segmentationThreshold),longOffsets:g,heatmapScoresRaw:l,offsetsRaw:c,displacementFwdRaw:d,displacementBwdRaw:p,partSegmentation:function(e){var t=e.shape,n=t[0],r=t[1],a=t[2];return Ba(function(){var t=gm(e),s=Li(Nl(0,a,1,"int32"),1),o=Ls(No(t,s),"int32");return vo(o,[n,r])})}(m)}}),c=l.segmentation,d=l.longOffsets,p=l.heatmapScoresRaw,h=l.offsetsRaw,f=l.displacementFwdRaw,m=l.displacementBwdRaw,g=l.partSegmentation,[4,ig([p,h,f,m])];case 1:return y=S.sent(),b=y[0],x=y[1],v=y[2],w=y[3],k=ug(k=Km(b,x,v,w,this.baseModel.outputStride,t.maxDetections,t.scoreThreshold,t.nmsRadius),[r,a],s,u,!1),[4,Mm(c,d,g,k,r,a,this.baseModel.outputStride,s,u,t.scoreThreshold,t.refineSteps,t.minKeypointScore,t.maxDetections)];case 2:return I=S.sent(),i.dispose(),c.dispose(),d.dispose(),p.dispose(),h.dispose(),f.dispose(),m.dispose(),g.dispose(),[2,I]}})})},e.prototype.dispose=function(){this.baseModel.dispose()},e}();function xg(e){return lm(this,0,void 0,function(){var t,n,r,a,s,o;return cm(this,function(i){switch(i.label){case 0:if(t=e.outputStride,n=e.quantBytes,r=e.multiplier,null==Ah)throw new Error("Cannot find TensorFlow.js. If you are using a