(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[414],{4699:function(e,t){"use strict";t.byteLength=function(e){var t=getLens(e),n=t[0],i=t[1];return(n+i)*3/4-i},t.toByteArray=function(e){var t,n,o=getLens(e),a=o[0],u=o[1],c=new s((a+u)*3/4-u),f=0,p=u>0?a-4:a;for(n=0;n>16&255,c[f++]=t>>8&255,c[f++]=255&t;return 2===u&&(t=i[e.charCodeAt(n)]<<2|i[e.charCodeAt(n+1)]>>4,c[f++]=255&t),1===u&&(t=i[e.charCodeAt(n)]<<10|i[e.charCodeAt(n+1)]<<4|i[e.charCodeAt(n+2)]>>2,c[f++]=t>>8&255,c[f++]=255&t),c},t.fromByteArray=function(e){for(var t,i=e.length,s=i%3,o=[],a=0,u=i-s;a>18&63]+n[s>>12&63]+n[s>>6&63]+n[63&s]);return o.join("")}(e,a,a+16383>u?u:a+16383));return 1===s?o.push(n[(t=e[i-1])>>2]+n[t<<4&63]+"=="):2===s&&o.push(n[(t=(e[i-2]<<8)+e[i-1])>>10]+n[t>>4&63]+n[t<<2&63]+"="),o.join("")};for(var n=[],i=[],s="undefined"!=typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,u=o.length;a0)throw Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");-1===n&&(n=t);var i=n===t?0:4-n%4;return[n,i]}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},7133:function(e,t,n){"use strict";/*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT */var i=n(4699),s=n(9087),o="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;function createBuffer(e){if(e>2147483647)throw RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return Object.setPrototypeOf(t,Buffer.prototype),t}function Buffer(e,t,n){if("number"==typeof e){if("string"==typeof t)throw TypeError('The "string" argument must be of type string. Received type number');return allocUnsafe(e)}return from(e,t,n)}function from(e,t,n){if("string"==typeof e)return function(e,t){if(("string"!=typeof t||""===t)&&(t="utf8"),!Buffer.isEncoding(t))throw TypeError("Unknown encoding: "+t);var n=0|byteLength(e,t),i=createBuffer(n),s=i.write(e,t);return s!==n&&(i=i.slice(0,s)),i}(e,t);if(ArrayBuffer.isView(e))return function(e){if(isInstance(e,Uint8Array)){var t=new Uint8Array(e);return fromArrayBuffer(t.buffer,t.byteOffset,t.byteLength)}return fromArrayLike(e)}(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(isInstance(e,ArrayBuffer)||e&&isInstance(e.buffer,ArrayBuffer)||"undefined"!=typeof SharedArrayBuffer&&(isInstance(e,SharedArrayBuffer)||e&&isInstance(e.buffer,SharedArrayBuffer)))return fromArrayBuffer(e,t,n);if("number"==typeof e)throw TypeError('The "value" argument must not be of type number. Received type number');var i=e.valueOf&&e.valueOf();if(null!=i&&i!==e)return Buffer.from(i,t,n);var s=function(e){if(Buffer.isBuffer(e)){var t,n=0|checked(e.length),i=createBuffer(n);return 0===i.length||e.copy(i,0,0,n),i}return void 0!==e.length?"number"!=typeof e.length||(t=e.length)!=t?createBuffer(0):fromArrayLike(e):"Buffer"===e.type&&Array.isArray(e.data)?fromArrayLike(e.data):void 0}(e);if(s)return s;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return Buffer.from(e[Symbol.toPrimitive]("string"),t,n);throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function assertSize(e){if("number"!=typeof e)throw TypeError('"size" argument must be of type number');if(e<0)throw RangeError('The value "'+e+'" is invalid for option "size"')}function allocUnsafe(e){return assertSize(e),createBuffer(e<0?0:0|checked(e))}function fromArrayLike(e){for(var t=e.length<0?0:0|checked(e.length),n=createBuffer(t),i=0;i=2147483647)throw RangeError("Attempt to allocate Buffer larger than maximum size: 0x7fffffff bytes");return 0|e}function byteLength(e,t){if(Buffer.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||isInstance(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var n=e.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===n)return 0;for(var s=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return utf8ToBytes(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return base64ToBytes(e).length;default:if(s)return i?-1:utf8ToBytes(e).length;t=(""+t).toLowerCase(),s=!0}}function slowToString(e,t,n){var s,o,a=!1;if((void 0===t||t<0)&&(t=0),t>this.length||((void 0===n||n>this.length)&&(n=this.length),n<=0||(n>>>=0)<=(t>>>=0)))return"";for(e||(e="utf8");;)switch(e){case"hex":return function(e,t,n){var i=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>i)&&(n=i);for(var s="",o=t;o2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),(o=n=+n)!=o&&(n=s?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(s)return -1;n=e.length-1}else if(n<0){if(!s)return -1;n=0}if("string"==typeof t&&(t=Buffer.from(t,i)),Buffer.isBuffer(t))return 0===t.length?-1:arrayIndexOf(e,t,n,i,s);if("number"==typeof t)return(t&=255,"function"==typeof Uint8Array.prototype.indexOf)?s?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):arrayIndexOf(e,[t],n,i,s);throw TypeError("val must be string, number or Buffer")}function arrayIndexOf(e,t,n,i,s){var o,a=1,u=e.length,c=t.length;if(void 0!==i&&("ucs2"===(i=String(i).toLowerCase())||"ucs-2"===i||"utf16le"===i||"utf-16le"===i)){if(e.length<2||t.length<2)return -1;a=2,u/=2,c/=2,n/=2}function read(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(s){var f=-1;for(o=n;ou&&(n=u-c),o=n;o>=0;o--){for(var p=!0,m=0;m239?4:f>223?3:f>191?2:1;if(s+m<=n)switch(m){case 1:f<128&&(p=f);break;case 2:(192&(o=e[s+1]))==128&&(c=(31&f)<<6|63&o)>127&&(p=c);break;case 3:o=e[s+1],a=e[s+2],(192&o)==128&&(192&a)==128&&(c=(15&f)<<12|(63&o)<<6|63&a)>2047&&(c<55296||c>57343)&&(p=c);break;case 4:o=e[s+1],a=e[s+2],u=e[s+3],(192&o)==128&&(192&a)==128&&(192&u)==128&&(c=(15&f)<<18|(63&o)<<12|(63&a)<<6|63&u)>65535&&c<1114112&&(p=c)}null===p?(p=65533,m=1):p>65535&&(p-=65536,i.push(p>>>10&1023|55296),p=56320|1023&p),i.push(p),s+=m}return function(e){var t=e.length;if(t<=4096)return String.fromCharCode.apply(String,e);for(var n="",i=0;in)throw RangeError("Trying to access beyond buffer length")}function checkInt(e,t,n,i,s,o){if(!Buffer.isBuffer(e))throw TypeError('"buffer" argument must be a Buffer instance');if(t>s||te.length)throw RangeError("Index out of range")}function checkIEEE754(e,t,n,i,s,o){if(n+i>e.length||n<0)throw RangeError("Index out of range")}function writeFloat(e,t,n,i,o){return t=+t,n>>>=0,o||checkIEEE754(e,t,n,4,34028234663852886e22,-34028234663852886e22),s.write(e,t,n,i,23,4),n+4}function writeDouble(e,t,n,i,o){return t=+t,n>>>=0,o||checkIEEE754(e,t,n,8,17976931348623157e292,-17976931348623157e292),s.write(e,t,n,i,52,8),n+8}t.lW=Buffer,t.h2=50,Buffer.TYPED_ARRAY_SUPPORT=function(){try{var e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),Buffer.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(Buffer.prototype,"parent",{enumerable:!0,get:function(){if(Buffer.isBuffer(this))return this.buffer}}),Object.defineProperty(Buffer.prototype,"offset",{enumerable:!0,get:function(){if(Buffer.isBuffer(this))return this.byteOffset}}),Buffer.poolSize=8192,Buffer.from=function(e,t,n){return from(e,t,n)},Object.setPrototypeOf(Buffer.prototype,Uint8Array.prototype),Object.setPrototypeOf(Buffer,Uint8Array),Buffer.alloc=function(e,t,n){return(assertSize(e),e<=0)?createBuffer(e):void 0!==t?"string"==typeof n?createBuffer(e).fill(t,n):createBuffer(e).fill(t):createBuffer(e)},Buffer.allocUnsafe=function(e){return allocUnsafe(e)},Buffer.allocUnsafeSlow=function(e){return allocUnsafe(e)},Buffer.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==Buffer.prototype},Buffer.compare=function(e,t){if(isInstance(e,Uint8Array)&&(e=Buffer.from(e,e.offset,e.byteLength)),isInstance(t,Uint8Array)&&(t=Buffer.from(t,t.offset,t.byteLength)),!Buffer.isBuffer(e)||!Buffer.isBuffer(t))throw TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;for(var n=e.length,i=t.length,s=0,o=Math.min(n,i);si.length?Buffer.from(o).copy(i,s):Uint8Array.prototype.set.call(i,o,s);else if(Buffer.isBuffer(o))o.copy(i,s);else throw TypeError('"list" argument must be an Array of Buffers');s+=o.length}return i},Buffer.byteLength=byteLength,Buffer.prototype._isBuffer=!0,Buffer.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;tn&&(e+=" ... "),""},o&&(Buffer.prototype[o]=Buffer.prototype.inspect),Buffer.prototype.compare=function(e,t,n,i,s){if(isInstance(e,Uint8Array)&&(e=Buffer.from(e,e.offset,e.byteLength)),!Buffer.isBuffer(e))throw TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===i&&(i=0),void 0===s&&(s=this.length),t<0||n>e.length||i<0||s>this.length)throw RangeError("out of range index");if(i>=s&&t>=n)return 0;if(i>=s)return -1;if(t>=n)return 1;if(t>>>=0,n>>>=0,i>>>=0,s>>>=0,this===e)return 0;for(var o=s-i,a=n-t,u=Math.min(o,a),c=this.slice(i,s),f=e.slice(t,n),p=0;p>>=0,isFinite(n)?(n>>>=0,void 0===i&&(i="utf8")):(i=n,n=void 0);else throw Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var s,o,a,u,c,f,p,m,g=this.length-t;if((void 0===n||n>g)&&(n=g),e.length>0&&(n<0||t<0)||t>this.length)throw RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var _=!1;;)switch(i){case"hex":return function(e,t,n,i){n=Number(n)||0;var s=e.length-n;i?(i=Number(i))>s&&(i=s):i=s;var o=t.length;i>o/2&&(i=o/2);for(var a=0;a>8,s.push(n%256),s.push(i);return s}(e,this.length-p),this,p,m);default:if(_)throw TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),_=!0}},Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},Buffer.prototype.slice=function(e,t){var n=this.length;e=~~e,t=void 0===t?n:~~t,e<0?(e+=n)<0&&(e=0):e>n&&(e=n),t<0?(t+=n)<0&&(t=0):t>n&&(t=n),t>>=0,t>>>=0,n||checkOffset(e,t,this.length);for(var i=this[e],s=1,o=0;++o>>=0,t>>>=0,n||checkOffset(e,t,this.length);for(var i=this[e+--t],s=1;t>0&&(s*=256);)i+=this[e+--t]*s;return i},Buffer.prototype.readUint8=Buffer.prototype.readUInt8=function(e,t){return e>>>=0,t||checkOffset(e,1,this.length),this[e]},Buffer.prototype.readUint16LE=Buffer.prototype.readUInt16LE=function(e,t){return e>>>=0,t||checkOffset(e,2,this.length),this[e]|this[e+1]<<8},Buffer.prototype.readUint16BE=Buffer.prototype.readUInt16BE=function(e,t){return e>>>=0,t||checkOffset(e,2,this.length),this[e]<<8|this[e+1]},Buffer.prototype.readUint32LE=Buffer.prototype.readUInt32LE=function(e,t){return e>>>=0,t||checkOffset(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},Buffer.prototype.readUint32BE=Buffer.prototype.readUInt32BE=function(e,t){return e>>>=0,t||checkOffset(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},Buffer.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||checkOffset(e,t,this.length);for(var i=this[e],s=1,o=0;++o=(s*=128)&&(i-=Math.pow(2,8*t)),i},Buffer.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||checkOffset(e,t,this.length);for(var i=t,s=1,o=this[e+--i];i>0&&(s*=256);)o+=this[e+--i]*s;return o>=(s*=128)&&(o-=Math.pow(2,8*t)),o},Buffer.prototype.readInt8=function(e,t){return(e>>>=0,t||checkOffset(e,1,this.length),128&this[e])?-((255-this[e]+1)*1):this[e]},Buffer.prototype.readInt16LE=function(e,t){e>>>=0,t||checkOffset(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},Buffer.prototype.readInt16BE=function(e,t){e>>>=0,t||checkOffset(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},Buffer.prototype.readInt32LE=function(e,t){return e>>>=0,t||checkOffset(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},Buffer.prototype.readInt32BE=function(e,t){return e>>>=0,t||checkOffset(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},Buffer.prototype.readFloatLE=function(e,t){return e>>>=0,t||checkOffset(e,4,this.length),s.read(this,e,!0,23,4)},Buffer.prototype.readFloatBE=function(e,t){return e>>>=0,t||checkOffset(e,4,this.length),s.read(this,e,!1,23,4)},Buffer.prototype.readDoubleLE=function(e,t){return e>>>=0,t||checkOffset(e,8,this.length),s.read(this,e,!0,52,8)},Buffer.prototype.readDoubleBE=function(e,t){return e>>>=0,t||checkOffset(e,8,this.length),s.read(this,e,!1,52,8)},Buffer.prototype.writeUintLE=Buffer.prototype.writeUIntLE=function(e,t,n,i){if(e=+e,t>>>=0,n>>>=0,!i){var s=Math.pow(2,8*n)-1;checkInt(this,e,t,n,s,0)}var o=1,a=0;for(this[t]=255&e;++a>>=0,n>>>=0,!i){var s=Math.pow(2,8*n)-1;checkInt(this,e,t,n,s,0)}var o=n-1,a=1;for(this[t+o]=255&e;--o>=0&&(a*=256);)this[t+o]=e/a&255;return t+n},Buffer.prototype.writeUint8=Buffer.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||checkInt(this,e,t,1,255,0),this[t]=255&e,t+1},Buffer.prototype.writeUint16LE=Buffer.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||checkInt(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},Buffer.prototype.writeUint16BE=Buffer.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||checkInt(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},Buffer.prototype.writeUint32LE=Buffer.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||checkInt(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},Buffer.prototype.writeUint32BE=Buffer.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||checkInt(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},Buffer.prototype.writeIntLE=function(e,t,n,i){if(e=+e,t>>>=0,!i){var s=Math.pow(2,8*n-1);checkInt(this,e,t,n,s-1,-s)}var o=0,a=1,u=0;for(this[t]=255&e;++o>0)-u&255;return t+n},Buffer.prototype.writeIntBE=function(e,t,n,i){if(e=+e,t>>>=0,!i){var s=Math.pow(2,8*n-1);checkInt(this,e,t,n,s-1,-s)}var o=n-1,a=1,u=0;for(this[t+o]=255&e;--o>=0&&(a*=256);)e<0&&0===u&&0!==this[t+o+1]&&(u=1),this[t+o]=(e/a>>0)-u&255;return t+n},Buffer.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||checkInt(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},Buffer.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||checkInt(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},Buffer.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||checkInt(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},Buffer.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||checkInt(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},Buffer.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||checkInt(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},Buffer.prototype.writeFloatLE=function(e,t,n){return writeFloat(this,e,t,!0,n)},Buffer.prototype.writeFloatBE=function(e,t,n){return writeFloat(this,e,t,!1,n)},Buffer.prototype.writeDoubleLE=function(e,t,n){return writeDouble(this,e,t,!0,n)},Buffer.prototype.writeDoubleBE=function(e,t,n){return writeDouble(this,e,t,!1,n)},Buffer.prototype.copy=function(e,t,n,i){if(!Buffer.isBuffer(e))throw TypeError("argument should be a Buffer");if(n||(n=0),i||0===i||(i=this.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&i=this.length)throw RangeError("Index out of range");if(i<0)throw RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(s=t;s55295&&n<57344){if(!s){if(n>56319||a+1===i){(t-=3)>-1&&o.push(239,191,189);continue}s=n;continue}if(n<56320){(t-=3)>-1&&o.push(239,191,189),s=n;continue}n=(s-55296<<10|n-56320)+65536}else s&&(t-=3)>-1&&o.push(239,191,189);if(s=null,n<128){if((t-=1)<0)break;o.push(n)}else if(n<2048){if((t-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;o.push(n>>12|224,n>>6&63|128,63&n|128)}else if(n<1114112){if((t-=4)<0)break;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}else throw Error("Invalid code point")}return o}function base64ToBytes(e){return i.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(a,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function blitBuffer(e,t,n,i){for(var s=0;s=t.length)&&!(s>=e.length);++s)t[s+n]=e[s];return s}function isInstance(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}var u=function(){for(var e="0123456789abcdef",t=Array(256),n=0;n<16;++n)for(var i=16*n,s=0;s<16;++s)t[i+s]=e[n]+e[s];return t}()},9087:function(e,t){/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */t.read=function(e,t,n,i,s){var o,a,u=8*s-i-1,c=(1<>1,p=-7,m=n?s-1:0,g=n?-1:1,_=e[t+m];for(m+=g,o=_&(1<<-p)-1,_>>=-p,p+=u;p>0;o=256*o+e[t+m],m+=g,p-=8);for(a=o&(1<<-p)-1,o>>=-p,p+=i;p>0;a=256*a+e[t+m],m+=g,p-=8);if(0===o)o=1-f;else{if(o===c)return a?NaN:(_?-1:1)*(1/0);a+=Math.pow(2,i),o-=f}return(_?-1:1)*a*Math.pow(2,o-i)},t.write=function(e,t,n,i,s,o){var a,u,c,f=8*o-s-1,p=(1<>1,g=23===s?5960464477539062e-23:0,_=i?0:o-1,y=i?1:-1,w=t<0||0===t&&1/t<0?1:0;for(isNaN(t=Math.abs(t))||t===1/0?(u=isNaN(t)?1:0,a=p):(a=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-a))<1&&(a--,c*=2),a+m>=1?t+=g/c:t+=g*Math.pow(2,1-m),t*c>=2&&(a++,c/=2),a+m>=p?(u=0,a=p):a+m>=1?(u=(t*c-1)*Math.pow(2,s),a+=m):(u=t*Math.pow(2,m-1)*Math.pow(2,s),a=0));s>=8;e[n+_]=255&u,_+=y,u/=256,s-=8);for(a=a<0;e[n+_]=255&a,_+=y,a/=256,f-=8);e[n+_-y]|=128*w}},2601:function(e,t,n){"use strict";var i,s;e.exports=(null==(i=n.g.process)?void 0:i.env)&&"object"==typeof(null==(s=n.g.process)?void 0:s.env)?n.g.process:n(8960)},692:function(e,t,n){!function(){var t={452:function(e){"use strict";e.exports=n(9875)}},i={};function __nccwpck_require__(e){var n=i[e];if(void 0!==n)return n.exports;var s=i[e]={exports:{}},o=!0;try{t[e](s,s.exports,__nccwpck_require__),o=!1}finally{o&&delete i[e]}return s.exports}__nccwpck_require__.ab="//";var s={};!function(){var e,t=(e=__nccwpck_require__(452))&&"object"==typeof e&&"default"in e?e.default:e,n=/https?|ftp|gopher|file/;function r(e){"string"==typeof e&&(e=d(e));var i,s,o,a,u,c,f,p,m,g=(s=(i=e).auth,o=i.hostname,a=i.protocol||"",u=i.pathname||"",c=i.hash||"",f=i.query||"",p=!1,s=s?encodeURIComponent(s).replace(/%3A/i,":")+"@":"",i.host?p=s+i.host:o&&(p=s+(~o.indexOf(":")?"["+o+"]":o),i.port&&(p+=":"+i.port)),f&&"object"==typeof f&&(f=t.encode(f)),m=i.search||f&&"?"+f||"",a&&":"!==a.substr(-1)&&(a+=":"),i.slashes||(!a||n.test(a))&&!1!==p?(p="//"+(p||""),u&&"/"!==u[0]&&(u="/"+u)):p||(p=""),c&&"#"!==c[0]&&(c="#"+c),m&&"?"!==m[0]&&(m="?"+m),{protocol:a,host:p,pathname:u=u.replace(/[?#]/g,encodeURIComponent),search:m=m.replace("#","%23"),hash:c});return""+g.protocol+g.host+g.pathname+g.search+g.hash}var i="http://",o=i+"w.w",a=/^([a-z0-9.+-]*:\/\/\/)([a-z0-9.+-]:\/*)?/i,u=/https?|ftp|gopher|file/;function h(e,t){var n="string"==typeof e?d(e):e;e="object"==typeof e?r(e):e;var s=d(t),c="";n.protocol&&!n.slashes&&(c=n.protocol,e=e.replace(n.protocol,""),c+="/"===t[0]||"/"===e[0]?"/":""),c&&s.protocol&&(c="",s.slashes||(c=s.protocol,t=t.replace(s.protocol,"")));var f=e.match(a);f&&!s.protocol&&(e=e.substr((c=f[1]+(f[2]||"")).length),/^\/\/[^/]/.test(t)&&(c=c.slice(0,-1)));var p=new URL(e,o+"/"),m=new URL(t,p).toString().replace(o,""),g=s.protocol||n.protocol;return g+=n.slashes||s.slashes?"//":"",!c&&g?m=m.replace(i,g):c&&(m=m.replace(i,"")),u.test(m)||~t.indexOf(".")||"/"===e.slice(-1)||"/"===t.slice(-1)||"/"!==m.slice(-1)||(m=m.slice(0,-1)),c&&(m=c+("/"===m[0]?m.substr(1):m)),m}function l(){}l.prototype.parse=d,l.prototype.format=r,l.prototype.resolve=h,l.prototype.resolveObject=h;var c=/^https?|ftp|gopher|file/,f=/^(.*?)([#?].*)/,p=/^([a-z0-9.+-]*:)(\/{0,3})(.*)/i,m=/^([a-z0-9.+-]*:)?\/\/\/*/i,g=/^([a-z0-9.+-]*:)(\/{0,2})\[(.*)\]$/i;function d(e,n,i){if(void 0===n&&(n=!1),void 0===i&&(i=!1),e&&"object"==typeof e&&e instanceof l)return e;var s=(e=e.trim()).match(f);e=s?s[1].replace(/\\/g,"/")+s[2]:e.replace(/\\/g,"/"),g.test(e)&&"/"!==e.slice(-1)&&(e+="/");var a=!/(^javascript)/.test(e)&&e.match(p),u=m.test(e),_="";a&&(c.test(a[1])||(_=a[1].toLowerCase(),e=""+a[2]+a[3]),a[2]||(u=!1,c.test(a[1])?(_=a[1],e=""+a[3]):e="//"+a[3]),3!==a[2].length&&1!==a[2].length||(_=a[1],e="/"+a[3]));var y,w=(s?s[1]:e).match(/^https?:\/\/[^/]+(:[0-9]+)(?=\/|$)/),b=w&&w[1],v=new l,x="",E="";try{y=new URL(e)}catch(t){x=t,_||i||!/^\/\//.test(e)||/^\/\/.+[@.]/.test(e)||(E="/",e=e.substr(1));try{y=new URL(e,o)}catch(e){return v.protocol=_,v.href=_,v}}v.slashes=u&&!E,v.host="w.w"===y.host?"":y.host,v.hostname="w.w"===y.hostname?"":y.hostname.replace(/(\[|\])/g,""),v.protocol=x?_||null:y.protocol,v.search=y.search.replace(/\\/g,"%5C"),v.hash=y.hash.replace(/\\/g,"%5C");var A=e.split("#");!v.search&&~A[0].indexOf("?")&&(v.search="?"),v.hash||""!==A[1]||(v.hash="#"),v.query=n?t.decode(y.search.substr(1)):v.search.substr(1),v.pathname=E+(a?y.pathname.replace(/['^|`]/g,function(e){return"%"+e.charCodeAt().toString(16).toUpperCase()}).replace(/((?:%[0-9A-F]{2})+)/g,function(e,t){try{return decodeURIComponent(t).split("").map(function(e){var t=e.charCodeAt();return t>256||/^[a-z0-9]$/i.test(e)?e:"%"+t.toString(16).toUpperCase()}).join("")}catch(e){return t}}):y.pathname),"about:"===v.protocol&&"blank"===v.pathname&&(v.protocol="",v.pathname=""),x&&"/"!==e[0]&&(v.pathname=v.pathname.substr(1)),_&&!c.test(_)&&"/"!==e.slice(-1)&&"/"===v.pathname&&(v.pathname=""),v.path=v.pathname+v.search,v.auth=[y.username,y.password].map(decodeURIComponent).filter(Boolean).join(":"),v.port=y.port,b&&!v.host.endsWith(b)&&(v.host+=b,v.port=b.slice(1)),v.href=E?""+v.pathname+v.search+v.hash:r(v);var k=/^(file)/.test(v.href)?["host","hostname"]:[];return Object.keys(v).forEach(function(e){~k.indexOf(e)||(v[e]=v[e]||null)}),v}s.parse=d,s.format=r,s.resolve=h,s.resolveObject=function(e,t){return d(h(e,t))},s.Url=l}(),e.exports=s}()},8960:function(e){!function(){var t={229:function(e){var t,n,i,s=e.exports={};function defaultSetTimout(){throw Error("setTimeout has not been defined")}function defaultClearTimeout(){throw Error("clearTimeout has not been defined")}function runTimeout(e){if(t===setTimeout)return setTimeout(e,0);if((t===defaultSetTimout||!t)&&setTimeout)return t=setTimeout,setTimeout(e,0);try{return t(e,0)}catch(n){try{return t.call(null,e,0)}catch(n){return t.call(this,e,0)}}}!function(){try{t="function"==typeof setTimeout?setTimeout:defaultSetTimout}catch(e){t=defaultSetTimout}try{n="function"==typeof clearTimeout?clearTimeout:defaultClearTimeout}catch(e){n=defaultClearTimeout}}();var o=[],a=!1,u=-1;function cleanUpNextTick(){a&&i&&(a=!1,i.length?o=i.concat(o):u=-1,o.length&&drainQueue())}function drainQueue(){if(!a){var e=runTimeout(cleanUpNextTick);a=!0;for(var t=o.length;t;){for(i=o,o=[];++u1)for(var n=1;n0&&c>u&&(c=u);for(var f=0;f=0?(p=y.substr(0,w),m=y.substr(w+1)):(p=y,m=""),g=decodeURIComponent(p),_=decodeURIComponent(m),Object.prototype.hasOwnProperty.call(o,g))?t(o[g])?o[g].push(_):o[g]=[o[g],_]:o[g]=_}return o};var t=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},577:function(e){var stringifyPrimitive=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};e.exports=function(e,i,s,o){return(i=i||"&",s=s||"=",null===e&&(e=void 0),"object"==typeof e)?map(n(e),function(n){var o=encodeURIComponent(stringifyPrimitive(n))+s;return t(e[n])?map(e[n],function(e){return o+encodeURIComponent(stringifyPrimitive(e))}).join(i):o+encodeURIComponent(stringifyPrimitive(e[n]))}).join(i):o?encodeURIComponent(stringifyPrimitive(o))+s+encodeURIComponent(stringifyPrimitive(e)):""};var t=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};function map(e,t){if(e.map)return e.map(t);for(var n=[],i=0;i{if(t&&"function"==typeof t.init&&"function"==typeof t.createSessionHandler){let o=i[e];if(void 0===o)i[e]={backend:t,priority:n};else if(o.priority>n)return;else if(o.priority===n&&o.backend!==t)throw Error(`cannot register backend "${e}" using priority ${n}`);if(n>=0){let t=s.indexOf(e);-1!==t&&s.splice(t,1);for(let t=0;t{let t=0===e.length?s:e,n=[];for(let e of t){let t=i[e];if(t){if(t.initialized)return t.backend;if(t.aborted)continue;let i=!!t.initPromise;try{return i||(t.initPromise=t.backend.init()),await t.initPromise,t.initialized=!0,t.backend}catch(s){i||n.push({name:e,err:s}),t.aborted=!0}finally{delete t.initPromise}}}throw Error(`no available backend found. ERR: ${n.map(e=>`[${e.name}] ${e.err}`).join(", ")}`)},o=new class{constructor(){this.wasm={},this.webgl={},this.logLevelInternal="warning"}set logLevel(e){if(void 0!==e){if("string"!=typeof e||-1===["verbose","info","warning","error","fatal"].indexOf(e))throw Error(`Unsupported logging level: ${e}`);this.logLevelInternal=e}}get logLevel(){return this.logLevelInternal}},a="undefined"!=typeof BigInt64Array&&"function"==typeof BigInt64Array.from,u="undefined"!=typeof BigUint64Array&&"function"==typeof BigUint64Array.from,c=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),f=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);a&&(c.set("int64",BigInt64Array),f.set(BigInt64Array,"int64")),u&&(c.set("uint64",BigUint64Array),f.set(BigUint64Array,"uint64"));let calculateSize=e=>{let t=1;for(let n=0;n{let s=document.createElement("canvas"),o=s.getContext("2d");if(!e||!o)return i();let a=new Image;a.crossOrigin="Anonymous",a.src=e,a.onload=()=>{s.width=a.width,s.height=a.height,o.drawImage(a,0,0,s.width,s.height);let e=o.getImageData(0,0,s.width,s.height);if(void 0!==t){if(void 0!==t.height&&t.height!==s.height)throw Error("Image input config height doesn't match ImageBitmap height");if(u.height=s.height,void 0!==t.width&&t.width!==s.width)throw Error("Image input config width doesn't match ImageBitmap width");u.width=s.width}else u.height=s.height,u.width=s.width;n(Tensor.bufferToTensor(e.data,u))}});else throw Error("Input data provided is not supported - aborted tensor creation");if(void 0!==n)return Tensor.bufferToTensor(n,u);throw Error("Input data provided is not supported - aborted tensor creation")}toImageData(e){var t,n;let i;let s=document.createElement("canvas").getContext("2d");if(null!=s){let o=this.dims[3],a=this.dims[2],u=this.dims[1],c=void 0!==e&&void 0!==e.format?e.format:"RGB",f=void 0!==e&&(null===(t=e.norm)||void 0===t?void 0:t.mean)!==void 0?e.norm.mean:255,p=void 0!==e&&(null===(n=e.norm)||void 0===n?void 0:n.bias)!==void 0?e.norm.bias:0,m=a*o;if(void 0!==e){if(void 0!==e.height&&e.height!==a)throw Error("Image output config height doesn't match tensor height");if(void 0!==e.width&&e.width!==o)throw Error("Image output config width doesn't match tensor width");if(void 0!==e.format&&4===u&&"RGBA"!==e.format||3===u&&"RGB"!==e.format&&"BGR"!==e.format)throw Error("Tensor format doesn't match input tensor dims")}let g=0,_=1,y=2,w=3,b=0,v=m,x=2*m,E=-1;"RGBA"===c?(b=0,v=m,x=2*m,E=3*m):"RGB"===c?(b=0,v=m,x=2*m):"RBG"===c&&(b=0,x=m,v=2*m),i=s.createImageData(o,a);for(let e=0;e=e.byteLength)throw RangeError(`'byteOffset' is out of range [0, ${e.byteLength}).`);if(u=e.byteLength-a,"number"==typeof n){if(!Number.isSafeInteger(u=n))throw RangeError("'byteLength' must be an integer.");if(u<=0||a+u>e.byteLength)throw RangeError(`'byteLength' is out of range (0, ${e.byteLength-a}].`);if("object"==typeof i&&null!==i)o=i;else if(void 0!==i)throw TypeError("'options' must be an object.")}else if(void 0!==n)throw TypeError("'byteLength' must be a number.")}else if(void 0!==t)throw TypeError("'options' must be an object.");s=new Uint8Array(e,a,u)}else throw TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let a=o.executionProviders||[],u=a.map(e=>"string"==typeof e?e:e.name),c=await resolveBackend(u),f=await c.createSessionHandler(s,o);return new InferenceSession(f)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}};let m=InferenceSession},8828:function(e,t,n){"use strict";n.d(t,{YS:function(){return $}});var i=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",NotIn:"NotIn",Else:"Else",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator"}),s=Object.freeze({set:i.Set,for:i.For,in:i.In,if:i.If,else:i.Else,endif:i.EndIf,elif:i.ElseIf,endfor:i.EndFor,and:i.And,or:i.Or,not:i.Not,"not in":i.NotIn,true:i.BooleanLiteral,false:i.BooleanLiteral}),o=class{constructor(e,t){this.value=e,this.type=t}};function isWord(e){return/\w/.test(e)}function isInteger(e){return/[0-9]/.test(e)}var a=[["{%",i.OpenStatement],["%}",i.CloseStatement],["{{",i.OpenExpression],["}}",i.CloseExpression],["(",i.OpenParen],[")",i.CloseParen],["[",i.OpenSquareBracket],["]",i.CloseSquareBracket],[",",i.Comma],[".",i.Dot],[":",i.Colon],["|",i.Pipe],["<=",i.ComparisonBinaryOperator],[">=",i.ComparisonBinaryOperator],["==",i.ComparisonBinaryOperator],["!=",i.ComparisonBinaryOperator],["<",i.ComparisonBinaryOperator],[">",i.ComparisonBinaryOperator],["+",i.AdditiveBinaryOperator],["-",i.AdditiveBinaryOperator],["*",i.MultiplicativeBinaryOperator],["/",i.MultiplicativeBinaryOperator],["%",i.MultiplicativeBinaryOperator],["=",i.Equals]],u=new Map([["n","\n"],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]),c=class{type="Statement"},f=class extends c{constructor(e){super(),this.body=e}type="Program"},p=class extends c{constructor(e,t,n){super(),this.test=e,this.body=t,this.alternate=n}type="If"},m=class extends c{constructor(e,t,n){super(),this.loopvar=e,this.iterable=t,this.body=n}type="For"},g=class extends c{constructor(e,t){super(),this.assignee=e,this.value=t}type="Set"},_=class extends c{type="Expression"},y=class extends _{constructor(e,t,n){super(),this.object=e,this.property=t,this.computed=n}type="MemberExpression"},w=class extends _{constructor(e,t){super(),this.callee=e,this.args=t}type="CallExpression"},b=class extends _{constructor(e){super(),this.value=e}type="Identifier"},v=class extends _{constructor(e){super(),this.value=e}type="Literal"},x=class extends v{type="NumericLiteral"},E=class extends v{type="StringLiteral";constructor(e){super(e)}},A=class extends v{type="BooleanLiteral"},k=class extends _{constructor(e,t,n){super(),this.operator=e,this.left=t,this.right=n}type="BinaryExpression"},B=class extends _{constructor(e,t){super(),this.operand=e,this.filter=t}type="FilterExpression"},I=class extends _{constructor(e,t){super(),this.operator=e,this.argument=t}type="UnaryExpression"},T=class extends _{constructor(e,t,n){super(),this.start=e,this.stop=t,this.step=n}type="SliceExpression"};function slice(e,t,n,i=1){let s=Math.sign(i);s>=0?(t=(t??=0)<0?Math.max(e.length+t,0):Math.min(t,e.length),n=(n??=e.length)<0?Math.max(e.length+n,0):Math.min(n,e.length)):(t=(t??=e.length-1)<0?Math.max(e.length+t,-1):Math.min(t,e.length-1),n=(n??=-1)<-1?Math.max(e.length+n,-1):Math.min(n,e.length-1));let o=[];for(let a=t;s*anew C(this.value.toUpperCase()))],["lower",new M(()=>new C(this.value.toLowerCase()))],["strip",new M(()=>new C(this.value.trim()))],["length",new S(this.value.length)]])},O=class extends z{type="BooleanValue"},P=class extends z{type="ObjectValue";__bool__(){return new O(this.value.size>0)}},F=class extends z{type="ArrayValue";builtins=new Map([["length",new S(this.value.length)]]);__bool__(){return new O(this.value.length>0)}},M=class extends z{type="FunctionValue"},L=class extends z{type="NullValue"},U=class extends z{type="UndefinedValue"},R=class{constructor(e){this.parent=e}variables=new Map;set(e,t){return this.declareVariable(e,function convertToRuntimeValues(e){switch(typeof e){case"number":return new S(e);case"string":return new C(e);case"boolean":return new O(e);case"object":if(null===e)return new L;if(Array.isArray(e))return new F(e.map(convertToRuntimeValues));return new P(new Map(Object.entries(e).map(([e,t])=>[e,convertToRuntimeValues(t)])));case"function":return new M((t,n)=>{let i=e(...t.map(e=>e.value))??null;return convertToRuntimeValues(i)});default:throw Error(`Cannot convert to runtime value: ${e}`)}}(t))}declareVariable(e,t){if(this.variables.has(e))throw SyntaxError(`Variable already declared: ${e}`);return this.variables.set(e,t),t}setVariable(e,t){let n;try{n=this.resolve(e)}catch{}return(n??this).variables.set(e,t),t}resolve(e){if(this.variables.has(e))return this;if(this.parent)return this.parent.resolve(e);throw Error(`Unknown variable: ${e}`)}lookupVariable(e){return this.resolve(e).variables.get(e)??new L}},N=class{global;constructor(e){this.global=e??new R}run(e){return this.evaluate(e,this.global)}evaluateBinaryExpression(e,t){let n=this.evaluate(e.left,t),i=this.evaluate(e.right,t);switch(e.operator.value){case"==":return new O(n.value==i.value);case"!=":return new O(n.value!=i.value);case"and":return n.__bool__().value?i:n;case"or":return n.__bool__().value?n:i}if(n instanceof U||i instanceof U)throw Error("Cannot perform operation on undefined values");if(n instanceof L||i instanceof L)throw Error("Cannot perform operation on null values");if(n instanceof S&&i instanceof S)switch(e.operator.value){case"+":return new S(n.value+i.value);case"-":return new S(n.value-i.value);case"*":return new S(n.value*i.value);case"/":return new S(n.value/i.value);case"%":return new S(n.value%i.value);case"<":return new O(n.value":return new O(n.value>i.value);case">=":return new O(n.value>=i.value);case"<=":return new O(n.value<=i.value)}else if(i instanceof F){let t=void 0!==i.value.find(e=>e.value===n.value);switch(e.operator.value){case"in":return new O(t);case"not in":return new O(!t)}}if((n instanceof C||i instanceof C)&&"+"===e.operator.value)return new C(n.value.toString()+i.value.toString());if(n instanceof C&&i instanceof C)switch(e.operator.value){case"in":return new O(i.value.includes(n.value));case"not in":return new O(!i.value.includes(n.value))}throw SyntaxError(`Unknown operator "${e.operator.value}" between ${n.type} and ${i.type}`)}evaluateFilterExpression(e,t){let n=this.evaluate(e.operand,t);if(n instanceof F)switch(e.filter.value){case"first":return n.value[0];case"last":return n.value[n.value.length-1];case"length":return new S(n.value.length);case"reverse":return new F(n.value.reverse());case"sort":return new F(n.value.sort((e,t)=>{if(e.type!==t.type)throw Error(`Cannot compare different types: ${e.type} and ${t.type}`);switch(e.type){case"NumericValue":return e.value-t.value;case"StringValue":return e.value.localeCompare(t.value);default:throw Error(`Cannot compare type: ${e.type}`)}}));default:throw Error(`Unknown filter: ${e.filter.value}`)}throw Error(`Cannot apply filter to type: ${n.type}`)}evaluateUnaryExpression(e,t){let n=this.evaluate(e.argument,t);if("not"===e.operator.value)return new O(!n.value);throw SyntaxError(`Unknown operator: ${e.operator.value}`)}evalProgram(e,t){return this.evaluateBlock(e.body,t)}evaluateBlock(e,t){let n="";for(let i of e){let e=this.evaluate(i,t);"NullValue"!==e.type&&(n+=e.value)}return n=n.replace(/^\n/,""),new C(n)}evaluateIdentifier(e,t){return t.lookupVariable(e.value)}evaluateCallExpression(e,t){let n=e.args.map(e=>this.evaluate(e,t)),i=this.evaluate(e.callee,t);if("FunctionValue"!==i.type)throw Error(`Cannot call something that is not a function: got ${i.type}`);return i.value(n,t)}evaluateSliceExpression(e,t,n){if(!(e instanceof F||e instanceof C))throw Error("Slice object must be an array or string");let i=this.evaluate(t.start,n),s=this.evaluate(t.stop,n),o=this.evaluate(t.step,n);if(!(i instanceof S||i instanceof U))throw Error("Slice start must be numeric or undefined");if(!(s instanceof S||s instanceof U))throw Error("Slice stop must be numeric or undefined");if(!(o instanceof S||o instanceof U))throw Error("Slice step must be numeric or undefined");return e instanceof F?new F(slice(e.value,i.value,s.value,o.value)):new C(slice(Array.from(e.value),i.value,s.value,o.value).join(""))}evaluateMemberExpression(e,t){let n,i;let s=this.evaluate(e.object,t);if(e.computed){if("SliceExpression"===e.property.type)return this.evaluateSliceExpression(s,e.property,t);n=this.evaluate(e.property,t)}else n=new C(e.property.value);if(s instanceof P){if(!(n instanceof C))throw Error(`Cannot access property with non-string: got ${n.type}`);i=s.value.get(n.value)??s.builtins.get(n.value)}else if(s instanceof F||s instanceof C){if(n instanceof S)i=s.value.at(n.value),s instanceof C&&(i=new C(s.value.at(n.value)));else if(n instanceof C)i=s.builtins.get(n.value);else throw Error(`Cannot access property with non-string/non-number: got ${n.type}`)}else{if(!(n instanceof C))throw Error(`Cannot access property with non-string: got ${n.type}`);i=s.builtins.get(n.value)}if(!(i instanceof z))throw Error(`${s.type} has no property '${n.value}'`);return i}evaluateSet(e,t){if("Identifier"!==e.assignee.type)throw Error(`Invalid LHS inside assignment expression: ${JSON.stringify(e.assignee)}`);let n=e.assignee.value;return t.setVariable(n,this.evaluate(e.value,t)),new L}evaluateIf(e,t){let n=this.evaluate(e.test,t);return this.evaluateBlock(n.__bool__().value?e.body:e.alternate,t)}evaluateFor(e,t){let n=new R(t),i=this.evaluate(e.iterable,n);if(!(i instanceof F))throw Error(`Expected iterable type in for loop: got ${i.type}`);let s="";for(let t=0;t[e,t])))),n.setVariable(e.loopvar.value,i.value[t]);let o=this.evaluateBlock(e.body,n);s+=o.value}return new C(s)}evaluate(e,t){if(void 0===e)return new U;switch(e.type){case"Program":return this.evalProgram(e,t);case"Set":return this.evaluateSet(e,t);case"If":return this.evaluateIf(e,t);case"For":return this.evaluateFor(e,t);case"NumericLiteral":return new S(Number(e.value));case"StringLiteral":return new C(e.value);case"BooleanLiteral":return new O(e.value);case"Identifier":return this.evaluateIdentifier(e,t);case"CallExpression":return this.evaluateCallExpression(e,t);case"MemberExpression":return this.evaluateMemberExpression(e,t);case"UnaryExpression":return this.evaluateUnaryExpression(e,t);case"BinaryExpression":return this.evaluateBinaryExpression(e,t);case"FilterExpression":return this.evaluateFilterExpression(e,t);default:throw SyntaxError(`Unknown node type: ${e.type}`)}}},$=class{parsed;constructor(e){e=e.replace(/%}\s+{%/g,"%}{%");let t=function(e){let t=[],n=0,consumeWhile=t=>{let i="";for(;t(e[n]);){if("\\"===e[n]){if(++n>=e.length)throw SyntaxError("Unexpected end of input");let t=e[n++],s=u.get(t);if(void 0===s)throw SyntaxError(`Unexpected escaped character: ${t}`);i+=s;continue}if(i+=e[n++],n>=e.length)throw SyntaxError("Unexpected end of input")}return i};e:for(;n0){t.push(new o(s,i.Text));continue}}consumeWhile(e=>/\s/.test(e));let c=e[n];if("-"===c||"+"===c){let e=t.at(-1)?.type;if(e===i.Text||void 0===e)throw SyntaxError(`Unexpected character: ${c}`);switch(e){case i.Identifier:case i.NumericLiteral:case i.BooleanLiteral:case i.StringLiteral:case i.CloseParen:case i.CloseSquareBracket:break;default:{++n;let e=consumeWhile(isInteger);t.push(new o(`${c}${e}`,e.length>0?i.NumericLiteral:i.UnaryOperator));continue}}}for(let[i,s]of a){let a=e.slice(n,n+i.length);if(a===i){t.push(new o(i,s)),n+=i.length;continue e}}if("'"===c){++n;let e=consumeWhile(e=>"'"!==e);t.push(new o(e,i.StringLiteral)),++n;continue}if(isInteger(c)){let e=consumeWhile(isInteger);t.push(new o(e,i.NumericLiteral));continue}if(isWord(c)){let e=consumeWhile(isWord),n=Object.hasOwn(s,e)?s[e]:i.Identifier;n===i.In&&t.at(-1)?.type===i.Not?(t.pop(),t.push(new o("not in",i.NotIn))):t.push(new o(e,n));continue}throw SyntaxError(`Unexpected character: ${c}`)}return t}(e);this.parsed=function(e){let t=new f([]),n=0;function expect(t,i){let s=e[n++];if(!s||s.type!==t)throw Error(`Parser Error: ${i}. ${s.type} !== ${t}.`);return s}function is(...t){return n+t.length<=e.length&&t.every((t,i)=>t===e[n+i].type)}function parseLogicalOrExpression(){let t=parseLogicalAndExpression();for(;is(i.Or);){let i=e[n];++n;let s=parseLogicalAndExpression();t=new k(i,t,s)}return t}function parseLogicalAndExpression(){let t=parseLogicalNegationExpression();for(;is(i.And);){let i=e[n];++n;let s=parseLogicalNegationExpression();t=new k(i,t,s)}return t}function parseLogicalNegationExpression(){let t;for(;is(i.Not);){let i=e[n];++n;let s=parseLogicalNegationExpression();t=new I(i,s)}return t??function(){let t=parseAdditiveExpression();for(;is(i.ComparisonBinaryOperator)||is(i.In)||is(i.NotIn);){let i=e[n];++n;let s=parseAdditiveExpression();t=new k(i,t,s)}return t}()}function parseAdditiveExpression(){let t=parseMultiplicativeExpression();for(;is(i.AdditiveBinaryOperator);){let i=e[n];++n;let s=parseMultiplicativeExpression();t=new k(i,t,s)}return t}function parseMultiplicativeExpression(){let t=parseFilterExpression();for(;is(i.MultiplicativeBinaryOperator);){let i=e[n];++n;let s=parseFilterExpression();t=new k(i,t,s)}return t}function parseFilterExpression(){let t=function(){let t=function(){let t=parsePrimaryExpression();for(;is(i.Dot)||is(i.OpenSquareBracket);){let s;let o=e[n];++n;let a=o.type!==i.Dot;if(a)s=function(){let e=[],t=!1;for(;!is(i.CloseSquareBracket);)is(i.Colon)?(e.push(void 0),++n,t=!0):(e.push(parseLogicalOrExpression()),is(i.Colon)&&(++n,t=!0));if(0===e.length)throw SyntaxError("Expected at least one argument for member/slice expression");if(t){if(e.length>3)throw SyntaxError("Expected 0-3 arguments for slice expression");return new T(...e)}return e[0]}(),expect(i.CloseSquareBracket,"Expected closing square bracket");else if("Identifier"!==(s=parsePrimaryExpression()).type)throw SyntaxError("Expected identifier following dot operator");t=new y(t,s,a)}return t}();return is(i.OpenParen)?function parseCallExpression(e){let t=new w(e,function(){expect(i.OpenParen,"Expected opening parenthesis for arguments list");let e=is(i.CloseParen)?[]:function(){let e=[parseLogicalOrExpression()];for(;is(i.Comma);)++n,e.push(parseLogicalOrExpression());return e}();return expect(i.CloseParen,"Expected closing parenthesis for arguments list"),e}());return is(i.OpenParen)&&(t=parseCallExpression(t)),t}(t):t}();for(;is(i.Pipe);){++n;let e=parsePrimaryExpression();if(!(e instanceof b))throw SyntaxError("Expected identifier for the filter");t=new B(t,e)}return t}function parsePrimaryExpression(){let t=e[n];switch(t.type){case i.NumericLiteral:return++n,new x(Number(t.value));case i.StringLiteral:return++n,new E(t.value);case i.BooleanLiteral:return++n,new A("true"===t.value);case i.Identifier:return++n,new b(t.value);case i.OpenParen:{++n;let t=parseLogicalOrExpression();if(e[n].type!==i.CloseParen)throw SyntaxError("Expected closing parenthesis");return++n,t}default:throw SyntaxError(`Unexpected token: ${t.type}`)}}for(;nt!==e[n+i].type)}(i.OpenStatement,i.EndFor);)o.push(parseAny());return new m(t,s,o)}(),expect(i.OpenStatement,"Expected {% token"),expect(i.EndFor,"Expected endfor token"),expect(i.CloseStatement,"Expected %} token");break;default:throw SyntaxError(`Unknown statement type: ${e[n].type}`)}return t}();case i.OpenExpression:return function(){expect(i.OpenExpression,"Expected opening expression token");let e=parseLogicalOrExpression();return expect(i.CloseExpression,"Expected closing expression token"),e}();default:throw SyntaxError(`Unexpected token type: ${e[n].type}`)}}());return t}(t)}render(e){let t=new R;for(let[n,i]of(t.set("false",!1),t.set("true",!0),t.set("raise_exception",e=>{throw Error(e)}),Object.entries(e)))t.set(n,i);let n=new N(t),i=n.run(this.parsed);return i.value}}},6577:function(e,t,n){"use strict";let i;n.d(t,{ONNX:function(){return i},p:function(){return f}});var s,o,a=n(495),u=n(2018),c=n(2601);let f=["wasm"];if(void 0!==c&&c?.release?.name==="node")i=a??(s||(s=n.t(a,2))),f.unshift("cpu");else{i=u??(o||(o=n.t(u,2)));let e="undefined"!=typeof navigator&&/iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent);e&&(i.env.wasm.simd=!1)}},9252:function(e,t,n){"use strict";n.d(t,{z:function(){return AutoConfig}});var i=n(4320);async function loadConfig(e,t){return await (0,i.yM)(e,"config.json",!0,t)}let PretrainedConfig=class PretrainedConfig{constructor(e){this.model_type=null,this.is_encoder_decoder=!1,Object.assign(this,e)}static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:i=null,local_files_only:s=!1,revision:o="main"}={}){let a=n??await loadConfig(e,{progress_callback:t,config:n,cache_dir:i,local_files_only:s,revision:o});return new this(a)}};let AutoConfig=class AutoConfig{static async from_pretrained(...e){return PretrainedConfig.from_pretrained(...e)}}},9721:function(e,t,n){"use strict";n.d(t,{O:function(){return v}});var i=n(8386),s=n(3342),o=n(692),a=n(6577);let{env:u}=a.ONNX,c="2.14.0",f="undefined"!=typeof self&&"caches"in self,p=!isEmpty(i),m=!isEmpty(s),g=p&&m,_=g?s.dirname(s.dirname(o.fileURLToPath("file:///workspaces/transformers.js/examples/semantic-image-search-client/node_modules/@xenova/transformers/src/env.js"))):"./",y=g?s.join(_,"/.cache/"):null,w="/models/",b=g?s.join(_,w):w;u.wasm.wasmPaths=g?s.join(_,"/dist/"):`https://cdn.jsdelivr.net/npm/@xenova/transformers@${c}/dist/`;let v={backends:{onnx:u,tfjs:{}},__dirname:_,version:c,allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!0,localModelPath:b,useFS:p,useBrowserCache:f,useFSCache:p,cacheDir:y,useCustomCache:!1,customCache:null};function isEmpty(e){return 0===Object.keys(e).length}},7582:function(e,t,n){"use strict";let i,s,o;n.d(t,{t25:function(){return a.t2},v3$:function(){return u.v3$},OBj:function(){return g.O},qCb:function(){return p.qC}});var a=n(9191),u=n(5242),c=n(1802),f=n(4320),p=n(4297),m=n(6001),g=n(9721),_=n(8741);let y="undefined"!=typeof self,w=y&&"DedicatedWorkerGlobalScope"===self.constructor.name;if(y)i=(e,t)=>{if(!self.OffscreenCanvas)throw Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(e,t)},o=self.createImageBitmap,s=self.ImageData;else if(_)o=async e=>{let t=await e.metadata(),n=t.channels,{data:i,info:s}=await e.raw().toBuffer({resolveWithObject:!0}),o=new RawImage(new Uint8ClampedArray(i),s.width,s.height,s.channels);return void 0!==n&&n!==s.channels&&o.convert(n),o};else throw Error("Unable to load image processing library.");let b={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},v=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);let RawImage=class RawImage{constructor(e,t,n,i){this.data=e,this.width=t,this.height=n,this.channels=i}get size(){return[this.width,this.height]}static async read(e){if(e instanceof RawImage)return e;if("string"==typeof e||e instanceof URL)return await this.fromURL(e);throw Error(`Unsupported input type: ${typeof e}`)}static async fromURL(e){let t=await (0,f.hn)(e);if(200!==t.status)throw Error(`Unable to read image from "${e}" (${t.status} ${t.statusText})`);let n=await t.blob();return this.fromBlob(n)}static async fromBlob(e){if(y){let t=await o(e),n=i(t.width,t.height).getContext("2d");return n.drawImage(t,0,0),new this(n.getImageData(0,0,t.width,t.height).data,t.width,t.height,4)}{let t=_(await e.arrayBuffer());return await o(t)}}static fromTensor(e,t="CHW"){if(3!==e.dims.length)throw Error(`Tensor should have 3 dimensions, but has ${e.dims.length} dimensions.`);if("CHW"===t)e=e.transpose(1,2,0);else if("HWC"===t);else throw Error(`Unsupported channel format: ${t}`);if(!(e.data instanceof Uint8ClampedArray||e.data instanceof Uint8Array))throw Error(`Unsupported tensor type: ${e.type}`);switch(e.dims[2]){case 1:case 2:case 3:case 4:return new RawImage(e.data,e.dims[1],e.dims[0],e.dims[2]);default:throw Error(`Unsupported number of channels: ${e.dims[2]}`)}}grayscale(){if(1===this.channels)return this;let e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let t=0,n=0;t=0?c=n:p=-n,s>=0?f=s:m=-s,u.drawImage(a,c,f,e,t,p,m,e,t),new RawImage(u.getImageData(0,0,e,t).data,e,t,4).convert(o)}{let i=this.toSharp();if(n>=0&&s>=0)i=i.extract({left:Math.floor(n),top:Math.floor(s),width:e,height:t});else if(n<=0&&s<=0){let o=Math.floor(-s),a=Math.floor(-n);i=i.extend({top:o,left:a,right:e-this.width-a,bottom:t-this.height-o})}else{let o=[0,0],a=0;s<0?(o[0]=Math.floor(-s),o[1]=t-this.height-o[0]):a=Math.floor(s);let u=[0,0],c=0;n<0?(u[0]=Math.floor(-n),u[1]=e-this.width-u[0]):c=Math.floor(n),i=i.extend({top:o[0],bottom:o[1],left:u[0],right:u[1]}).extract({left:c,top:a,width:e,height:t})}return await o(i)}}async toBlob(e="image/png",t=1){if(!y)throw Error("toBlob() is only supported in browser environments.");let n=this.toCanvas();return await n.convertToBlob({type:e,quality:t})}toCanvas(){if(!y)throw Error("toCanvas() is only supported in browser environments.");let e=this.clone().rgba(),t=i(e.width,e.height),n=new s(e.data,e.width,e.height);return t.getContext("2d").putImageData(n,0,0),t}_update(e,t,n,i=null){return this.data=e,this.width=t,this.height=n,null!==i&&(this.channels=i),this}clone(){return new RawImage(this.data.slice(),this.width,this.height,this.channels)}convert(e){if(this.channels===e)return this;switch(e){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(e){if(y){if(w)throw Error("Unable to save an image from a Web Worker.");let t=e.split(".").pop().toLowerCase(),n=v.get(t)??"image/png",i=await this.toBlob(n),s=URL.createObjectURL(i),o=document.createElement("a");o.href=s,o.download=e,o.click(),o.remove()}else if(g.O.useFS){let t=this.toSharp();return await t.toFile(e)}else throw Error("Unable to save the image because filesystem is disabled in this environment.")}toSharp(){if(y)throw Error("toSharp() is only supported in server-side environments.");return _(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}};async function read_audio(e,t){let n;if("undefined"==typeof AudioContext)throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");let i=await (await (0,f.hn)(e)).arrayBuffer(),s=new AudioContext({sampleRate:t});void 0===t&&console.warn(`No sampling rate provided, using default of ${s.sampleRate}Hz.`);let o=await s.decodeAudioData(i);if(2===o.numberOfChannels){let e=Math.sqrt(2),t=o.getChannelData(0),i=o.getChannelData(1);n=new Float32Array(t.length);for(let s=0;s2595*Math.log10(1+e/700),kaldi:e=>1127*Math.log(1+e/700),slaney:(e,t=1e3,n=15,i=27/Math.log(6.4))=>e>=t?n+Math.log(e/t)*i:3*e/200};function hertz_to_mel(e,t="htk"){let n=x[t];if(!n)throw Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return"number"==typeof e?n(e):e.map(e=>n(e))}let E={htk:e=>700*(10**(e/2595)-1),kaldi:e=>700*(Math.exp(e/1127)-1),slaney:(e,t=1e3,n=15,i=Math.log(6.4)/27)=>e>=n?t*Math.exp(i*(e-n)):200*e/3};function linspace(e,t,n){let i=(t-e)/(n-1);return Float64Array.from({length:n},(t,n)=>e+i*n)}function mel_filter_bank(e,t,n,i,s,o=null,a="htk",u=!1){let c;if(null!==o&&"slaney"!==o)throw Error('norm must be one of null or "slaney"');let f=hertz_to_mel(n,a),p=hertz_to_mel(i,a),m=linspace(f,p,t+2),g=function(e,t="htk"){let n=E[t];if(!n)throw Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return"number"==typeof e?n(e):e.map(e=>n(e))}(m,a);if(u){let t=s/(2*e);c=hertz_to_mel(Float64Array.from({length:e},(e,n)=>n*t),a),g=m}else c=linspace(0,Math.floor(s/2),e);let _=function(e,t){let n=Float64Array.from({length:t.length-1},(e,n)=>t[n+1]-t[n]),i=Array.from({length:e.length},()=>Array(t.length));for(let n=0;nArray(e.length));for(let t=0;ts)throw Error(`frame_length (${n}) may not be larger than fft_length (${s})`);if(B!==n)throw Error(`Length of the window (${B}) must equal frame_length (${n})`);if(i<=0)throw Error("hop_length must be greater than zero");if(a){if("reflect"!==u)throw Error(`pad_mode="${u}" not implemented yet.`);let t=Math.floor((s-1)/2)+1;e=function(e,t,n){let i=new e.constructor(e.length+t+n),s=e.length-1;for(let n=0;nI?A&&(S=E):S=z=E);let C=new p.vw(s),O=new Float64Array(s),P=new Float64Array(C.outputBufferSize),F=Array(z);for(let s=0;s=1;--e)O[e]-=m*O[e-1];O[0]*=1-m}for(let e=0;ei)throw Error(`Length of the window (${e}) may not be larger than frame_length (${i})`);return o}function post_process_object_detection(e,t=.5,n=null,i=!1){let s=e.logits,o=e.pred_boxes,[a,u,c]=s.dims;if(null!==n&&n.length!==a)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let f=[];for(let e=0;et&&o.push(e)}else{let e=(0,p.Fp)(s.data)[1];if(e===c-1)continue;o.push(e),n=(0,p.XA)(s.data)}for(let t of o){let i=_[e].data;i=function([e,t,n,i]){return[e-n/2,t-i/2,e+n/2,t+i/2]}(i),null!==a&&(i=i.map((e,t)=>e*a[(t+1)%2])),m.boxes.push(i),m.classes.push(t),m.scores.push(n[t])}}f.push(m)}return f}function validate_audio_inputs(e,t){if(!(e instanceof Float32Array||e instanceof Float64Array))throw Error(`${t} expects input to be a Float32Array or a Float64Array, but got ${e?.constructor?.name??typeof e} instead.If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}let FeatureExtractor=class FeatureExtractor extends c.Ag{constructor(e){super(),this.config=e}};let ImageFeatureExtractor=class ImageFeatureExtractor extends FeatureExtractor{constructor(e){super(e),this.image_mean=this.config.image_mean??this.config.mean,this.image_std=this.config.image_std??this.config.std,this.resample=this.config.resample??2,this.do_rescale=this.config.do_rescale??!0,this.rescale_factor=this.config.rescale_factor??1/255,this.do_normalize=this.config.do_normalize,this.do_resize=this.config.do_resize,this.do_thumbnail=this.config.do_thumbnail,this.size=this.config.size,this.size_divisibility=this.config.size_divisibility??this.config.size_divisor,this.do_center_crop=this.config.do_center_crop,this.crop_size=this.config.crop_size,this.do_convert_rgb=this.config.do_convert_rgb??!0,this.do_crop_margin=this.config.do_crop_margin,this.pad_size=this.config.pad_size,this.do_pad=this.config.do_pad,this.do_pad&&!this.pad_size&&this.size&&void 0!==this.size.width&&void 0!==this.size.height&&(this.pad_size=this.size)}async thumbnail(e,t,n=2){let i=e.height,s=e.width,o=t.height,a=t.width,u=Math.min(i,o),c=Math.min(s,a);return u===i&&c===s?e:(i>s?c=Math.floor(s*u/i):s>i&&(u=Math.floor(i*c/s)),await e.resize(c,u,{resample:n}))}async crop_margin(e,t=200){let n=e.clone().grayscale(),i=(0,p.VV)(n.data)[0],s=(0,p.Fp)(n.data)[0],o=s-i;if(0===o)return e;let a=t/255,u=n.width,c=n.height,f=0,m=0;for(let e=0;ethis.preprocess(e))),i=(0,m.kn)(n.map(e=>e.pixel_values),0);return{pixel_values:i,original_sizes:n.map(e=>e.original_size),reshaped_input_sizes:n.map(e=>e.reshaped_input_size)}}};let SegformerFeatureExtractor=class SegformerFeatureExtractor extends ImageFeatureExtractor{post_process_semantic_segmentation(e,t=null){let n=e.logits,i=n.dims[0];if(null!==t&&t.length!==i)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let s=[];for(let e=0;ef[n]&&(f[n]=t[n],c.data[n]=e)}let p=Array(o.dims[0]),g=c.data;for(let e=0;evoid 0!==e);s.push({segmentation:c,labels:_})}return s}};let BitImageProcessor=class BitImageProcessor extends ImageFeatureExtractor{};let DPTFeatureExtractor=class DPTFeatureExtractor extends ImageFeatureExtractor{};let GLPNFeatureExtractor=class GLPNFeatureExtractor extends ImageFeatureExtractor{};let CLIPFeatureExtractor=class CLIPFeatureExtractor extends ImageFeatureExtractor{};let ChineseCLIPFeatureExtractor=class ChineseCLIPFeatureExtractor extends ImageFeatureExtractor{};let SiglipImageProcessor=class SiglipImageProcessor extends ImageFeatureExtractor{};let ConvNextFeatureExtractor=class ConvNextFeatureExtractor extends ImageFeatureExtractor{constructor(e){super(e),this.crop_pct=this.config.crop_pct??.875}async resize(e){let t=this.size?.shortest_edge;if(void 0===t)throw Error("Size dictionary must contain 'shortest_edge' key.");if(t<384){let n=Math.floor(t/this.crop_pct),[i,s]=this.get_resize_output_image_size(e,{shortest_edge:n});e=await e.resize(i,s,{resample:this.resample}),e=await e.center_crop(t,t)}else e=await e.resize(t,t,{resample:this.resample});return e}};let ConvNextImageProcessor=class ConvNextImageProcessor extends ConvNextFeatureExtractor{};let ViTFeatureExtractor=class ViTFeatureExtractor extends ImageFeatureExtractor{};let ViTImageProcessor=class ViTImageProcessor extends ImageFeatureExtractor{};let MobileViTFeatureExtractor=class MobileViTFeatureExtractor extends ImageFeatureExtractor{};let OwlViTFeatureExtractor=class OwlViTFeatureExtractor extends ImageFeatureExtractor{post_process_object_detection(...e){return post_process_object_detection(...e)}};let DeiTFeatureExtractor=class DeiTFeatureExtractor extends ImageFeatureExtractor{};let BeitFeatureExtractor=class BeitFeatureExtractor extends ImageFeatureExtractor{};let DonutFeatureExtractor=class DonutFeatureExtractor extends ImageFeatureExtractor{pad_image(e,t,n,i={}){let[s,o,a]=t,u=this.image_mean;Array.isArray(this.image_mean)||(u=Array(a).fill(u));let c=this.image_std;Array.isArray(c)||(c=Array(a).fill(u));let f=u.map((e,t)=>-e/this.image_std[t]);return super.pad_image(e,t,n,{center:!0,constant_values:f,...i})}};let NougatImageProcessor=class NougatImageProcessor extends DonutFeatureExtractor{};let DetrFeatureExtractor=class DetrFeatureExtractor extends ImageFeatureExtractor{async _call(e){let t=await super._call(e),n=[t.pixel_values.dims[0],64,64],i=new m.es("int64",new BigInt64Array(n.reduce((e,t)=>e*t)).fill(1n),n);return{...t,pixel_mask:i}}post_process_object_detection(...e){return post_process_object_detection(...e)}remove_low_and_no_objects(e,t,n,i){let s=[],o=[],a=[];for(let u=0;un&&(s.push(f),o.push(g),a.push(m))}return[s,o,a]}check_segment_validity(e,t,n,i=.5,s=.8){let o=[],a=0,u=0;for(let s=0;s=i&&++u;let c=a>0&&u>0;return c&&(c=a/u>s),[c,o]}compute_segments(e,t,n,i,s,o=null,a=null){let[u,c]=a??e[0].dims,f=new m.es("int32",new Int32Array(u*c),[u,c]),p=[];if(null!==a)for(let t=0;t_[t]&&(g[t]=n,_[t]=e[n].data[t])}let y=0;for(let o=0;oe!==t.dims[n]))throw Error(`The first ${n.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new m.es("int64",e.flat(1/0).map(BigInt),n)}async _call(e,t=null,n=null){let i=await super._call(e);if(t&&(i.input_points=this.reshape_input_points(t,i.original_sizes,i.reshaped_input_sizes)),n){if(!i.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");i.input_labels=this.add_input_labels(n,i.input_points)}return i}post_process_masks(e,t,n,{mask_threshold:i=0,binarize:s=!0,pad_size:o=null}={}){let a=[];o=o??this.pad_size;let u=[o.height,o.width];for(let o=0;oi&&(e[t]=1);n=new m.es("bool",e,n.dims)}g.push(n)}a.push((0,m.kn)(g))}return a}};let Swin2SRImageProcessor=class Swin2SRImageProcessor extends ImageFeatureExtractor{pad_image(e,t,n,i={}){let[s,o,a]=t;return super.pad_image(e,t,{width:s+(n-s%n)%n,height:o+(n-o%n)%n},{mode:"symmetric",center:!1,constant_values:-1,...i})}};let VitMatteImageProcessor=class VitMatteImageProcessor extends ImageFeatureExtractor{async _call(e,t){Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);let n=await Promise.all(e.map(e=>this.preprocess(e))),i=await Promise.all(t.map(e=>this.preprocess(e,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0}))),s=(0,m.kn)(n.map((e,t)=>(0,m.d3)([e.pixel_values,i[t].pixel_values],0)),0);return{pixel_values:s,original_sizes:n.map(e=>e.original_size),reshaped_input_sizes:n.map(e=>e.reshaped_input_size)}}};let WhisperFeatureExtractor=class WhisperFeatureExtractor extends FeatureExtractor{constructor(e){super(e),this.config.mel_filters??=mel_filter_bank(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney"),this.window=window_function(this.config.n_fft,"hann")}_extract_fbank_features(e){let{data:t,dims:n}=spectrogram(e,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:this.config.nb_max_frames}),i=(0,p.Fp)(t)[0];for(let e=0;ethis.config.n_samples?(console.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),t=e.slice(0,this.config.n_samples)):(t=new Float32Array(this.config.n_samples)).set(e);let{data:n,dims:i}=this._extract_fbank_features(t);return{input_features:new m.es("float32",n,[1,...i])}}};let Wav2Vec2FeatureExtractor=class Wav2Vec2FeatureExtractor extends FeatureExtractor{_zero_mean_unit_var_norm(e){let t=e.reduce((e,t)=>e+t,0),n=t/e.length,i=e.reduce((e,t)=>e+(t-n)**2,0)/e.length;return e.map(e=>(e-n)/Math.sqrt(i+1e-7))}async _call(e){validate_audio_inputs(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let t=e;this.config.do_normalize&&(t=this._zero_mean_unit_var_norm(t));let n=[1,t.length];return{input_values:new m.es("float32",t,n),attention_mask:new m.es("int64",new BigInt64Array(t.length).fill(1n),n)}}};let ASTFeatureExtractor=class ASTFeatureExtractor extends FeatureExtractor{constructor(e){super(e);let t=this.config.sampling_rate,n=mel_filter_bank(256,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);for(let e=0;e0){if("rand_trunc"===n){o=!0;let n=Math.floor(Math.random()*(a+1));e=e.subarray(n,n+t),(s=this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)).dims=[1,...s.dims]}else throw Error(`Truncation strategy "${n}" not implemented`)}else{if(a<0){let n=new Float64Array(t);if(n.set(e),"repeat"===i)for(let i=e.length;iRawImage.read(e)))}async function prepareAudios(e,t){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(e=>"string"==typeof e||e instanceof URL?read_audio(e,t):e instanceof Float64Array?new Float32Array(e):e))}function get_bounding_box(e,t){t&&(e=e.map(e=>0|e));let[n,i,s,o]=e;return{xmin:n,ymin:i,xmax:s,ymax:o}}let Pipeline=class Pipeline extends c.Ag{constructor({task:e,model:t,tokenizer:n=null,processor:i=null}){super(),this.task=e,this.model=t,this.tokenizer=n,this.processor=i}async dispose(){await this.model.dispose()}};let Text2TextGenerationPipeline=class Text2TextGenerationPipeline extends Pipeline{_key="generated_text";constructor(e){super(e)}async _call(e,t={}){let n;Array.isArray(e)||(e=[e]),this.model.config.prefix&&(e=e.map(e=>this.model.config.prefix+e));let i=this.model.config.task_specific_params;i&&i[this.task]&&i[this.task].prefix&&(e=e.map(e=>i[this.task].prefix+e));let s=this.tokenizer,o={padding:!0,truncation:!0};n=this instanceof TranslationPipeline&&"_build_translation_inputs"in s?s._build_translation_inputs(e,o,t).input_ids:s(e,o).input_ids;let a=await this.model.generate(n,t);return s.batch_decode(a,{skip_special_tokens:!0}).map(e=>({[this._key]:e}))}};let TranslationPipeline=class TranslationPipeline extends Text2TextGenerationPipeline{_key="translation_text";constructor(e){super(e)}};Object.freeze({"text-classification":{tokenizer:a.t2,pipeline:class extends Pipeline{constructor(e){super(e)}async _call(e,{topk:t=1}={}){let n=this.tokenizer(e,{padding:!0,truncation:!0}),i=await this.model(n),s="multi_label_classification"===this.model.config.problem_type?e=>e.sigmoid().data:e=>(0,p.XA)(e.data),o=this.model.config.id2label,a=[];for(let e of i.logits){let n=s(e),i=(0,p.em)(n,t),u=i.map(e=>({label:o[e[0]],score:e[1]}));1===t?a.push(...u):a.push(u)}return Array.isArray(e)||1===t?a:a[0]}},model:u.o$X,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:a.t2,pipeline:class extends Pipeline{constructor(e){super(e)}async _call(e,{ignore_labels:t=["O"]}={}){let n=Array.isArray(e),i=this.tokenizer(n?e:[e],{padding:!0,truncation:!0}),s=await this.model(i),o=s.logits,a=this.model.config.id2label,u=[];for(let e=0;e[e,t]).filter(e=>e[1]>a),f=Array.from((0,p.XA)(s.end_logits[e].data)).map((e,t)=>[e,t]).filter(e=>e[1]>a),m=(0,c.O7)(u,f).filter(e=>e[0][1]<=e[1][1]).map(e=>[e[0][1],e[1][1],e[0][0]*e[1][0]]).sort((e,t)=>t[2]-e[2]);for(let e=0;e{let t=[...o];return t[a]=e[0],{score:e[1],token:e[0],token_str:this.tokenizer.model.vocab[e[0]],sequence:this.tokenizer.decode(t,{skip_special_tokens:!0})}}))}return Array.isArray(e)?s:s[0]}},model:u.t78,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:a.t2,pipeline:class extends Text2TextGenerationPipeline{_key="summary_text";constructor(e){super(e)}},model:u.Kf0,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:a.t2,pipeline:TranslationPipeline,model:u.Kf0,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:a.t2,pipeline:Text2TextGenerationPipeline,model:u.Kf0,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:a.t2,pipeline:class extends Pipeline{constructor(e){super(e)}async _call(e,t={}){let n=Array.isArray(e);n||(e=[e]);let i=t.add_special_tokens??!1;this.tokenizer.padding_side="left";let{input_ids:s,attention_mask:o}=this.tokenizer(e,{add_special_tokens:i,padding:!0,truncation:!0}),a=await this.model.generate(s,t,null,{inputs_attention_mask:o}),u=this.tokenizer.batch_decode(a,{skip_special_tokens:!0}),c=Array.from({length:e.length},e=>[]);for(let t=0;t[e.toLowerCase(),t])),this.entailment_id=this.label2id.entailment,void 0===this.entailment_id&&(console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,void 0===this.contradiction_id&&(console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(e,t,{hypothesis_template:n="This example is {}.",multi_label:i=!1}={}){let s=Array.isArray(e);s||(e=[e]),Array.isArray(t)||(t=[t]);let o=t.map(e=>n.replace("{}",e)),a=i||1===t.length,u=[];for(let n of e){let e=[];for(let t of o){let i=this.tokenizer(n,{text_pair:t,padding:!0,truncation:!0}),s=await this.model(i);a?e.push([s.logits.data[this.contradiction_id],s.logits.data[this.entailment_id]]):e.push(s.logits.data[this.entailment_id])}let i=a?e.map(e=>(0,p.XA)(e)[1]):(0,p.XA)(e),s=i.map((e,t)=>[e,t]).sort((e,t)=>t[0]-e[0]);u.push({sequence:n,labels:s.map(e=>t[e[1]]),scores:s.map(e=>e[0])})}return s?u:u[0]}},model:u.o$X,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:class extends Pipeline{constructor(e){super(e)}async _call(e,{topk:t=null}={}){let n=!Array.isArray(e),i=this.processor.feature_extractor.config.sampling_rate,s=await prepareAudios(e,i),o=this.model.config.id2label,a=[];for(let e of s){let n=await this.processor(e),i=await this.model(n),s=i.logits[0],u=(0,p.em)((0,p.XA)(s.data),t),c=u.map(e=>({label:o[e[0]],score:e[1]}));1===t?a.push(...c):a.push(c)}return n&&1!==t?a[0]:a}},model:u.K2m,processor:AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:a.t2,pipeline:class extends Pipeline{constructor(e){super(e)}async _call(e,t,{hypothesis_template:n="This is a sound of {}."}={}){let i=!Array.isArray(e);i&&(e=[e]);let s=t.map(e=>n.replace("{}",e)),o=this.tokenizer(s,{padding:!0,truncation:!0}),a=this.processor.feature_extractor.config.sampling_rate,u=await prepareAudios(e,a),c=[];for(let e of u){let n=await this.processor(e),i=await this.model({...o,...n}),s=(0,p.XA)(i.logits_per_audio.data);c.push([...s].map((e,n)=>({score:e,label:t[n]})))}return i?c[0]:c}},model:u.$Sz,processor:AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:a.t2,pipeline:class extends Pipeline{constructor(e){super(e)}async _call(e,t={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(e,t);case"wav2vec2":case"hubert":return this._call_wav2vec2(e,t);default:throw Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(e,t={}){t.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),t.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');let n=!Array.isArray(e);n&&(e=[e]);let i=this.processor.feature_extractor.config.sampling_rate,s=await prepareAudios(e,i),o=[];for(let e of s){let t=await this.processor(e),n=await this.model(t),i=n.logits[0],s=[];for(let e of i)s.push((0,p.Fp)(e.data)[1]);let a=this.tokenizer.decode(s);o.push({text:a})}return n?o[0]:o}async _call_whisper(e,t={}){let n=t.return_timestamps??!1,i=t.chunk_length_s??0,s=t.chunk_callback??null,o=t.force_full_sequences??!1,a=t.stride_length_s??null;"word"===n&&(t.return_token_timestamps=!0);let u=(0,c.Sw)(t,"language",null),f=(0,c.Sw)(t,"task",null);if(u||f||n){if(t.forced_decoder_ids)throw Error("Cannot specify `language`/`task`/`return_timestamps` and `forced_decoder_ids` at the same time.");let e=this.tokenizer.get_decoder_prompt_ids({language:u,task:f,no_timestamps:!n});e.length>0&&(t.forced_decoder_ids=e)}let m=!Array.isArray(e);m&&(e=[e]);let g=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,_=this.processor.feature_extractor.config.hop_length,y=this.processor.feature_extractor.config.sampling_rate,w=await prepareAudios(e,y),b=[];for(let e of w){let u=[];if(i>0){if(null===a)a=i/6;else if(i<=a)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");let t=y*i,n=y*a,s=t-2*n,o=0;for(;o=e.length;u.push({stride:[i.length,c?0:n,f?0:n],input_features:a.input_features,is_last:f}),o+=s}}else u=[{stride:[e.length,0,0],input_features:(await this.processor(e)).input_features,is_last:!0}];for(let e of u){t.num_frames=Math.floor(e.stride[0]/_);let i=await this.model.generate(e.input_features,t);"word"===n?(e.tokens=i.sequences[0],e.token_timestamps=i.token_timestamps.tolist()[0].map(e=>(0,p.NM)(e,2))):e.tokens=i[0],e.stride=e.stride.map(e=>e/y),null!==s&&s(e)}let[c,f]=this.tokenizer._decode_asr(u,{time_precision:g,return_timestamps:n,force_full_sequences:o});b.push({text:c,...f})}return m?b[0]:b}},model:[u.hZO,u.ENH],processor:AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:a.t2,pipeline:class extends Pipeline{DEFAULT_VOCODER_ID="Xenova/speecht5_hifigan";constructor(e){super(e),this.vocoder=e.vocoder??null}async _call(e,{speaker_embeddings:t=null}={}){return this.processor?this._call_text_to_spectrogram(e,{speaker_embeddings:t}):this._call_text_to_waveform(e)}async _call_text_to_waveform(e){let t=this.tokenizer(e,{padding:!0,truncation:!0}),{waveform:n}=await this.model(t),i=this.model.config.sampling_rate;return{audio:n.data,sampling_rate:i}}async _call_text_to_spectrogram(e,{speaker_embeddings:t}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await u.$Sz.from_pretrained(this.DEFAULT_VOCODER_ID,{quantized:!1})),("string"==typeof t||t instanceof URL)&&(t=new Float32Array(await (await fetch(t)).arrayBuffer())),t instanceof Float32Array)t=new m.es("float32",t,[1,t.length]);else if(!(t instanceof m.es))throw Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");let{input_ids:n}=this.tokenizer(e,{padding:!0,truncation:!0}),{waveform:i}=await this.model.generate_speech(n,t,{vocoder:this.vocoder}),s=this.processor.feature_extractor.config.sampling_rate;return{audio:i.data,sampling_rate:s}}},model:[u.z6E,u.lbf],processor:[AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:a.t2,pipeline:class extends Pipeline{constructor(e){super(e)}async _call(e,t={}){let n=Array.isArray(e),i=await prepareImages(e),{pixel_values:s}=await this.processor(i),o=[];for(let e of s){e.dims=[1,...e.dims];let n=await this.model.generate(e,t),i=this.tokenizer.batch_decode(n,{skip_special_tokens:!0}).map(e=>({generated_text:e.trim()}));o.push(i)}return n?o:o[0]}},model:u.tLj,processor:AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:class extends Pipeline{constructor(e){super(e)}async _call(e,{topk:t=1}={}){let n=Array.isArray(e),i=await prepareImages(e),{pixel_values:s}=await this.processor(i),o=await this.model({pixel_values:s}),a=this.model.config.id2label,u=[];for(let e of o.logits){let n=(0,p.em)((0,p.XA)(e.data),t),i=n.map(e=>({label:a[e[0]],score:e[1]}));1===t?u.push(...i):u.push(i)}return n||1===t?u:u[0]}},model:u.En$,processor:AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:class extends Pipeline{constructor(e){super(e),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(e,{threshold:t=.5,mask_threshold:n=.5,overlap_mask_area_threshold:i=.8,label_ids_to_fuse:s=null,target_sizes:o=null,subtask:a=null}={}){let u=Array.isArray(e);if(u&&1!==e.length)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");let c=await prepareImages(e),f=c.map(e=>[e.height,e.width]),{pixel_values:p,pixel_mask:m}=await this.processor(c),g=await this.model({pixel_values:p,pixel_mask:m}),_=null;if(null!==a)_=this.subtasks_mapping[a];else for(let[e,t]of Object.entries(this.subtasks_mapping))if(t in this.processor.feature_extractor){_=this.processor.feature_extractor[t].bind(this.processor.feature_extractor),a=e;break}let y=this.model.config.id2label,w=[];if("panoptic"===a||"instance"===a){let e=_(g,t,n,i,s,o??f)[0],a=e.segmentation;for(let t of e.segments_info){let e=new Uint8ClampedArray(a.data.length);for(let n=0;nn.replace("{}",e)),a=this.tokenizer(o,{padding:"siglip"!==this.model.config.model_type||"max_length",truncation:!0}),{pixel_values:u}=await this.processor(s),c=await this.model({...a,pixel_values:u}),f="siglip"===this.model.config.model_type?e=>e.sigmoid().data:e=>(0,p.XA)(e.data),m=[];for(let e of c.logits_per_image){let n=f(e),i=[...n].map((e,n)=>({score:e,label:t[n]}));i.sort((e,t)=>t.score-e.score),m.push(i)}return i?m:m[0]}},model:u.$Sz,processor:AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:class extends Pipeline{constructor(e){super(e)}async _call(e,{threshold:t=.9,percentage:n=!1}={}){let i=Array.isArray(e);if(i&&1!==e.length)throw Error("Object detection pipeline currently only supports a batch size of 1.");let s=await prepareImages(e),o=n?null:s.map(e=>[e.height,e.width]),{pixel_values:a,pixel_mask:u}=await this.processor(s),c=await this.model({pixel_values:a,pixel_mask:u}),f=this.processor.feature_extractor.post_process_object_detection(c,t,o),p=this.model.config.id2label,m=f.map(e=>e.boxes.map((t,i)=>({score:e.scores[i],label:p[e.classes[i]],box:get_bounding_box(t,!n)})));return i?m:m[0]}},model:u.Zn,processor:AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:a.t2,pipeline:class extends Pipeline{constructor(e){super(e)}async _call(e,t,{threshold:n=.1,topk:i=null,percentage:s=!1}={}){let o=Array.isArray(e),a=await prepareImages(e),u=this.tokenizer(t,{padding:!0,truncation:!0}),c=await this.processor(a),f=[];for(let e=0;e({score:_.scores[n],label:t[_.classes[n]],box:get_bounding_box(e,!s)})).sort((e,t)=>t.score-e.score);null!==i&&(y=y.slice(0,i)),f.push(y)}return o?f:f[0]}},model:u.LdW,processor:AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:a.t2,pipeline:class extends Pipeline{constructor(e){super(e)}async _call(e,t,n={}){let i=(await prepareImages(e))[0],{pixel_values:s}=await this.processor(i),o=`${t}`,a=this.tokenizer(o,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,u=await this.model.generate(s,{...n,decoder_input_ids:a,max_length:this.model.config.decoder.max_position_embeddings}),c=this.tokenizer.batch_decode(u)[0],f=c.match(/(.*?)<\/s_answer>/),p=null;return f&&f.length>=2&&(p=f[1].trim()),[{answer:p}]}},model:u.DcG,processor:AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:class extends Pipeline{constructor(e){super(e)}async _call(e){let t=await prepareImages(e),n=await this.processor(t),i=await this.model(n),s=[];for(let e of i.reconstruction){let t=e.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");s.push(RawImage.fromTensor(t))}return s.length>1?s:s[0]}},model:u.S2d,processor:AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:class extends Pipeline{constructor(e){super(e)}async _call(e){let t=await prepareImages(e),n=await this.processor(t),{predicted_depth:i}=await this.model(n),s=[];for(let e=0;e1?s:s[0]}},model:u.hY6,processor:AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:a.t2,pipeline:class extends Pipeline{constructor(e){super(e)}async _call(e,{pooling:t="none",normalize:n=!1}={}){let i=this.tokenizer(e,{padding:!0,truncation:!0}),s=await this.model(i),o=s.last_hidden_state??s.logits;if("none"===t);else if("mean"===t)o=(0,m.v6)(o,i.attention_mask);else if("cls"===t)o=o.slice(null,0);else throw Error(`Pooling method '${t}' not supported.`);return n&&(o=o.normalize(2,-1)),o}},model:u.$Sz,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"}}),Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"}),n(9252)},1802:function(e,t,n){"use strict";function dispatchCallback(e,t){e&&e(t)}function reverseDictionary(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e]))}function escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}n.d(t,{$2:function(){return reverseDictionary},Ag:function(){return i},Gg:function(){return exists},O7:function(){return product},Sw:function(){return pop},T2:function(){return dispatchCallback},Wy:function(){return isIntegralNumber},eG:function(){return mergeArrays},fU:function(){return isTypedArray},hr:function(){return escapeRegExp},hs:function(){return calculateReflectOffset},jg:function(){return calculateDimensions}});let i=class{constructor(){let closure=function(...e){return closure._call(...e)};return Object.setPrototypeOf(closure,new.target.prototype)}_call(...e){throw Error("Must implement _call method in subclass")}};function isTypedArray(e){return e?.prototype?.__proto__?.constructor?.name==="TypedArray"}function isIntegralNumber(e){return Number.isInteger(e)||"bigint"==typeof e}function exists(e){return null!=e}function calculateDimensions(e){let t=[],n=e;for(;Array.isArray(n);)t.push(n.length),n=n[0];return t}function pop(e,t,n){let i=e[t];if(void 0!==i)return delete e[t],i;if(void 0===n)throw Error(`Key ${t} does not exist in object.`);return n}function mergeArrays(...e){return Array.prototype.concat.apply([],e)}function product(...e){return e.reduce((e,t)=>e.flatMap(e=>t.map(t=>[e,t])))}function calculateReflectOffset(e,t){return Math.abs((e+t)%(2*t)-t)}},6106:function(e,t,n){"use strict";n.d(t,{GA:function(){return CharTrie},Z3:function(){return PriorityQueue},pQ:function(){return TokenLattice}});let PriorityQueue=class PriorityQueue{constructor(e=(e,t)=>e>t){this._heap=[],this._comparator=e}get size(){return this._heap.length}isEmpty(){return 0===this.size}peek(){return this._heap[0]}push(...e){return this.extend(e)}extend(e){for(let t of e)this._heap.push(t),this._siftUp();return this.size}pop(){let e=this.peek(),t=this.size-1;return t>0&&this._swap(0,t),this._heap.pop(),this._siftDown(),e}replace(e){let t=this.peek();return this._heap[0]=e,this._siftDown(),t}_parent(e){return(e+1>>>1)-1}_left(e){return(e<<1)+1}_right(e){return e+1<<1}_greater(e,t){return this._comparator(this._heap[e],this._heap[t])}_swap(e,t){let n=this._heap[e];this._heap[e]=this._heap[t],this._heap[t]=n}_siftUp(){let e=this.size-1;for(;e>0&&this._greater(e,this._parent(e));)this._swap(e,this._parent(e)),e=this._parent(e)}_siftDown(){let e=0;for(;this._left(e)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);let i=new TokenLatticeNode(this.bosTokenId,0,0,0,0),s=new TokenLatticeNode(this.eosTokenId,1,this.len,0,0);this.nodes.push(i.clone()),this.nodes.push(s.clone()),this.beginNodes[this.len].push(s),this.endNodes[0].push(i)}insert(e,t,n,i){let s=this.nodes.length,o=new TokenLatticeNode(i,s,e,t,n);this.beginNodes[e].push(o),this.endNodes[e+t].push(o),this.nodes.push(o)}viterbi(){let e=this.len,t=0;for(;t<=e;){if(0==this.beginNodes[t].length)return[];for(let e of this.beginNodes[t]){e.prev=null;let n=0,i=null;for(let s of this.endNodes[t]){let t=s.backtraceScore+e.score;(null===i||t>n)&&(i=s.clone(),n=t)}if(null===i)return[];e.prev=i,e.backtraceScore=n}++t}let n=[],i=this.beginNodes[e][0],s=i.prev;if(null===s)return[];let o=s.clone();for(;null!==o.prev;){n.push(o.clone());let e=o.clone();o=e.prev.clone()}return n.reverse(),n}piece(e){return this.sentence.slice(e.pos,e.pos+e.length)}tokens(){let e=this.viterbi();return e.map(e=>this.piece(e))}tokenIds(){let e=this.viterbi();return e.map(e=>e.tokenId)}};let TokenLatticeNode=class TokenLatticeNode{constructor(e,t,n,i,s){this.tokenId=e,this.nodeId=t,this.pos=n,this.length=i,this.score=s,this.prev=null,this.backtraceScore=0}clone(){let e=new TokenLatticeNode(this.tokenId,this.nodeId,this.pos,this.length,this.score);return e.prev=this.prev,e.backtraceScore=this.backtraceScore,e}}},2013:function(e,t,n){"use strict";n.d(t,{AE:function(){return NoBadWordsLogitsProcessor},C9:function(){return ForcedBOSTokenLogitsProcessor},CJ:function(){return MinNewTokensLengthLogitsProcessor},E:function(){return ForceTokensLogitsProcessor},GU:function(){return SuppressTokensAtBeginLogitsProcessor},Jj:function(){return RepetitionPenaltyLogitsProcessor},Jm:function(){return LogitsProcessorList},Pg:function(){return WhisperTimeStampLogitsProcessor},Z4:function(){return Sampler},aP:function(){return o},dZ:function(){return ForcedEOSTokenLogitsProcessor},ez:function(){return MinLengthLogitsProcessor},jF:function(){return NoRepeatNGramLogitsProcessor}}),n(6001);var i=n(1802),s=n(4297);let LogitsProcessorList=class LogitsProcessorList extends i.Ag{constructor(){super(),this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,t){for(let n of t)this.processors.forEach(t=>t(e,n))}[Symbol.iterator](){return this.processors.values()}};let LogitsProcessor=class LogitsProcessor extends i.Ag{_call(e,t){throw Error("`_call` should be implemented in a subclass")}};let ForceTokensLogitsProcessor=class ForceTokensLogitsProcessor extends LogitsProcessor{constructor(e){super(),this.force_token_map=Object.fromEntries(e??[])}_call(e,t){let n=this.force_token_map[e.length];return(0,i.Gg)(n)&&(t.data.fill(-1/0),t.data[n]=0),t}};let ForcedBOSTokenLogitsProcessor=class ForcedBOSTokenLogitsProcessor extends LogitsProcessor{constructor(e){super(),this.bos_token_id=e}_call(e,t){return 1===e.length&&(t.data.fill(-1/0),t.data[this.bos_token_id]=0),t}};let ForcedEOSTokenLogitsProcessor=class ForcedEOSTokenLogitsProcessor extends LogitsProcessor{constructor(e,t){super(),this.max_length=e,this.forced_eos_token_id=t}_call(e,t){}};let SuppressTokensAtBeginLogitsProcessor=class SuppressTokensAtBeginLogitsProcessor extends LogitsProcessor{constructor(e,t){super(),this.begin_suppress_tokens=e,this.begin_index=t}_call(e,t){if(e.length===this.begin_index)for(let e of this.begin_suppress_tokens)t.data[e]=-1/0;return t}};let WhisperTimeStampLogitsProcessor=class WhisperTimeStampLogitsProcessor extends LogitsProcessor{constructor(e){super(),this.eos_token_id=e.eos_token_id,this.no_timestamps_token_id=e.no_timestamps_token_id,this.timestamp_begin=this.no_timestamps_token_id+1,this.begin_index=(e.forced_decoder_ids||[]).length+2,e.forced_decoder_ids.slice(-1)[0][1]===this.no_timestamps_token_id&&(this.begin_index-=1),this.max_initial_timestamp_index=e.max_initial_timestamp_index}_call(e,t){let n=t.data;if(n[this.no_timestamps_token_id]=-1/0,e.length===this.begin_index-1)return n.fill(-1/0),n[this.timestamp_begin]=0,t;let i=e.slice(this.begin_index),o=i.length>=1&&i[i.length-1]>=this.timestamp_begin,a=i.length<2||i[i.length-2]>=this.timestamp_begin;if(o&&(a?n.subarray(this.timestamp_begin).fill(-1/0):n.subarray(0,this.eos_token_id).fill(-1/0)),e.length===this.begin_index&&null!==this.max_initial_timestamp_index){let e=this.timestamp_begin+this.max_initial_timestamp_index;n.subarray(e+1).fill(-1/0)}let u=(0,s.CI)(n),c=Math.log(u.subarray(this.timestamp_begin).map(Math.exp).reduce((e,t)=>e+t)),f=(0,s.Fp)(u.subarray(0,this.timestamp_begin))[0];return c>f&&n.subarray(0,this.timestamp_begin).fill(-1/0),t}};let NoRepeatNGramLogitsProcessor=class NoRepeatNGramLogitsProcessor extends LogitsProcessor{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){let t=e.length,n=[];for(let i=0;i0&&(i=i.map(e=>e/this.generation_config.temperature)),i}randomSelect(e){let t=Math.random()*e.reduce((e,t)=>e+t,0);for(let n=0;n1)return new BeamSearchSampler(e);if(e.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${e.num_return_sequences}.`);return new GreedySampler(e)}};let GreedySampler=class GreedySampler extends Sampler{sample(e,t=-1){let n=this.getLogits(e,t);return[[(0,s.Fp)(n)[1],0]]}};let MultinomialSampler=class MultinomialSampler extends Sampler{sample(e,t=-1){let n=e.dims.at(-1);this.generation_config.top_k>0&&(n=Math.min(this.generation_config.top_k,n));let i=this.getLogits(e,t),o=(0,s.em)(i,n),a=(0,s.XA)(o.map(e=>e[1]));return Array.from({length:this.generation_config.num_beams},()=>{let e=this.randomSelect(a);return[o[e][0],Math.log(a[e])]})}};let BeamSearchSampler=class BeamSearchSampler extends Sampler{sample(e,t=-1){let n=e.dims.at(-1);this.generation_config.top_k>0&&(n=Math.min(this.generation_config.top_k,n));let i=this.getLogits(e,t),o=(0,s.em)(i,n),a=(0,s.XA)(o.map(e=>e[1]));return Array.from({length:this.generation_config.num_beams},(e,t)=>[o[t][0],Math.log(a[t])])}}},4320:function(e,t,n){"use strict";n.d(t,{hn:function(){return getFile},st:function(){return getModelFile},yM:function(){return getModelJSON}});var i=n(7147),s=n(1418),o=n(319),a=n(9721),u=n(1802),c=n(2601),f=n(7133).lW;globalThis.ReadableStream||(globalThis.ReadableStream=o.ReadableStream);let FileResponse=class FileResponse{_CONTENT_TYPE_MAP={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"};constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=i.existsSync(e),this.exists){this.status=200,this.statusText="OK";let t=i.statSync(e);this.headers.set("content-length",t.size.toString()),this.updateContentType();let n=this;this.body=new ReadableStream({start(e){n.arrayBuffer().then(t=>{e.enqueue(new Uint8Array(t)),e.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){let e=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",this._CONTENT_TYPE_MAP[e]??"application/octet-stream")}clone(){let e=new FileResponse(this.filePath);return e.exists=this.exists,e.status=this.status,e.statusText=this.statusText,e.headers=new Headers(this.headers),e}async arrayBuffer(){let e=await i.promises.readFile(this.filePath);return e.buffer}async blob(){let e=await i.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){let e=await i.promises.readFile(this.filePath,"utf8");return e}async json(){return JSON.parse(await this.text())}};function isValidHttpUrl(e,t=null){let n;try{n=new URL(e)}catch(e){return!1}return(!t||!!t.includes(n.hostname))&&("http:"===n.protocol||"https:"===n.protocol)}async function getFile(e){if(a.O.useFS&&!isValidHttpUrl(e))return new FileResponse(e);if(void 0===c||c?.release?.name!=="node")return fetch(e);{let t=!!c.env?.TESTING_REMOTELY,n=a.O.version,i=new Headers;i.set("User-Agent",`transformers.js/${n}; is_ci/${t};`);let s=isValidHttpUrl(e,["huggingface.co","hf.co"]);if(s){let e=c.env?.HF_TOKEN??c.env?.HF_ACCESS_TOKEN;e&&i.set("Authorization",`Bearer ${e}`)}return fetch(e,{headers:i})}}let p={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"};let FileCache=class FileCache{constructor(e){this.path=e}async match(e){let t=s.join(this.path,e),n=new FileResponse(t);return n.exists?n:void 0}async put(e,t){let n=f.from(await t.arrayBuffer()),o=s.join(this.path,e);try{await i.promises.mkdir(s.dirname(o),{recursive:!0}),await i.promises.writeFile(o,n)}catch(e){console.warn("An error occurred while writing the file to cache:",e)}}};async function tryCache(e,...t){for(let n of t)try{let t=await e.match(n);if(t)return t}catch(e){continue}}async function getModelFile(e,t,n=!0,i={}){let s,o,c,f;if(!a.O.allowLocalModels){if(i.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!a.O.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}if((0,u.T2)(i.progress_callback,{status:"initiate",name:e,file:t}),!s&&a.O.useBrowserCache){if("undefined"==typeof caches)throw Error("Browser cache is not available in this environment.");try{s=await caches.open("transformers-cache")}catch(e){console.warn("An error occurred while opening the browser cache:",e)}}if(!s&&a.O.useFSCache&&(s=new FileCache(i.cache_dir??a.O.cacheDir)),!s&&a.O.useCustomCache){if(!a.O.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!a.O.customCache.match||!a.O.customCache.put)throw Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");s=a.O.customCache}let m=i.revision??"main",g=pathJoin(e,t),_=pathJoin(a.O.localModelPath,g),y=pathJoin(a.O.remoteHost,a.O.remotePathTemplate.replaceAll("{model}",e).replaceAll("{revision}",encodeURIComponent(m)),t),w="main"===m?g:pathJoin(e,m,t),b=s instanceof FileCache?w:y,v=!1;s&&(c=await tryCache(s,_,b));let x=void 0!==c;if(void 0===c){if(a.O.allowLocalModels){let e=isValidHttpUrl(g);if(e){if(i.local_files_only)throw Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${g}.`);if(!a.O.allowRemoteModels)throw Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${g}.`)}else try{c=await getFile(_),o=_}catch(e){console.warn(`Unable to load from local path "${_}": "${e}"`)}}if(void 0===c||404===c.status){if(i.local_files_only||!a.O.allowRemoteModels){if(!n)return null;throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${_}".`)}if(200!==(c=await getFile(y)).status)return function(e,t,n){if(!n)return null;let i=p[e]??`Error (${e}) occurred while trying to load file`;throw Error(`${i}: "${t}".`)}(c.status,y,n);o=b}v=s&&"undefined"!=typeof Response&&c instanceof Response&&200===c.status}(0,u.T2)(i.progress_callback,{status:"download",name:e,file:t});let E={status:"progress",name:e,file:t};return i.progress_callback?x&&"undefined"!=typeof navigator&&/firefox/i.test(navigator.userAgent)?(f=new Uint8Array(await c.arrayBuffer()),(0,u.T2)(i.progress_callback,{...E,progress:100,loaded:f.length,total:f.length})):f=await readResponse(c,e=>{(0,u.T2)(i.progress_callback,{...E,...e})}):f=new Uint8Array(await c.arrayBuffer()),v&&o&&await s.match(o)===void 0&&await s.put(o,new Response(f,{headers:c.headers})).catch(e=>{console.warn(`Unable to add response to browser cache: ${e}.`)}),(0,u.T2)(i.progress_callback,{status:"done",name:e,file:t}),f}async function getModelJSON(e,t,n=!0,i={}){let s=await getModelFile(e,t,n,i);return null===s?{}:JSON.parse(new TextDecoder("utf-8").decode(s))}async function readResponse(e,t){let n=e.headers.get("Content-Length");null===n&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let i=parseInt(n??"0"),s=new Uint8Array(i),o=0,a=e.body.getReader();async function read(){let{done:e,value:n}=await a.read();if(e)return;let u=o+n.length;if(u>i){i=u;let e=new Uint8Array(i);e.set(s),s=e}s.set(n,o),o=u;let c=o/i*100;return t({progress:c,loaded:o,total:i}),read()}return await read(),s}function pathJoin(...e){return(e=e.map((t,n)=>(n&&(t=t.replace(RegExp("^/"),"")),n!==e.length-1&&(t=t.replace(RegExp("/$"),"")),t))).join("/")}},4297:function(e,t,n){"use strict";function interpolate_data(e,[t,n,i],[s,o],a="bilinear",u=!1){let c=o/i,f=s/n,p=new e.constructor(s*o*t),m=n*i,g=s*o;for(let a=0;a=0;--e)s[e]=o,i[e]=t[n[e]],o*=i[e];let o=n.map((e,t)=>s[n.indexOf(t)]),a=new e.constructor(e.length);for(let n=0;n=0;--e)i+=s%t[e]*o[e],s=Math.floor(s/t[e]);a[i]=e[n]}return[a,i]}function softmax(e){let t=max(e)[0],n=e.map(e=>Math.exp(e-t)),i=n.reduce((e,t)=>e+t,0),s=n.map(e=>e/i);return s}function log_softmax(e){let t=softmax(e),n=t.map(e=>Math.log(e));return n}function getTopItems(e,t=0){return e=Array.from(e).map((e,t)=>[t,e]).sort((e,t)=>t[1]-e[1]),null!==t&&t>0&&(e=e.slice(0,t)),e}function min(e){if(0===e.length)throw Error("Array must not be empty");let t=e[0],n=0;for(let i=1;it&&(t=e[i],n=i);return[Number(t),n]}function isPowerOfTwo(e){return e>0&&(e&e-1)==0}n.d(t,{CI:function(){return log_softmax},Fp:function(){return max},K0:function(){return transpose_data},NM:function(){return round},Nq:function(){return interpolate_data},VV:function(){return min},XA:function(){return softmax},em:function(){return getTopItems},qC:function(){return medianFilter},vw:function(){return FFT}});let P2FFT=class P2FFT{constructor(e){if(this.size=0|e,this.size<=1||!isPowerOfTwo(this.size))throw Error("FFT size must be a power of two larger than 1");this._csize=e<<1,this.table=new Float64Array(2*this.size);for(let e=0;ee;e<<=1)++t;this._width=t%2==0?t-1:t,this._bitrev=new Int32Array(1<>>t&3)<>>1);for(let t=0;t>>1]=e[t];return n}toComplexArray(e,t){let n=t||this.createComplexArray();for(let t=0;t>>1],n[t+1]=0;return n}completeSpectrum(e){let t=this._csize,n=t>>>1;for(let i=2;i>=2;u>=2;u>>=2){c=o/u<<1;let t=c>>>2;for(i=0;i>>1,u>>>1)}else for(i=0,s=0;i>>1,u>>>1,n)}for(u>>=2;u>=2;u>>=2){c=o/u<<1;let t=c>>>2;for(i=0;i>1;++t){let n=(t+1-e)**2/2,i=Math.sqrt(u**2+c**2)**n,a=n*Math.atan2(c,u),f=2*t;s[f]=i*Math.cos(a),s[f+1]=i*Math.sin(a),o[f]=s[f],o[f+1]=-s[f+1]}this._slicedChirpBuffer=s.subarray(t,n),this._f=new P2FFT(i>>1),this._f.transform(this._chirpBuffer,o)}_transform(e,t,n){let i=this._buffer1,s=this._buffer2,o=this._outBuffer1,a=this._outBuffer2,u=this._chirpBuffer,c=this._slicedChirpBuffer,f=this._a;if(n)for(let e=0;e>1,o=t[s];i[e]=o*c[e],i[n]=o*c[n]}else for(let e=0;e=e.length&&(s=2*(e.length-1)-s),i[o++]=e[s]}i.sort(),n[t]=i[s]}return n}function round(e,t){let n=Math.pow(10,t);return Math.round(e*n)/n}},6001:function(e,t,n){"use strict";n.d(t,{J6:function(){return mean},Ks:function(){return dynamicTimeWarping},d3:function(){return cat},es:function(){return Tensor},f3:function(){return std_mean},kn:function(){return stack},p4:function(){return transpose},r6:function(){return ones_like},sX:function(){return interpolate},v6:function(){return mean_pooling}});var i=n(6577),s=n(4297);let o=Object.freeze({float32:Float32Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array}),a=i.ONNX.Tensor;let Tensor=class Tensor{dims;type;data;size;constructor(...e){return e[0]instanceof a?Object.assign(this,e[0]):Object.assign(this,new a(e[0],e[1],e[2])),new Proxy(this,{get:(e,t)=>{if("string"==typeof t){let n=Number(t);if(Number.isInteger(n))return e._getitem(n)}return e[t]},set:(e,t,n)=>e[t]=n})}*[Symbol.iterator](){let[e,...t]=this.dims;if(t.length>0){let n=t.reduce((e,t)=>e*t);for(let i=0;i0))return new Tensor(this.type,[this.data[e]],n);{let t=n.reduce((e,t)=>e*t);return this._subarray(e,t,n)}}indexOf(e){for(let t=0;te*t);if(n!==i)throw Error(`cannot reshape array of size ${n} into shape (${t})`);let s=e;for(let e=t.length-1;e>=0;e--)s=s.reduce((n,i)=>{let s=n[n.length-1];return s.lengths[1])throw Error(`Invalid slice: ${s}`);let e=[Math.max(s[0],0),Math.min(s[1],this.dims[i])];n.push(e),t.push(e[1]-e[0])}else throw Error(`Invalid slice: ${s}`)}let i=n.map(([e,t])=>t-e),s=i.reduce((e,t)=>e*t),o=new this.data.constructor(s),a=this.stride();for(let e=0;e=0;--s){let e=i[s];t+=(o%e+n[s][0])*a[s],o=Math.floor(o/e)}o[e]=this.data[t]}return new Tensor(this.type,o,t)}transpose(...e){return transpose(this,e)}sum(e=null,t=!1){return this.norm(1,e,t)}norm(e="fro",t=null,n=!1){if("fro"===e)e=2;else if("string"==typeof e)throw Error(`Unsupported norm: ${e}`);if(null===t){let t=this.data.reduce((t,n)=>t+n**e,0)**(1/e);return new Tensor(this.type,[t],[])}t=safeIndex(t,this.dims.length);let i=this.dims.slice();i[t]=1;let s=new this.data.constructor(this.data.length/this.dims[t]);for(let n=0;n=0;--e){let n=this.dims[e];if(e!==t){let t=s%n;o+=t*a,a*=i[e]}s=Math.floor(s/n)}s[o]+=this.data[n]**e}if(1!==e)for(let t=0;t=0;--n){let e=this.dims[n];if(n!==t){let t=s%e;i+=t*o,o*=this.dims[n]}s=Math.floor(s/e)}this.data[e]/=n.data[i]}return this}normalize(e=2,t=1){return this.clone().normalize_(e,t)}stride(){return function(e){let t=Array(e.length);for(let n=e.length-1,i=1;n>=0;--n)t[n]=i,i*=e[n];return t}(this.dims)}squeeze(e=null){return new Tensor(this.type,this.data,calc_squeeze_dims(this.dims,e))}squeeze_(e=null){return this.dims=calc_squeeze_dims(this.dims,e),this}unsqueeze(e=null){return new Tensor(this.type,this.data,calc_unsqueeze_dims(this.dims,e))}unsqueeze_(e=null){return this.dims=calc_unsqueeze_dims(this.dims,e),this}flatten_(e=0,t=-1){t=(t+this.dims.length)%this.dims.length;let n=this.dims.slice(0,e),i=this.dims.slice(e,t+1),s=this.dims.slice(t+1);return this.dims=[...n,i.reduce((e,t)=>e*t,1),...s],this}flatten(e=0,t=-1){return this.clone().flatten_(e,t)}view(...e){let t=-1;for(let n=0;ni!==t?e*n:e,1);e[t]=this.data.length/n}return new Tensor(this.type,this.data,e)}neg_(){for(let e=0;e1!==e):"number"==typeof t?1===e[t]&&e.splice(t,1):Array.isArray(t)&&(e=e.filter((e,n)=>1!==e||!t.includes(n))),e}function calc_unsqueeze_dims(e,t){return t=safeIndex(t,e.length+1),(e=e.slice()).splice(t,0,1),e}function safeIndex(e,t,n=null){if(e<-t||e>=t)throw Error(`IndexError: index ${e} is out of bounds for dimension${null===n?"":" "+n} with size ${t}`);return e<0&&(e=(e%t+t)%t),e}function cat(e,t=0){t=safeIndex(t,e[0].dims.length);let n=e[0].dims.slice();n[t]=e.reduce((e,n)=>e+n.dims[t],0);let i=n.reduce((e,t)=>e*t,1),s=new e[0].data.constructor(i),o=e[0].type;if(0===t){let t=0;for(let n of e)s.set(n.data,t),t+=n.data.length}else{let i=0;for(let o=0;o=0;--s){let e=a.dims[s],f=u%e;s===t&&(f+=i),o+=f*c,c*=n[s],u=Math.floor(u/e)}s[o]=a.data[e]}i+=a.dims[t]}}return new Tensor(o,s,n)}function stack(e,t=0){return cat(e.map(e=>e.unsqueeze(t)),t)}function std_mean(e,t=null,n=1,i=!1){if(null===t){let t=e.data.reduce((e,t)=>e+t,0),i=t/e.data.length,s=Math.sqrt(e.data.reduce((e,t)=>e+(t-i)**2,0)/(e.data.length-n)),o=new Tensor(e.type,[i],[]),a=new Tensor(e.type,[s],[]);return[a,o]}t=safeIndex(t,e.dims.length);let s=mean(e,t,i),o=e.dims.slice();o[t]=1;let a=new e.data.constructor(e.data.length/e.dims[t]);for(let n=0;n=0;--s){let n=e.dims[s];if(s!==t){let e=a%n;i+=e*u,u*=o[s]}a=Math.floor(a/n)}a[i]+=(e.data[n]-s.data[i])**2}for(let i=0;ie+t,0);return new Tensor(e.type,[t/e.data.length],[])}t=safeIndex(t,e.dims.length);let i=e.dims.slice();i[t]=1;let s=new e.data.constructor(e.data.length/e.dims[t]);for(let n=0;n=0;--s){let n=e.dims[s];if(s!==t){let e=a%n;o+=e*u,u*=i[s]}a=Math.floor(a/n)}s[o]+=e.data[n]}if(1!==e.dims[t])for(let n=0;n0||u>0;){c.push(a-1),f.push(u-1);let e=o[a][u].item();switch(e){case 0:--a,--u;break;case 1:--a;break;case 2:--u;break;default:throw Error(`Internal error in dynamic time warping. Unexpected trace[${a}, ${u}]. Please file a bug report.`)}}return c.reverse(),f.reverse(),[c,f]}function ones_like(e){return function(e){let t=e.reduce((e,t)=>e*t,1);return new Tensor("int64",new BigInt64Array(t).fill(1n),e)}(e.dims)}}}]);