diff --git "a/_next/static/chunks/990.5d290f619543b668.js" "b/_next/static/chunks/990.5d290f619543b668.js" new file mode 100644--- /dev/null +++ "b/_next/static/chunks/990.5d290f619543b668.js" @@ -0,0 +1,6 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[990],{4699:function(e,t){"use strict";t.byteLength=function(e){var t=l(e),r=t[0],s=t[1];return(r+s)*3/4-s},t.toByteArray=function(e){var t,r,i=l(e),o=i[0],a=i[1],h=new n((o+a)*3/4-a),c=0,u=a>0?o-4:o;for(r=0;r>16&255,h[c++]=t>>8&255,h[c++]=255&t;return 2===a&&(t=s[e.charCodeAt(r)]<<2|s[e.charCodeAt(r+1)]>>4,h[c++]=255&t),1===a&&(t=s[e.charCodeAt(r)]<<10|s[e.charCodeAt(r+1)]<<4|s[e.charCodeAt(r+2)]>>2,h[c++]=t>>8&255,h[c++]=255&t),h},t.fromByteArray=function(e){for(var t,s=e.length,n=s%3,i=[],o=0,a=s-n;o>18&63]+r[n>>12&63]+r[n>>6&63]+r[63&n]);return i.join("")}(e,o,o+16383>a?a:o+16383));return 1===n?i.push(r[(t=e[s-1])>>2]+r[t<<4&63]+"=="):2===n&&i.push(r[(t=(e[s-2]<<8)+e[s-1])>>10]+r[t>>4&63]+r[t<<2&63]+"="),i.join("")};for(var r=[],s=[],n="undefined"!=typeof Uint8Array?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,a=i.length;o0)throw Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");-1===r&&(r=t);var s=r===t?0:4-r%4;return[r,s]}s["-".charCodeAt(0)]=62,s["_".charCodeAt(0)]=63},7133:function(e,t,r){"use strict";/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */var s=r(4699),n=r(9087),i="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;function o(e){if(e>2147483647)throw RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return Object.setPrototypeOf(t,a.prototype),t}function a(e,t,r){if("number"==typeof e){if("string"==typeof t)throw TypeError('The "string" argument must be of type string. Received type number');return c(e)}return l(e,t,r)}function l(e,t,r){if("string"==typeof e)return function(e,t){if(("string"!=typeof t||""===t)&&(t="utf8"),!a.isEncoding(t))throw TypeError("Unknown encoding: "+t);var r=0|p(e,t),s=o(r),n=s.write(e,t);return n!==r&&(s=s.slice(0,n)),s}(e,t);if(ArrayBuffer.isView(e))return function(e){if(M(e,Uint8Array)){var t=new Uint8Array(e);return d(t.buffer,t.byteOffset,t.byteLength)}return u(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(M(e,ArrayBuffer)||e&&M(e.buffer,ArrayBuffer)||"undefined"!=typeof SharedArrayBuffer&&(M(e,SharedArrayBuffer)||e&&M(e.buffer,SharedArrayBuffer)))return d(e,t,r);if("number"==typeof e)throw TypeError('The "value" argument must not be of type number. Received type number');var s=e.valueOf&&e.valueOf();if(null!=s&&s!==e)return a.from(s,t,r);var n=function(e){if(a.isBuffer(e)){var t,r=0|f(e.length),s=o(r);return 0===s.length||e.copy(s,0,0,r),s}return void 0!==e.length?"number"!=typeof e.length||(t=e.length)!=t?o(0):u(e):"Buffer"===e.type&&Array.isArray(e.data)?u(e.data):void 0}(e);if(n)return n;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return a.from(e[Symbol.toPrimitive]("string"),t,r);throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function h(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 c(e){return h(e),o(e<0?0:0|f(e))}function u(e){for(var t=e.length<0?0:0|f(e.length),r=o(t),s=0;s=2147483647)throw RangeError("Attempt to allocate Buffer larger than maximum size: 0x7fffffff bytes");return 0|e}function p(e,t){if(a.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||M(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 r=e.length,s=arguments.length>2&&!0===arguments[2];if(!s&&0===r)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return z(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return T(e).length;default:if(n)return s?-1:z(e).length;t=(""+t).toLowerCase(),n=!0}}function _(e,t,r){var n,i,o=!1;if((void 0===t||t<0)&&(t=0),t>this.length||((void 0===r||r>this.length)&&(r=this.length),r<=0||(r>>>=0)<=(t>>>=0)))return"";for(e||(e="utf8");;)switch(e){case"hex":return function(e,t,r){var s=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>s)&&(r=s);for(var n="",i=t;i2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),(i=r=+r)!=i&&(r=n?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(n)return -1;r=e.length-1}else if(r<0){if(!n)return -1;r=0}if("string"==typeof t&&(t=a.from(t,s)),a.isBuffer(t))return 0===t.length?-1:y(e,t,r,s,n);if("number"==typeof t)return(t&=255,"function"==typeof Uint8Array.prototype.indexOf)?n?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):y(e,[t],r,s,n);throw TypeError("val must be string, number or Buffer")}function y(e,t,r,s,n){var i,o=1,a=e.length,l=t.length;if(void 0!==s&&("ucs2"===(s=String(s).toLowerCase())||"ucs-2"===s||"utf16le"===s||"utf-16le"===s)){if(e.length<2||t.length<2)return -1;o=2,a/=2,l/=2,r/=2}function h(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(n){var c=-1;for(i=r;ia&&(r=a-l),i=r;i>=0;i--){for(var u=!0,d=0;d239?4:h>223?3:h>191?2:1;if(n+u<=r)switch(u){case 1:h<128&&(c=h);break;case 2:(192&(i=e[n+1]))==128&&(l=(31&h)<<6|63&i)>127&&(c=l);break;case 3:i=e[n+1],o=e[n+2],(192&i)==128&&(192&o)==128&&(l=(15&h)<<12|(63&i)<<6|63&o)>2047&&(l<55296||l>57343)&&(c=l);break;case 4:i=e[n+1],o=e[n+2],a=e[n+3],(192&i)==128&&(192&o)==128&&(192&a)==128&&(l=(15&h)<<18|(63&i)<<12|(63&o)<<6|63&a)>65535&&l<1114112&&(c=l)}null===c?(c=65533,u=1):c>65535&&(c-=65536,s.push(c>>>10&1023|55296),c=56320|1023&c),s.push(c),n+=u}return function(e){var t=e.length;if(t<=4096)return String.fromCharCode.apply(String,e);for(var r="",s=0;sr)throw RangeError("Trying to access beyond buffer length")}function x(e,t,r,s,n,i){if(!a.isBuffer(e))throw TypeError('"buffer" argument must be a Buffer instance');if(t>n||te.length)throw RangeError("Index out of range")}function k(e,t,r,s,n,i){if(r+s>e.length||r<0)throw RangeError("Index out of range")}function v(e,t,r,s,i){return t=+t,r>>>=0,i||k(e,t,r,4,34028234663852886e22,-34028234663852886e22),n.write(e,t,r,s,23,4),r+4}function A(e,t,r,s,i){return t=+t,r>>>=0,i||k(e,t,r,8,17976931348623157e292,-17976931348623157e292),n.write(e,t,r,s,52,8),r+8}t.lW=a,t.h2=50,a.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}}(),a.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(a.prototype,"parent",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.buffer}}),Object.defineProperty(a.prototype,"offset",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.byteOffset}}),a.poolSize=8192,a.from=function(e,t,r){return l(e,t,r)},Object.setPrototypeOf(a.prototype,Uint8Array.prototype),Object.setPrototypeOf(a,Uint8Array),a.alloc=function(e,t,r){return(h(e),e<=0)?o(e):void 0!==t?"string"==typeof r?o(e).fill(t,r):o(e).fill(t):o(e)},a.allocUnsafe=function(e){return c(e)},a.allocUnsafeSlow=function(e){return c(e)},a.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==a.prototype},a.compare=function(e,t){if(M(e,Uint8Array)&&(e=a.from(e,e.offset,e.byteLength)),M(t,Uint8Array)&&(t=a.from(t,t.offset,t.byteLength)),!a.isBuffer(e)||!a.isBuffer(t))throw TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;for(var r=e.length,s=t.length,n=0,i=Math.min(r,s);ns.length?a.from(i).copy(s,n):Uint8Array.prototype.set.call(s,i,n);else if(a.isBuffer(i))i.copy(s,n);else throw TypeError('"list" argument must be an Array of Buffers');n+=i.length}return s},a.byteLength=p,a.prototype._isBuffer=!0,a.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;tr&&(e+=" ... "),""},i&&(a.prototype[i]=a.prototype.inspect),a.prototype.compare=function(e,t,r,s,n){if(M(e,Uint8Array)&&(e=a.from(e,e.offset,e.byteLength)),!a.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===r&&(r=e?e.length:0),void 0===s&&(s=0),void 0===n&&(n=this.length),t<0||r>e.length||s<0||n>this.length)throw RangeError("out of range index");if(s>=n&&t>=r)return 0;if(s>=n)return -1;if(t>=r)return 1;if(t>>>=0,r>>>=0,s>>>=0,n>>>=0,this===e)return 0;for(var i=n-s,o=r-t,l=Math.min(i,o),h=this.slice(s,n),c=e.slice(t,r),u=0;u>>=0,isFinite(r)?(r>>>=0,void 0===s&&(s="utf8")):(s=r,r=void 0);else throw Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var n,i,o,a,l,h,c,u,d=this.length-t;if((void 0===r||r>d)&&(r=d),e.length>0&&(r<0||t<0)||t>this.length)throw RangeError("Attempt to write outside buffer bounds");s||(s="utf8");for(var f=!1;;)switch(s){case"hex":return function(e,t,r,s){r=Number(r)||0;var n=e.length-r;s?(s=Number(s))>n&&(s=n):s=n;var i=t.length;s>i/2&&(s=i/2);for(var o=0;o>8,n.push(r%256),n.push(s);return n}(e,this.length-c),this,c,u);default:if(f)throw TypeError("Unknown encoding: "+s);s=(""+s).toLowerCase(),f=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},a.prototype.slice=function(e,t){var r=this.length;e=~~e,t=void 0===t?r:~~t,e<0?(e+=r)<0&&(e=0):e>r&&(e=r),t<0?(t+=r)<0&&(t=0):t>r&&(t=r),t>>=0,t>>>=0,r||b(e,t,this.length);for(var s=this[e],n=1,i=0;++i>>=0,t>>>=0,r||b(e,t,this.length);for(var s=this[e+--t],n=1;t>0&&(n*=256);)s+=this[e+--t]*n;return s},a.prototype.readUint8=a.prototype.readUInt8=function(e,t){return e>>>=0,t||b(e,1,this.length),this[e]},a.prototype.readUint16LE=a.prototype.readUInt16LE=function(e,t){return e>>>=0,t||b(e,2,this.length),this[e]|this[e+1]<<8},a.prototype.readUint16BE=a.prototype.readUInt16BE=function(e,t){return e>>>=0,t||b(e,2,this.length),this[e]<<8|this[e+1]},a.prototype.readUint32LE=a.prototype.readUInt32LE=function(e,t){return e>>>=0,t||b(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},a.prototype.readUint32BE=a.prototype.readUInt32BE=function(e,t){return e>>>=0,t||b(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},a.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||b(e,t,this.length);for(var s=this[e],n=1,i=0;++i=(n*=128)&&(s-=Math.pow(2,8*t)),s},a.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||b(e,t,this.length);for(var s=t,n=1,i=this[e+--s];s>0&&(n*=256);)i+=this[e+--s]*n;return i>=(n*=128)&&(i-=Math.pow(2,8*t)),i},a.prototype.readInt8=function(e,t){return(e>>>=0,t||b(e,1,this.length),128&this[e])?-((255-this[e]+1)*1):this[e]},a.prototype.readInt16LE=function(e,t){e>>>=0,t||b(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},a.prototype.readInt16BE=function(e,t){e>>>=0,t||b(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},a.prototype.readInt32LE=function(e,t){return e>>>=0,t||b(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},a.prototype.readInt32BE=function(e,t){return e>>>=0,t||b(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},a.prototype.readFloatLE=function(e,t){return e>>>=0,t||b(e,4,this.length),n.read(this,e,!0,23,4)},a.prototype.readFloatBE=function(e,t){return e>>>=0,t||b(e,4,this.length),n.read(this,e,!1,23,4)},a.prototype.readDoubleLE=function(e,t){return e>>>=0,t||b(e,8,this.length),n.read(this,e,!0,52,8)},a.prototype.readDoubleBE=function(e,t){return e>>>=0,t||b(e,8,this.length),n.read(this,e,!1,52,8)},a.prototype.writeUintLE=a.prototype.writeUIntLE=function(e,t,r,s){if(e=+e,t>>>=0,r>>>=0,!s){var n=Math.pow(2,8*r)-1;x(this,e,t,r,n,0)}var i=1,o=0;for(this[t]=255&e;++o>>=0,r>>>=0,!s){var n=Math.pow(2,8*r)-1;x(this,e,t,r,n,0)}var i=r-1,o=1;for(this[t+i]=255&e;--i>=0&&(o*=256);)this[t+i]=e/o&255;return t+r},a.prototype.writeUint8=a.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||x(this,e,t,1,255,0),this[t]=255&e,t+1},a.prototype.writeUint16LE=a.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||x(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},a.prototype.writeUint16BE=a.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||x(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},a.prototype.writeUint32LE=a.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||x(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},a.prototype.writeUint32BE=a.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||x(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},a.prototype.writeIntLE=function(e,t,r,s){if(e=+e,t>>>=0,!s){var n=Math.pow(2,8*r-1);x(this,e,t,r,n-1,-n)}var i=0,o=1,a=0;for(this[t]=255&e;++i>0)-a&255;return t+r},a.prototype.writeIntBE=function(e,t,r,s){if(e=+e,t>>>=0,!s){var n=Math.pow(2,8*r-1);x(this,e,t,r,n-1,-n)}var i=r-1,o=1,a=0;for(this[t+i]=255&e;--i>=0&&(o*=256);)e<0&&0===a&&0!==this[t+i+1]&&(a=1),this[t+i]=(e/o>>0)-a&255;return t+r},a.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||x(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},a.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||x(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},a.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||x(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},a.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||x(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},a.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||x(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},a.prototype.writeFloatLE=function(e,t,r){return v(this,e,t,!0,r)},a.prototype.writeFloatBE=function(e,t,r){return v(this,e,t,!1,r)},a.prototype.writeDoubleLE=function(e,t,r){return A(this,e,t,!0,r)},a.prototype.writeDoubleBE=function(e,t,r){return A(this,e,t,!1,r)},a.prototype.copy=function(e,t,r,s){if(!a.isBuffer(e))throw TypeError("argument should be a Buffer");if(r||(r=0),s||0===s||(s=this.length),t>=e.length&&(t=e.length),t||(t=0),s>0&&s=this.length)throw RangeError("Index out of range");if(s<0)throw RangeError("sourceEnd out of bounds");s>this.length&&(s=this.length),e.length-t>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(n=t;n55295&&r<57344){if(!n){if(r>56319||o+1===s){(t-=3)>-1&&i.push(239,191,189);continue}n=r;continue}if(r<56320){(t-=3)>-1&&i.push(239,191,189),n=r;continue}r=(n-55296<<10|r-56320)+65536}else n&&(t-=3)>-1&&i.push(239,191,189);if(n=null,r<128){if((t-=1)<0)break;i.push(r)}else if(r<2048){if((t-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;i.push(r>>12|224,r>>6&63|128,63&r|128)}else if(r<1114112){if((t-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}else throw Error("Invalid code point")}return i}function T(e){return s.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(E,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function S(e,t,r,s){for(var n=0;n=t.length)&&!(n>=e.length);++n)t[n+r]=e[n];return n}function M(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}var I=function(){for(var e="0123456789abcdef",t=Array(256),r=0;r<16;++r)for(var s=16*r,n=0;n<16;++n)t[s+n]=e[r]+e[n];return t}()},9087:function(e,t){/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */t.read=function(e,t,r,s,n){var i,o,a=8*n-s-1,l=(1<>1,c=-7,u=r?n-1:0,d=r?-1:1,f=e[t+u];for(u+=d,i=f&(1<<-c)-1,f>>=-c,c+=a;c>0;i=256*i+e[t+u],u+=d,c-=8);for(o=i&(1<<-c)-1,i>>=-c,c+=s;c>0;o=256*o+e[t+u],u+=d,c-=8);if(0===i)i=1-h;else{if(i===l)return o?NaN:(f?-1:1)*(1/0);o+=Math.pow(2,s),i-=h}return(f?-1:1)*o*Math.pow(2,i-s)},t.write=function(e,t,r,s,n,i){var o,a,l,h=8*i-n-1,c=(1<>1,d=23===n?5960464477539062e-23:0,f=s?0:i-1,p=s?1:-1,_=t<0||0===t&&1/t<0?1:0;for(isNaN(t=Math.abs(t))||t===1/0?(a=isNaN(t)?1:0,o=c):(o=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-o))<1&&(o--,l*=2),o+u>=1?t+=d/l:t+=d*Math.pow(2,1-u),t*l>=2&&(o++,l/=2),o+u>=c?(a=0,o=c):o+u>=1?(a=(t*l-1)*Math.pow(2,n),o+=u):(a=t*Math.pow(2,u-1)*Math.pow(2,n),o=0));n>=8;e[r+f]=255&a,f+=p,a/=256,n-=8);for(o=o<0;e[r+f]=255&o,f+=p,o/=256,h-=8);e[r+f-p]|=128*_}},2601:function(e,t,r){"use strict";var s,n;e.exports=(null==(s=r.g.process)?void 0:s.env)&&"object"==typeof(null==(n=r.g.process)?void 0:n.env)?r.g.process:r(8960)},692:function(e,t,r){!function(){var t={452:function(e){"use strict";e.exports=r(9875)}},s={};function n(e){var r=s[e];if(void 0!==r)return r.exports;var i=s[e]={exports:{}},o=!0;try{t[e](i,i.exports,n),o=!1}finally{o&&delete s[e]}return i.exports}n.ab="//";var i={};!function(){var e,t=(e=n(452))&&"object"==typeof e&&"default"in e?e.default:e,r=/https?|ftp|gopher|file/;function s(e){"string"==typeof e&&(e=g(e));var s,n,i,o,a,l,h,c,u,d=(n=(s=e).auth,i=s.hostname,o=s.protocol||"",a=s.pathname||"",l=s.hash||"",h=s.query||"",c=!1,n=n?encodeURIComponent(n).replace(/%3A/i,":")+"@":"",s.host?c=n+s.host:i&&(c=n+(~i.indexOf(":")?"["+i+"]":i),s.port&&(c+=":"+s.port)),h&&"object"==typeof h&&(h=t.encode(h)),u=s.search||h&&"?"+h||"",o&&":"!==o.substr(-1)&&(o+=":"),s.slashes||(!o||r.test(o))&&!1!==c?(c="//"+(c||""),a&&"/"!==a[0]&&(a="/"+a)):c||(c=""),l&&"#"!==l[0]&&(l="#"+l),u&&"?"!==u[0]&&(u="?"+u),{protocol:o,host:c,pathname:a=a.replace(/[?#]/g,encodeURIComponent),search:u=u.replace("#","%23"),hash:l});return""+d.protocol+d.host+d.pathname+d.search+d.hash}var o="http://",a=o+"w.w",l=/^([a-z0-9.+-]*:\/\/\/)([a-z0-9.+-]:\/*)?/i,h=/https?|ftp|gopher|file/;function c(e,t){var r="string"==typeof e?g(e):e;e="object"==typeof e?s(e):e;var n=g(t),i="";r.protocol&&!r.slashes&&(i=r.protocol,e=e.replace(r.protocol,""),i+="/"===t[0]||"/"===e[0]?"/":""),i&&n.protocol&&(i="",n.slashes||(i=n.protocol,t=t.replace(n.protocol,"")));var c=e.match(l);c&&!n.protocol&&(e=e.substr((i=c[1]+(c[2]||"")).length),/^\/\/[^/]/.test(t)&&(i=i.slice(0,-1)));var u=new URL(e,a+"/"),d=new URL(t,u).toString().replace(a,""),f=n.protocol||r.protocol;return f+=r.slashes||n.slashes?"//":"",!i&&f?d=d.replace(o,f):i&&(d=d.replace(o,"")),h.test(d)||~t.indexOf(".")||"/"===e.slice(-1)||"/"===t.slice(-1)||"/"!==d.slice(-1)||(d=d.slice(0,-1)),i&&(d=i+("/"===d[0]?d.substr(1):d)),d}function u(){}u.prototype.parse=g,u.prototype.format=s,u.prototype.resolve=c,u.prototype.resolveObject=c;var d=/^https?|ftp|gopher|file/,f=/^(.*?)([#?].*)/,p=/^([a-z0-9.+-]*:)(\/{0,3})(.*)/i,_=/^([a-z0-9.+-]*:)?\/\/\/*/i,m=/^([a-z0-9.+-]*:)(\/{0,2})\[(.*)\]$/i;function g(e,r,n){if(void 0===r&&(r=!1),void 0===n&&(n=!1),e&&"object"==typeof e&&e instanceof u)return e;var i=(e=e.trim()).match(f);e=i?i[1].replace(/\\/g,"/")+i[2]:e.replace(/\\/g,"/"),m.test(e)&&"/"!==e.slice(-1)&&(e+="/");var o=!/(^javascript)/.test(e)&&e.match(p),l=_.test(e),h="";o&&(d.test(o[1])||(h=o[1].toLowerCase(),e=""+o[2]+o[3]),o[2]||(l=!1,d.test(o[1])?(h=o[1],e=""+o[3]):e="//"+o[3]),3!==o[2].length&&1!==o[2].length||(h=o[1],e="/"+o[3]));var c,g=(i?i[1]:e).match(/^https?:\/\/[^/]+(:[0-9]+)(?=\/|$)/),y=g&&g[1],w=new u,b="",x="";try{c=new URL(e)}catch(t){b=t,h||n||!/^\/\//.test(e)||/^\/\/.+[@.]/.test(e)||(x="/",e=e.substr(1));try{c=new URL(e,a)}catch(e){return w.protocol=h,w.href=h,w}}w.slashes=l&&!x,w.host="w.w"===c.host?"":c.host,w.hostname="w.w"===c.hostname?"":c.hostname.replace(/(\[|\])/g,""),w.protocol=b?h||null:c.protocol,w.search=c.search.replace(/\\/g,"%5C"),w.hash=c.hash.replace(/\\/g,"%5C");var k=e.split("#");!w.search&&~k[0].indexOf("?")&&(w.search="?"),w.hash||""!==k[1]||(w.hash="#"),w.query=r?t.decode(c.search.substr(1)):w.search.substr(1),w.pathname=x+(o?c.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}}):c.pathname),"about:"===w.protocol&&"blank"===w.pathname&&(w.protocol="",w.pathname=""),b&&"/"!==e[0]&&(w.pathname=w.pathname.substr(1)),h&&!d.test(h)&&"/"!==e.slice(-1)&&"/"===w.pathname&&(w.pathname=""),w.path=w.pathname+w.search,w.auth=[c.username,c.password].map(decodeURIComponent).filter(Boolean).join(":"),w.port=c.port,y&&!w.host.endsWith(y)&&(w.host+=y,w.port=y.slice(1)),w.href=x?""+w.pathname+w.search+w.hash:s(w);var v=/^(file)/.test(w.href)?["host","hostname"]:[];return Object.keys(w).forEach(function(e){~v.indexOf(e)||(w[e]=w[e]||null)}),w}i.parse=g,i.format=s,i.resolve=c,i.resolveObject=function(e,t){return g(c(e,t))},i.Url=u}(),e.exports=i}()},8960:function(e){!function(){var t={229:function(e){var t,r,s,n=e.exports={};function i(){throw Error("setTimeout has not been defined")}function o(){throw Error("clearTimeout has not been defined")}function a(e){if(t===setTimeout)return setTimeout(e,0);if((t===i||!t)&&setTimeout)return t=setTimeout,setTimeout(e,0);try{return t(e,0)}catch(r){try{return t.call(null,e,0)}catch(r){return t.call(this,e,0)}}}!function(){try{t="function"==typeof setTimeout?setTimeout:i}catch(e){t=i}try{r="function"==typeof clearTimeout?clearTimeout:o}catch(e){r=o}}();var l=[],h=!1,c=-1;function u(){h&&s&&(h=!1,s.length?l=s.concat(l):c=-1,l.length&&d())}function d(){if(!h){var e=a(u);h=!0;for(var t=l.length;t;){for(s=l,l=[];++c1)for(var r=1;r0&&l>a&&(l=a);for(var h=0;h=0?(c=p.substr(0,_),u=p.substr(_+1)):(c=p,u=""),d=decodeURIComponent(c),f=decodeURIComponent(u),Object.prototype.hasOwnProperty.call(i,d))?t(i[d])?i[d].push(f):i[d]=[i[d],f]:i[d]=f}return i};var t=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},577:function(e){var t=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,o,a){return(i=i||"&",o=o||"=",null===e&&(e=void 0),"object"==typeof e)?s(n(e),function(n){var a=encodeURIComponent(t(n))+o;return r(e[n])?s(e[n],function(e){return a+encodeURIComponent(t(e))}).join(i):a+encodeURIComponent(t(e[n]))}).join(i):a?encodeURIComponent(t(a))+o+encodeURIComponent(t(e)):""};var r=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};function s(e,t){if(e.map)return e.map(t);for(var r=[],s=0;s{if(t&&"function"==typeof t.init&&"function"==typeof t.createSessionHandler){let i=s[e];if(void 0===i)s[e]={backend:t,priority:r};else if(i.priority>r)return;else if(i.priority===r&&i.backend!==t)throw Error(`cannot register backend "${e}" using priority ${r}`);if(r>=0){let t=n.indexOf(e);-1!==t&&n.splice(t,1);for(let t=0;t{let t=0===e.length?n:e,r=[];for(let e of t){let t=s[e];if(t){if(t.initialized)return t.backend;if(t.aborted)continue;let s=!!t.initPromise;try{return s||(t.initPromise=t.backend.init()),await t.initPromise,t.initialized=!0,t.backend}catch(n){s||r.push({name:e,err:n}),t.aborted=!0}finally{delete t.initPromise}}}throw Error(`no available backend found. ERR: ${r.map(e=>`[${e.name}] ${e.err}`).join(", ")}`)},a=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}},l="undefined"!=typeof BigInt64Array&&"function"==typeof BigInt64Array.from,h="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]]),u=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);l&&(c.set("int64",BigInt64Array),u.set(BigInt64Array,"int64")),h&&(c.set("uint64",BigUint64Array),u.set(BigUint64Array,"uint64"));let d=e=>{let t=1;for(let r=0;r{let n=document.createElement("canvas"),i=n.getContext("2d");if(!e||!i)return s();let o=new Image;o.crossOrigin="Anonymous",o.src=e,o.onload=()=>{n.width=o.width,n.height=o.height,i.drawImage(o,0,0,n.width,n.height);let e=i.getImageData(0,0,n.width,n.height);if(void 0!==t){if(void 0!==t.height&&t.height!==n.height)throw Error("Image input config height doesn't match ImageBitmap height");if(a.height=n.height,void 0!==t.width&&t.width!==n.width)throw Error("Image input config width doesn't match ImageBitmap width");a.width=n.width}else a.height=n.height,a.width=n.width;r(f.bufferToTensor(e.data,a))}});else throw Error("Input data provided is not supported - aborted tensor creation");if(void 0!==r)return f.bufferToTensor(r,a);throw Error("Input data provided is not supported - aborted tensor creation")}toImageData(e){var t,r;let s;let n=document.createElement("canvas").getContext("2d");if(null!=n){let i=this.dims[3],o=this.dims[2],a=this.dims[1],l=void 0!==e&&void 0!==e.format?e.format:"RGB",h=void 0!==e&&(null===(t=e.norm)||void 0===t?void 0:t.mean)!==void 0?e.norm.mean:255,c=void 0!==e&&(null===(r=e.norm)||void 0===r?void 0:r.bias)!==void 0?e.norm.bias:0,u=o*i;if(void 0!==e){if(void 0!==e.height&&e.height!==o)throw Error("Image output config height doesn't match tensor height");if(void 0!==e.width&&e.width!==i)throw Error("Image output config width doesn't match tensor width");if(void 0!==e.format&&4===a&&"RGBA"!==e.format||3===a&&"RGB"!==e.format&&"BGR"!==e.format)throw Error("Tensor format doesn't match input tensor dims")}let d=0,f=1,p=2,_=3,m=0,g=u,y=2*u,w=-1;"RGBA"===l?(m=0,g=u,y=2*u,w=3*u):"RGB"===l?(m=0,g=u,y=2*u):"RBG"===l&&(m=0,y=u,g=2*u),s=n.createImageData(i,o);for(let e=0;e=e.byteLength)throw RangeError(`'byteOffset' is out of range [0, ${e.byteLength}).`);if(a=e.byteLength-o,"number"==typeof r){if(!Number.isSafeInteger(a=r))throw RangeError("'byteLength' must be an integer.");if(a<=0||o+a>e.byteLength)throw RangeError(`'byteLength' is out of range (0, ${e.byteLength-o}].`);if("object"==typeof s&&null!==s)i=s;else if(void 0!==s)throw TypeError("'options' must be an object.")}else if(void 0!==r)throw TypeError("'byteLength' must be a number.")}else if(void 0!==t)throw TypeError("'options' must be an object.");n=new Uint8Array(e,o,a)}else throw TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let a=i.executionProviders||[],l=a.map(e=>"string"==typeof e?e:e.name),h=await o(l),c=await h.createSessionHandler(n,i);return new _(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}let m=_},552:function(e,t,r){"use strict";let s,n,i,o;function a(e,t){null!==e&&e(t)}function l(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}r.d(t,{OBj:function(){return L},qCb:function(){return ee},EUT:function(){return sV}});let h=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}_call(...e){throw Error("Must implement _call method in subclass")}};function c(e){return"string"==typeof e||e instanceof String}function u(e){return Number.isInteger(e)||"bigint"==typeof e}function d(e,t,r){let s=e[t];if(void 0!==s)return delete e[t],s;if(void 0===r)throw Error(`Key ${t} does not exist in object.`);return r}function f(...e){return Array.prototype.concat.apply([],e)}var p=r(7147),_=r(1418),m=r(319),g=r(8386),y=r(3342),w=r(692),b=r(495),x=r.t(b,2),k=r(2018),v=r.t(k,2),A=r(2601);let E=["wasm"];if(void 0!==A&&A?.release?.name==="node")s=b??x,E.unshift("cpu");else{s=k??v;let e="undefined"!=typeof navigator&&/iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent);e&&(s.env.wasm.simd=!1)}let{env:z}=s,T="2.6.0",S="undefined"!=typeof self&&"caches"in self,M=!R(g),I=!R(y),C=M&&I,B=C?y.dirname(y.dirname(w.fileURLToPath("file:///Users/macbook/Documents/HuggingFace/hugging-face/node_modules/@xenova/transformers/src/env.js"))):"./",O=C?y.join(B,"/.cache/"):null,P="/models/",U=C?y.join(B,P):P;z.wasm.wasmPaths=C?y.join(B,"/dist/"):`https://cdn.jsdelivr.net/npm/@xenova/transformers@${T}/dist/`;let L={backends:{onnx:z,tfjs:{}},__dirname:B,version:T,allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!0,localModelPath:U,useFS:M,useBrowserCache:S,useFSCache:M,cacheDir:O,useCustomCache:!1,customCache:null};function R(e){return 0===Object.keys(e).length}var j=r(2601),$=r(7133).lW;globalThis.ReadableStream||(globalThis.ReadableStream=m.ReadableStream);class N{_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=p.existsSync(e),this.exists){this.status=200,this.statusText="OK";let t=p.statSync(e);this.headers.set("content-length",t.size.toString()),this.updateContentType();let r=this;this.body=new ReadableStream({start(e){r.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 N(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 p.promises.readFile(this.filePath);return e.buffer}async blob(){let e=await p.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){let e=await p.promises.readFile(this.filePath,"utf8");return e}async json(){return JSON.parse(await this.text())}}function F(e,t=null){let r;try{r=new URL(e)}catch(e){return!1}return(!t||!!t.includes(r.hostname))&&("http:"===r.protocol||"https:"===r.protocol)}async function D(e){if(L.useFS&&!F(e))return new N(e);if(void 0===j||j?.release?.name!=="node")return fetch(e);{let t=!!j.env?.TESTING_REMOTELY,r=L.version,s=new Headers;s.set("User-Agent",`transformers.js/${r}; is_ci/${t};`);let n=F(e,["huggingface.co","hf.co"]);if(n){let e=j.env?.HF_ACCESS_TOKEN;e&&s.set("Authorization",`Bearer ${e}`)}return fetch(e,{headers:s})}}let q={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"};class G{constructor(e){this.path=e}async match(e){let t=_.join(this.path,e),r=new N(t);return r.exists?r:void 0}async put(e,t){let r=$.from(await t.arrayBuffer()),s=_.join(this.path,e);try{await p.promises.mkdir(_.dirname(s),{recursive:!0}),await p.promises.writeFile(s,r)}catch(e){console.warn("An error occurred while writing the file to cache:",e)}}}async function W(e,...t){for(let r of t)try{let t=await e.match(r);if(t)return t}catch(e){continue}}async function H(e,t,r=!0,s={}){let n,i,o;if(!L.allowLocalModels){if(s.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(!L.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}if(a(s.progress_callback,{status:"initiate",name:e,file:t}),!n&&L.useBrowserCache){if("undefined"==typeof caches)throw Error("Browser cache is not available in this environment.");try{n=await caches.open("transformers-cache")}catch(e){console.warn("An error occurred while opening the browser cache:",e)}}if(!n&&L.useFSCache&&(n=new G(s.cache_dir??L.cacheDir)),!n&&L.useCustomCache){if(!L.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!L.customCache.match||!L.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");n=L.customCache}let l=s.revision??"main",h=V(e,t),c=V(L.localModelPath,h),u=V(L.remoteHost,L.remotePathTemplate.replaceAll("{model}",e).replaceAll("{revision}",l),t),d="main"===l?h:V(e,l,t),f=n instanceof G?d:u,p=!1;if(n&&(o=await W(n,c,f)),void 0===o){if(L.allowLocalModels){let e=F(h);if(e){if(s.local_files_only)throw Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${h}.`);if(!L.allowRemoteModels)throw Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${h}.`)}else try{o=await D(c),i=c}catch(e){console.warn(`Unable to load from local path "${c}": "${e}"`)}}if(void 0===o||404===o.status){if(s.local_files_only||!L.allowRemoteModels){if(!r)return null;throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${c}".`)}if(200!==(o=await D(u)).status)return function(e,t,r){if(!r)return null;let s=q[e]??`Error (${e}) occurred while trying to load file`;throw Error(`${s}: "${t}".`)}(o.status,u,r);i=f}p=n&&"undefined"!=typeof Response&&o instanceof Response&&200===o.status}a(s.progress_callback,{status:"download",name:e,file:t});let _=await X(o,r=>{a(s.progress_callback,{status:"progress",...r,name:e,file:t})});return p&&i&&await n.match(i)===void 0&&await n.put(i,new Response(_,{headers:o.headers})).catch(e=>{console.warn(`Unable to add response to browser cache: ${e}.`)}),a(s.progress_callback,{status:"done",name:e,file:t}),_}async function K(e,t,r=!0,s={}){let n=await H(e,t,r,s);return null===n?{}:JSON.parse(new TextDecoder("utf-8").decode(n))}async function X(e,t){let r=e.headers.get("Content-Length");null===r&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let s=parseInt(r??"0"),n=new Uint8Array(s),i=0,o=e.body.getReader();async function a(){let{done:e,value:r}=await o.read();if(e)return;let l=i+r.length;if(l>s){s=l;let e=new Uint8Array(s);e.set(n),n=e}n.set(r,i),i=l;let h=i/s*100;return t({progress:h,loaded:i,total:s}),a()}return await a(),n}function V(...e){return(e=e.map((t,r)=>(r&&(t=t.replace(RegExp("^/"),"")),r!==e.length-1&&(t=t.replace(RegExp("/$"),"")),t))).join("/")}function Y(e){let t=Z(e)[0],r=e.map(e=>Math.exp(e-t)),s=r.reduce((e,t)=>e+t,0),n=r.map(e=>e/s);return n}function J(e,t=0){return e=Array.from(e).map((e,t)=>[t,e]).sort((e,t)=>t[1]-e[1]),t>0&&(e=e.slice(0,t)),e}function Z(e){if(0===e.length)throw Error("Array must not be empty");let t=e[0],r=0;for(let s=1;st&&(t=e[s],r=s);return[t,r]}class Q{constructor(e){if(this.size=0|e,this.size<=1||(this.size&this.size-1)!=0)throw Error("FFT size must be a power of two and bigger than 1");this._csize=e<<1,this.table=new Float32Array(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 r}toComplexArray(e,t){let r=t||this.createComplexArray();for(let t=0;t>>1],r[t+1]=0;return r}completeSpectrum(e){let t=this._csize,r=t>>>1;for(let s=2;s>=2;a>=2;a>>=2){let t=(l=i/a<<1)>>>2;for(s=0;s>>1,i>>>1)}else for(a=0,l=0;a>>1,i>>>1,r)}for(i>>=2;i>=2;i>>=2){o=s/i<<1;let t=o>>>1,n=t>>>1,l=n>>>1;for(a=0;a=e.length&&(n=2*(e.length-1)-n),s[i++]=e[n]}s.sort(),r[t]=s[n]}return r}function et(e,t){let r=Math.pow(10,t);return Math.round(e*r)/r}let er=s.Tensor;class es extends er{constructor(...e){return e[0]instanceof s.Tensor?super(e[0].type,e[0].data,e[0].dims):super(...e),new Proxy(this,{get:(e,t)=>{if("string"==typeof t){let r=Number(t);if(Number.isInteger(r))return e._getitem(r)}return e[t]},set:(e,t,r)=>e[t]=r})}*[Symbol.iterator](){let[e,...t]=this.dims;if(t.length>0){let r=t.reduce((e,t)=>e*t);for(let s=0;s0))return new es(this.type,[this.data[e]],r);{let t=r.reduce((e,t)=>e*t);return this._subarray(e,t,r)}}indexOf(e){for(let t=0;te*t);if(r!==s)throw Error(`cannot reshape array of size ${r} into shape (${t})`);let n=e;for(let e=t.length-1;e>=0;e--)n=n.reduce((r,s)=>{let n=r[r.length-1];return n.lengthn[1])throw Error(`Invalid slice: ${n}`);let e=[Math.max(n[0],0),Math.min(n[1],this.dims[s])];r.push(e),t.push(e[1]-e[0])}else throw Error(`Invalid slice: ${n}`)}let s=r.map(([e,t])=>t-e),n=s.reduce((e,t)=>e*t),i=new this.data.constructor(n),o=this.stride();for(let e=0;e=0;--n){let e=s[n];t+=(i%e+r[n][0])*o[n],i=Math.floor(i/e)}i[e]=this.data[t]}return new es(this.type,i,t)}transpose(...e){return en(this,e)}sum(e=null,t=!1){return this.norm(1,e,t)}norm(e="fro",t=null,r=!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,r)=>t+r**e,0)**(1/e);return new es(this.type,[t],[])}t=el(t,this.dims.length);let s=this.dims.slice();s[t]=1;let n=new this.data.constructor(this.data.length/this.dims[t]);for(let r=0;r=0;--e){let r=this.dims[e];if(e!==t){let t=n%r;i+=t*o,o*=s[e]}n=Math.floor(n/r)}n[i]+=this.data[r]**e}if(1!==e)for(let t=0;t=0;--r){let e=this.dims[r];if(r!==t){let t=n%e;s+=t*i,i*=this.dims[r]}n=Math.floor(n/e)}this.data[e]/=r.data[s]}return this}normalize(e=2,t=1){return this.clone().normalize_(e,t)}stride(){return function(e){let t=Array(e.length);for(let r=e.length-1,s=1;r>=0;--r)t[r]=s,s*=e[r];return t}(this.dims)}squeeze(e=null){return new es(this.type,this.data,eo(this.dims,e))}squeeze_(e=null){return this.dims=eo(this.dims,e),this}unsqueeze(e=null){return new es(this.type,this.data,ea(this.dims,e))}unsqueeze_(e=null){return this.dims=ea(this.dims,e),this}flatten_(e=0,t=-1){t=(t+this.dims.length)%this.dims.length;let r=this.dims.slice(0,e),s=this.dims.slice(e,t+1),n=this.dims.slice(t+1);return this.dims=[...r,s.reduce((e,t)=>e*t,1),...n],this}flatten(e=0,t=-1){return this.clone().flatten_(e,t)}view(...e){let t=-1;for(let r=0;rs!==t?e*r:e,1);e[t]=this.data.length/r}return new es(this.type,this.data,e)}neg_(){for(let e=0;e=0;--e)n[e]=i,s[e]=t[r[e]],i*=s[e];let i=r.map((e,t)=>n[r.indexOf(t)]),o=new e.constructor(e.length);for(let r=0;r=0;--e)s+=n%t[e]*i[e],n=Math.floor(n/t[e]);o[s]=e[r]}return[o,s]}(e.data,e.dims,t);return new es(e.type,r,s)}function ei(e,[t,r],s="bilinear",n=!1){let i=e.dims.at(-3)??1,o=e.dims.at(-2),a=e.dims.at(-1),l=function(e,[t,r,s],[n,i],o="bilinear",a=!1){let l=i/s,h=n/r,c=new e.constructor(n*i*t),u=r*s,d=n*i;for(let o=0;o1!==e):"number"==typeof t?1===e[t]&&e.splice(t,1):Array.isArray(t)&&(e=e.filter((e,r)=>1!==e||!t.includes(r))),e}function ea(e,t){return t=el(t,e.length+1),(e=e.slice()).splice(t,0,1),e}function el(e,t,r=null){if(e<-t||e>=t)throw Error(`IndexError: index ${e} is out of bounds for dimension${null===r?"":" "+r} with size ${t}`);return e<0&&(e=(e%t+t)%t),e}function eh(e,t=0){t=el(t,e[0].dims.length);let r=e[0].dims.slice();r[t]=e.reduce((e,r)=>e+r.dims[t],0);let s=r.reduce((e,t)=>e*t,1),n=new e[0].data.constructor(s),i=e[0].type;if(0===t){let t=0;for(let r of e)n.set(r.data,t),t+=r.data.length}else{let s=0;for(let i=0;i=0;--n){let e=o.dims[n],h=a%e;n===t&&(h+=s),i+=h*l,l*=r[n],a=Math.floor(a/e)}n[i]=o.data[e]}s+=o.dims[t]}}return new es(i,n,r)}function ec(e,t=null,r=!1){if(null===t){let t=e.data.reduce((e,t)=>e+t,0);return new es(e.type,[t/e.data.length],[])}t=el(t,e.dims.length);let s=e.dims.slice();s[t]=1;let n=new e.data.constructor(e.data.length/e.dims[t]);for(let r=0;r=0;--n){let r=e.dims[n];if(n!==t){let e=o%r;i+=e*a,a*=s[n]}o=Math.floor(o/r)}n[i]+=e.data[r]}if(1!==e.dims[t])for(let r=0;re>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 r=this._heap[e];this._heap[e]=this._heap[t],this._heap[t]=r}_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 s=new e_(this.bosTokenId,0,0,0,0),n=new e_(this.eosTokenId,1,this.len,0,0);this.nodes.push(s.clone()),this.nodes.push(n.clone()),this.beginNodes[this.len].push(n),this.endNodes[0].push(s)}insert(e,t,r,s){let n=this.nodes.length,i=new e_(s,n,e,t,r);this.beginNodes[e].push(i),this.endNodes[e+t].push(i),this.nodes.push(i)}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 r=0,s=null;for(let n of this.endNodes[t]){let t=n.backtraceScore+e.score;(null===s||t>r)&&(s=n.clone(),r=t)}if(null===s)return[];e.prev=s,e.backtraceScore=r}++t}let r=[],s=this.beginNodes[e][0],n=s.prev;if(null===n)return[];let i=n.clone();for(;null!==i.prev;){r.push(i.clone());let e=i.clone();i=e.prev.clone()}return r.reverse(),r}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)}}class e_{constructor(e,t,r,s,n){this.tokenId=e,this.nodeId=t,this.pos=r,this.length=s,this.score=n,this.prev=null,this.backtraceScore=0}clone(){let e=new e_(this.tokenId,this.nodeId,this.pos,this.length,this.score);return e.prev=this.prev,e.backtraceScore=this.backtraceScore,e}}async function em(e,t){return await Promise.all([K(e,"tokenizer.json",!0,t),K(e,"tokenizer_config.json",!0,t)])}function eg(e,t=!0){return void 0!==e.Regex?RegExp(t?e.Regex:`(${e.Regex})`,"gu"):void 0!==e.String?e.String:(console.warn("Unknown pattern type:",e),null)}function ey(e){return new Map(Object.entries(e))}function ew(e){return e.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n\'t/g,"n't").replace(/ \'m/g,"'m").replace(/ \'s/g,"'s").replace(/ \'ve/g,"'ve").replace(/ \'re/g,"'re")}function eb(e){return e.replace(/[\u0300-\u036f]/g,"")}let ex="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E";class ek extends h{constructor(e){super(),this.config=e,this.vocab=[],this.tokens_to_ids=new Map,this.unk_token_id=void 0,this.unk_token=void 0,this.end_of_word_suffix=void 0,this.fuse_unk=this.config.fuse_unk??!1}static fromConfig(e,...t){switch(e.type){case"WordPiece":return new ev(e);case"Unigram":return new eA(e,...t);case"BPE":return new eT(e);default:if(e.vocab)return new eS(e,...t);throw Error(`Unknown TokenizerModel type: ${e.type}`)}}_call(e){return this.encode(e)}encode(e){throw Error("encode should be implemented in subclass.")}convert_tokens_to_ids(e){let t=e.map(e=>this.tokens_to_ids.get(e)??this.unk_token_id);return this.fuse_unk&&(t=function(e,t){let r=[],s=0;for(;sthis.vocab[e]??this.unk_token)}}class ev extends ek{constructor(e){for(let[t,r]of(super(e),this.tokens_to_ids=ey(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.vocab=Array(this.tokens_to_ids.size),this.tokens_to_ids))this.vocab[r]=t}encode(e){let t=[];for(let r of e){let e=[...r],s=!1,n=0,i=[];for(;n0&&(s=this.config.continuing_subword_prefix+s),this.tokens_to_ids.has(s)){r=s;break}--t}if(null===r){s=!0;break}i.push(r),n=t}s?t.push(this.unk_token):t.push(...i)}return t}}class eA extends ek{constructor(e,t){super(e);let r=e.vocab.length;this.vocab=Array(r),this.scores=Array(r);for(let t=0;t[e,t])),this.bosToken=" ",this.bosTokenId=this.tokens_to_ids.get(this.bosToken),this.eosToken=t.eos_token,this.eosTokenId=this.tokens_to_ids.get(this.eosToken),this.unkToken=this.vocab[this.unk_token_id],this.minScore=function(e){if(0===e.length)throw Error("Array must not be empty");let t=e[0],r=0;for(let s=1;s{let e=[...Array.from({length:94},(e,t)=>t+33),...Array.from({length:12},(e,t)=>t+161),...Array.from({length:82},(e,t)=>t+174)],t=e.slice(),r=0;for(let s=0;s<256;++s)e.includes(s)||(e.push(s),t.push(256+r),r+=1);let s=t.map(e=>String.fromCharCode(e));return Object.fromEntries(e.map((e,t)=>[e,s[t]]))})(),ez=Object.fromEntries(Object.entries(eE).map(([e,t])=>[t,e]));class eT extends ek{constructor(e){for(let[t,r]of(super(e),this.BPE_SPLIT_TOKEN=" ",this.tokens_to_ids=ey(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.vocab=Array(this.tokens_to_ids.size),this.tokens_to_ids))this.vocab[r]=t;this.bpe_ranks=new Map(e.merges.map((e,t)=>[e,t])),this.merges=e.merges.map(e=>e.split(this.BPE_SPLIT_TOKEN)),this.end_of_word_suffix=e.end_of_word_suffix,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.cache=new Map}bpe(e){if(0===e.length)return[];let t=this.cache.get(e);if(void 0!==t)return t;let r=Array.from(e);this.end_of_word_suffix&&(r[r.length-1]+=this.end_of_word_suffix);let s=[];if(r.length>1){let e=new eu((e,t)=>e.score`<0x${e.toString(16).toUpperCase().padStart(2,"0")}>`)):t.push(this.unk_token);return t}}class eS extends ek{constructor(e,t){for(let[r,s]of(super(e),this.tokens_to_ids=ey(t.target_lang?e.vocab[t.target_lang]:e.vocab),this.bos_token=t.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=t.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=t.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=Array(this.tokens_to_ids.size),this.tokens_to_ids))this.vocab[s]=r}encode(e){return e}}class eM extends h{constructor(e){super(),this.config=e}static fromConfig(e){if(null===e)return null;switch(e.type){case"BertNormalizer":return new ej(e);case"Precompiled":return new e9(e);case"Sequence":return new eR(e);case"Replace":return new eI(e);case"NFC":return new eC(e);case"NFKD":return new eB(e);case"Strip":return new eO(e);case"StripAccents":return new eP(e);case"Lowercase":return new eU(e);case"Prepend":return new eL(e);default:throw Error(`Unknown Normalizer type: ${e.type}`)}}normalize(e){throw Error("normalize should be implemented in subclass.")}_call(e){return this.normalize(e)}}class eI extends eM{normalize(e){let t=eg(this.config.pattern);return null===t?e:e=e.replaceAll(t,this.config.content)}}class eC extends eM{normalize(e){return e=e.normalize("NFC")}}class eB extends eM{normalize(e){return e=e.normalize("NFKD")}}class eO extends eM{normalize(e){return this.config.strip_left&&this.config.strip_right?e=e.trim():(this.config.strip_left&&(e=e.trimStart()),this.config.strip_right&&(e=e.trimEnd())),e}}class eP extends eM{normalize(e){return e=eb(e)}}class eU extends eM{normalize(e){return e=e.toLowerCase()}}class eL extends eM{normalize(e){return e=this.config.prepend+e}}class eR extends eM{constructor(e){super(e),this.normalizers=e.normalizers.map(e=>eM.fromConfig(e))}normalize(e){return this.normalizers.reduce((e,t)=>t.normalize(e),e)}}class ej extends eM{_tokenize_chinese_chars(e){let t=[];for(let r=0;r=19968&&e<=40959||e>=13312&&e<=19903||e>=131072&&e<=173791||e>=173824&&e<=177983||e>=177984&&e<=178207||e>=178208&&e<=183983||e>=63744&&e<=64255||e>=194560&&e<=195103}stripAccents(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"")}normalize(e){return this.config.handle_chinese_chars&&(e=this._tokenize_chinese_chars(e)),this.config.lowercase?(e=e.toLowerCase(),!1!==this.config.strip_accents&&(e=this.stripAccents(e))):this.config.strip_accents&&(e=this.stripAccents(e)),e}}class e$ extends h{static fromConfig(e){if(null===e)return null;switch(e.type){case"BertPreTokenizer":return new eN(e);case"Sequence":return new e7(e);case"WhitespaceSplit":return new te(e);case"Metaspace":return new e8(e);case"ByteLevel":return new eF(e);case"Split":return new eD(e);case"Punctuation":return new eq(e);case"Digits":return new eG(e);default:throw Error(`Unknown PreTokenizer type: ${e.type}`)}}pre_tokenize_text(e){throw Error("pre_tokenize_text should be implemented in subclass.")}pre_tokenize(e){return(Array.isArray(e)?e.map(e=>this.pre_tokenize_text(e)):this.pre_tokenize_text(e)).flat()}_call(e){return this.pre_tokenize(e)}}class eN extends e${constructor(e){super(),this.pattern=RegExp(`[^\\s${ex}]+|[${ex}]`,"gu")}pre_tokenize_text(e){return e.trim().match(this.pattern)||[]}}class eF extends e${constructor(e){super(),this.config=e,this.add_prefix_space=this.config.add_prefix_space,this.trim_offsets=this.config.trim_offsets,this.use_regex=this.config.use_regex??!0,this.pattern=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu,this.byte_encoder=eE,this.text_encoder=new TextEncoder}pre_tokenize_text(e){return(this.use_regex?e.match(this.pattern)||[]:[e]).map(e=>(this.add_prefix_space&&!e.startsWith(" ")&&(e=" "+e),e=Array.from(this.text_encoder.encode(e),e=>this.byte_encoder[e]).join("")))}}class eD extends e${constructor(e){super(),this.config=e,this.pattern=eg(this.config.pattern,this.config.invert)}pre_tokenize_text(e){return null===this.pattern?[]:this.config.invert?e.match(this.pattern)||[]:e.split(this.pattern).filter(e=>e)}}class eq extends e${constructor(e){super(),this.config=e,this.pattern=RegExp(`[^${ex}]+|[${ex}]+`,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}}class eG extends e${constructor(e){super(),this.config=e;let t=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=RegExp(t,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}}class eW extends h{constructor(e){super(),this.config=e}static fromConfig(e){if(null===e)return null;switch(e.type){case"TemplateProcessing":return new eX(e);case"ByteLevel":return new eV(e);case"RobertaProcessing":return new eK(e);case"BertProcessing":return new eH(e);default:throw Error(`Unknown PostProcessor type: ${e.type}`)}}post_process(e,...t){throw Error("post_process should be implemented in subclass.")}_call(e,...t){return this.post_process(e,...t)}}class eH extends eW{constructor(e){super(e),this.cls=e.cls[0],this.sep=e.sep[0]}post_process(e,t=null){return e=f([this.cls],e,[this.sep]),null!==t&&(e=f(e,[this.sep],t,[this.sep])),e}}class eK extends eH{}class eX extends eW{constructor(e){super(e),this.single=e.single,this.pair=e.pair}post_process(e,t=null){let r=null===t?this.single:this.pair,s=[];for(let n of r)"SpecialToken"in n?s.push(n.SpecialToken.id):"Sequence"in n&&("A"===n.Sequence.id?s=f(s,e):"B"===n.Sequence.id&&(s=f(s,t)));return s}}class eV extends eW{post_process(e){return e}}class eY extends h{constructor(e){super(),this.config=e,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=e.trim_offsets}static fromConfig(e){switch(e.type){case"WordPiece":return new e1(e);case"Metaspace":return new e5(e);case"ByteLevel":return new e2(e);case"Replace":return new eJ(e);case"ByteFallback":return new eZ(e);case"Fuse":return new eQ(e);case"Strip":return new e0(e);case"Sequence":return new e6(e);case"CTC":return new e3(e);case"BPEDecoder":return new e4(e);default:throw Error(`Unknown Decoder type: ${e.type}`)}}_call(e){return this.decode(e)}decode(e){return this.decode_chain(e).join("")}decode_chain(e){throw Error("`decode_chain` should be implemented in subclass.")}}class eJ extends eY{decode_chain(e){let t=eg(this.config.pattern);return null===t?e:e.map(e=>e.replaceAll(t,this.config.content))}}class eZ extends eY{constructor(e){super(e),this.text_decoder=new TextDecoder}decode_chain(e){let t=[],r=[];for(let s of e){let e=null;if(6===s.length&&s.startsWith("<0x")&&s.endsWith(">")){let t=parseInt(s.slice(3,5),16);isNaN(t)||(e=t)}if(null!==e)r.push(e);else{if(r.length>0){let e=this.text_decoder.decode(Uint8Array.from(r));t.push(e),r=[]}t.push(s)}}if(r.length>0){let e=this.text_decoder.decode(Uint8Array.from(r));t.push(e),r=[]}return t}}class eQ extends eY{decode_chain(e){return[e.join("")]}}class e0 extends eY{constructor(e){super(e),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(e){return e.map(e=>{let t=0;for(let r=0;r(0!==t&&(e=e.startsWith(this.config.prefix)?e.replace(this.config.prefix,""):" "+e),this.cleanup&&(e=ew(e)),e))}}class e2 extends eY{constructor(e){super(e),this.byte_decoder=ez,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(e){let t=e.join(""),r=new Uint8Array([...t].map(e=>this.byte_decoder[e]));return this.text_decoder.decode(r)}decode_chain(e){let t=[],r=[];for(let s of e)this.added_tokens.includes(s)?(r.length>0&&(t.push(this.convert_tokens_to_string(r)),r=[]),t.push(s)):r.push(s);return r.length>0&&t.push(this.convert_tokens_to_string(r)),t}}class e3 extends eY{constructor(e){super(e),this.pad_token=this.config.pad_token,this.word_delimiter_token=this.config.word_delimiter_token,this.cleanup=this.config.cleanup}convert_tokens_to_string(e){if(0===e.length)return"";let t=[e[0]];for(let r=1;re!==this.pad_token).join("");return this.cleanup&&(r=ew(r).replaceAll(this.word_delimiter_token," ").trim()),r}decode_chain(e){return[this.convert_tokens_to_string(e)]}}class e6 extends eY{constructor(e){super(e),this.decoders=e.decoders.map(e=>eY.fromConfig(e))}decode_chain(e){return this.decoders.reduce((e,t)=>t.decode_chain(e),e)}}class e4 extends eY{constructor(e){super(e),this.suffix=this.config.suffix}decode_chain(e){return e.map((t,r)=>t.replaceAll(this.suffix,r===e.length-1?"":" "))}}class e8 extends e${constructor(e){super(),this.addPrefixSpace=e.add_prefix_space,this.replacement=e.replacement,this.strRep=e.str_rep||this.replacement}pre_tokenize(e){"string"==typeof e&&(e=e.trimStart().split(/\s+/));let t=[];for(let r of e){let e=r.replaceAll(" ",this.strRep);this.addPrefixSpace&&!e.startsWith(this.replacement)&&(e=this.strRep+e),t.push(e)}return t}}class e5 extends eY{constructor(e){super(e),this.addPrefixSpace=e.add_prefix_space,this.replacement=e.replacement}decode_chain(e){let t=[];for(let r=0;re.normalize("NFKC")).join("~")}else e=e.normalize("NFKC");return e}}class e7 extends e${constructor(e){super(),this.tokenizers=e.pretokenizers.map(e=>e$.fromConfig(e))}pre_tokenize_text(e){return"string"==typeof e&&(e=[e]),this.tokenizers.reduce((e,t)=>t.pre_tokenize(e),e)}}class te extends e${constructor(e){super()}pre_tokenize_text(e){return e.match(/\S+/g)||[]}}class tt extends h{constructor(e,t){for(let r of(super(),this.normalizer=eM.fromConfig(e.normalizer),this.pre_tokenizer=e$.fromConfig(e.pre_tokenizer),this.model=ek.fromConfig(e.model,t),this.post_processor=eW.fromConfig(e.post_processor),this.decoder=eY.fromConfig(e.decoder),this.decoder.end_of_word_suffix=this.model.end_of_word_suffix,this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[],e.added_tokens)){let e=r.id,t=r.content;this.added_tokens.push(t),this.model.tokens_to_ids.set(t,e),this.model.vocab[e]=t,r.special&&(this.special_tokens.push(t),this.all_special_ids.push(e))}this.special_tokens.push(...t.additional_special_tokens??[]),this.special_tokens=[...new Set(this.special_tokens)],this.decoder.added_tokens=this.added_tokens,this.added_tokens_regex=this.added_tokens.length>0?RegExp("("+this.added_tokens.map(l).join("|")+")"):null,this.mask_token=this.getToken(t,"mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken(t,"pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken(t,"sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.model_max_length=t.model_max_length,this.remove_space=t.remove_space,this.clean_up_tokenization_spaces=t.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=t.do_lowercase_and_remove_accent??!1,this.padding_side="right"}getToken(e,...t){for(let r of t){let t=e[r];if(t){if("object"!=typeof t)return t;if("AddedToken"===t.__type)return t.content;throw Error(`Unknown token: ${t}`)}}return null}static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:s=null,local_files_only:n=!1,revision:i="main"}={}){let o=await em(e,{progress_callback:t,config:r,cache_dir:s,local_files_only:n,revision:i});return new this(...o)}prepare_model_inputs(e){return e}_call(e,{text_pair:t=null,padding:r=!1,truncation:s=null,max_length:n=null,return_tensor:i=!0}={}){let o;if(Array.isArray(e)){if(0===e.length)throw Error("text array must be non-empty");if(null!==t){if(Array.isArray(t)){if(e.length!==t.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");o=e.map((e,r)=>this.encode(e,t[r]))}else o=e.map(e=>this.encode(e))}else{if(null===e)throw Error("text may not be null");if(Array.isArray(t))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");o=[this.encode(e,t)]}let a=Z(o.map(e=>e.length))[0];null===n&&(n=a),n=Math.min(n,this.model_max_length);let l=[];if(r||s)for(let e=0;en)s&&(o[e]=o[e].slice(0,n)),l.push(Array(o[e].length).fill(1));else if(r){let t=n-o[e].length;"right"===this.padding_side?(l.push(Array(o[e].length).fill(1).concat(Array(t).fill(0))),o[e].push(...Array(t).fill(this.pad_token_id))):(l.push(Array(t).fill(0).concat(Array(o[e].length).fill(1))),o[e].unshift(...Array(t).fill(this.pad_token_id)))}else l.push(Array(o[e].length).fill(1))}else l=o.map(e=>Array(e.length).fill(1));if(i){if(!(r&&s)&&o.some(e=>e.length!==o[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");let e=[o.length,o[0].length];o=new es("int64",BigInt64Array.from(o.flat().map(BigInt)),e),l=new es("int64",BigInt64Array.from(l.flat().map(BigInt)),e)}else Array.isArray(e)||(o=o[0],l=l[0]);let h={input_ids:o,attention_mask:l};return this.prepare_model_inputs(h)}_encode_text(e){if(null===e)return null;let t=this.added_tokens_regex?e.split(this.added_tokens_regex).filter(e=>e):[e];return t.map(e=>{if(this.added_tokens.includes(e))return e;{!0===this.remove_space&&(e=e.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(e=eb(e.toLowerCase())),null!==this.normalizer&&(e=this.normalizer(e));let t=null!==this.pre_tokenizer?this.pre_tokenizer(e):[e];return this.model(t)}}).flat()}encode(e,t=null){let r=this._encode_text(e),s=this._encode_text(t),n=null!==this.post_processor?this.post_processor(r,s):f(r??[],s??[]);return this.model.convert_tokens_to_ids(n)}batch_decode(e,t={}){return e.map(e=>this.decode(e,t))}decode(e,t={}){if(!Array.isArray(e)||0===e.length||!u(e[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(e,t)}decode_single(e,{skip_special_tokens:t=!1,clean_up_tokenization_spaces:r=null}){let s=this.model.convert_ids_to_tokens(e);t&&(s=s.filter(e=>!this.special_tokens.includes(e)));let n=this.decoder(s);return this.decoder.end_of_word_suffix&&(n=n.replaceAll(this.decoder.end_of_word_suffix," "),t&&(n=n.trim())),(r??this.clean_up_tokenization_spaces)&&(n=ew(n)),n}}function tr(e){if(e.input_ids instanceof es)e.token_type_ids=new es("int64",new BigInt64Array(e.input_ids.data.length),e.input_ids.dims);else if(Array.isArray(e.input_ids))Array.isArray(e.input_ids[0])?e.token_type_ids=e.input_ids.map(e=>Array(e.length).fill(0)):e.token_type_ids=Array(e.input_ids.length).fill(0);else throw Error("Input ids must be a Tensor or an Array");return e}class ts extends tt{prepare_model_inputs(e){return tr(e)}}class tn extends tt{prepare_model_inputs(e){return tr(e)}}class ti extends tt{prepare_model_inputs(e){return tr(e)}}class to extends tt{prepare_model_inputs(e){return tr(e)}}class ta extends tt{prepare_model_inputs(e){return tr(e)}}class tl extends tt{prepare_model_inputs(e){return tr(e)}}class th extends tt{prepare_model_inputs(e){return tr(e)}}class tc extends tt{}class tu extends tt{}class td extends tt{constructor(e,t){super(e,t),console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}prepare_model_inputs(e){return tr(e)}}class tf extends tt{}class tp extends tt{}class t_ extends tt{}class tm extends tt{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(e=>this.languageRegex.test(e)),this.lang_to_token=e=>e}_build_translation_inputs(e,t,r){return tz(this,e,t,r)}}class tg extends tm{}class ty extends tt{}class tw extends tt{constructor(e,t){let r=".,!?…。,、।۔،",s=e.pre_tokenizer?.pretokenizers[0]?.pattern;s&&s.Regex===` ?[^(\\s|[${r}])]+`&&(s.Regex=` ?[^\\s${r}]+`),super(e,t)}}class tb extends tt{}class tx extends tt{}class tk extends tt{}class tv extends tt{}class tA extends tt{prepare_model_inputs(e){return tr(e)}}class tE extends tt{}function tz(e,t,r,s){if(!("language_codes"in e)||!Array.isArray(e.language_codes))throw Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in e)||!(e.languageRegex instanceof RegExp))throw Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in e)||"function"!=typeof e.lang_to_token)throw Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");let n=s.src_lang,i=s.tgt_lang;if(!e.language_codes.includes(i))throw Error(`Target language code "${i}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);if(void 0!==n){if(!e.language_codes.includes(n))throw Error(`Source language code "${n}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);for(let t of e.post_processor.config.single)if("SpecialToken"in t&&e.languageRegex.test(t.SpecialToken.id)){t.SpecialToken.id=e.lang_to_token(n);break}}return s.forced_bos_token_id=e.model.convert_tokens_to_ids([e.lang_to_token(i)])[0],e._call(t,r)}class tT extends tt{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(e=>this.languageRegex.test(e)),this.lang_to_token=e=>e}_build_translation_inputs(e,t,r){return tz(this,e,t,r)}}class tS extends tt{constructor(e,t){super(e,t),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(e=>this.languageRegex.test(e)).map(e=>e.slice(2,-2)),this.lang_to_token=e=>`__${e}__`}_build_translation_inputs(e,t,r){return tz(this,e,t,r)}}let tM=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]],tI=new Map(tM),tC=new Map([...tM.map(([e,t])=>[t,e]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);class tB extends tt{_decode_asr(e,{return_timestamps:t=!1,return_language:r=!1,time_precision:s=null,force_full_sequences:n=!0}={}){if(null===s)throw Error("Must specify time_precision");let i=null,o="word"===t;function a(){return{language:i,timestamp:[null,null],text:""}}let l=[],h=a(),c=0,u=this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1,d=[],f=[],p=!1,_=null,m=new Set(this.all_special_ids);for(let r of e){let e=r.tokens,n=o?r.token_timestamps:null,g=null,y=u;if("stride"in r){let[t,n,i]=r.stride;if(c-=n,_=t-i,n&&(y=n/s+u),i)for(let t=e.length-1;t>=0;--t){let r=e[t];if(r>=u){if(null!==g&&(r-u)*s<_)break;g=r}}}let w=[],b=[];for(let r=0;r=u){let e=(_-u)*s+c,t=et(e,2);if(null!==g&&_>=g)p=!0;else if(p||d.length>0&&_0?(d.push(w),o&&f.push(b)):d.every(e=>0===e.length)&&(h=a(),d=[],w=[],f=[],b=[])}if(d.length>0){if(n&&t)throw Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");let[e,r]=this.findLongestCommonSequence(d,f),s=this.decode(e);h.text=s,o&&(h.words=this.collateWordTimestamps(e,r,i)),l.push(h)}let g=Object.create(null),y=l.map(e=>e.text).join("");if(t||r){for(let e=0;e0,o=i?[]:null,a=i?t[0]:null;for(let l=1;le===f[t]).length,_=p/e+t;p>1&&_>c&&(c=_,u=[n,i,a,l])}let[f,p,_,m]=u,g=Math.floor((p+f)/2),y=Math.floor((m+_)/2);n.push(...r.slice(0,g)),s=(r=h.slice(y)).length,i&&(o.push(...a.slice(0,g)),a=t[l].slice(y))}return(n.push(...r),i)?(o.push(...a),[n,o]):[n,[]]}collateWordTimestamps(e,t,r){let[s,n,i]=this.combineTokensIntoWords(e,r),o=[];for(let e=0;e=s){let e=(t-s)*r;e=et(e,2),n.push(`<|${e}|>`),n.push([])}else n[n.length-1].push(t);return(n=n.map(e=>"string"==typeof e?e:super.decode(e,t))).join("")}splitTokensOnUnicode(e){let t=this.decode(e,{decode_with_timestamps:!0}),r=[],s=[],n=[],i=[],o=[],a=0;for(let l=0;l=this.model.tokens_to_ids.get("<|endoftext|>"),d=l.startsWith(" "),f=l.trim(),p=a.test(f);if(u||d||p||0===n.length)n.push(l),i.push(h),o.push(c);else{let e=n.length-1;n[e]+=l,i[e].push(...h),o[e].push(...c)}}return[n,i,o]}mergePunctuations(e,t,r,s,n){let i=structuredClone(e),o=structuredClone(t),a=structuredClone(r),l=i.length-2,h=i.length-1;for(;l>=0;)i[l].startsWith(" ")&&s.includes(i[l].trim())?(i[h]=i[l]+i[h],o[h]=f(o[l],o[h]),a[h]=f(a[l],a[h]),i[l]="",o[l]=[],a[l]=[]):h=l,--l;for(l=0,h=1;he),o.filter(e=>e.length>0),a.filter(e=>e.length>0)]}get_decoder_prompt_ids({language:e=null,task:t=null,no_timestamps:r=!0}={}){let s=[];if(e){e=e.toLowerCase();let t=tC.get(e);if(void 0===t){if(tI.has(e))t=e;else{let t=2===e.length,r=t?tI.keys():tI.values();throw Error(`Language "${e}" is not supported. Must be one of: ${JSON.stringify(r)}`)}}let r=this.model.tokens_to_ids.get(`<|${t}|>`);if(void 0===r)throw Error(`Unable to find language "${t}" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.`);s.push(r)}else s.push(null);if(t){if("transcribe"!==(t=t.toLowerCase())&&"translate"!==t)throw Error(`Task "${t}" is not supported. Must be one of: ["transcribe", "translate"]`);let e=this.model.tokens_to_ids.get(`<|${t}|>`);if(void 0===e)throw Error(`Unable to find task "${t}" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.`);s.push(e)}else s.push(null);if(r){let e=this.model.tokens_to_ids.get("<|notimestamps|>");if(void 0===e)throw Error('Unable to find "<|notimestamps|>" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.');s.push(e)}return s.map((e,t)=>[t+1,e]).filter(e=>null!==e[1])}}class tO extends tt{}class tP extends tt{}class tU extends tt{constructor(e,t){super(e,t),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(e=>this.languageRegex.test(e)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(e){if(null===e)return null;let[t,...r]=e.trim().split(this.languageRegex);if(0===r.length)return super._encode_text(t);if(2===r.length){let[e,t]=r;return this.supported_language_codes.includes(e)||console.warn(`Unsupported language code "${e}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),f([e],super._encode_text(t))}}}class tL extends tt{}class tR{static TOKENIZER_CLASS_MAPPING={T5Tokenizer:tf,DistilBertTokenizer:tc,CamembertTokenizer:tu,DebertaTokenizer:ta,DebertaV2Tokenizer:tl,BertTokenizer:ts,HerbertTokenizer:th,XLMTokenizer:td,MobileBertTokenizer:ti,SqueezeBertTokenizer:to,AlbertTokenizer:tn,GPT2Tokenizer:tp,BartTokenizer:t_,MBartTokenizer:tm,MBart50Tokenizer:tg,RobertaTokenizer:ty,WhisperTokenizer:tB,CodeGenTokenizer:tO,CLIPTokenizer:tP,MarianTokenizer:tU,BloomTokenizer:tw,NllbTokenizer:tT,M2M100Tokenizer:tS,LlamaTokenizer:tb,CodeLlamaTokenizer:tx,XLMRobertaTokenizer:tk,MPNetTokenizer:tv,FalconTokenizer:tA,GPTNeoXTokenizer:tE,Wav2Vec2CTCTokenizer:tL,PreTrainedTokenizer:tt};static async from_pretrained(e,{quantized:t=!0,progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:i=!1,revision:o="main"}={}){let[a,l]=await em(e,{quantized:t,progress_callback:r,config:s,cache_dir:n,local_files_only:i,revision:o}),h=l.tokenizer_class.replace(/Fast$/,""),c=this.TOKENIZER_CLASS_MAPPING[h];return c||(console.warn(`Unknown tokenizer class "${h}", attempting to construct from base class.`),c=tt),new c(a,l)}}async function tj(e,t){return await K(e,"config.json",!0,t)}class t${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:r=null,cache_dir:s=null,local_files_only:n=!1,revision:i="main"}={}){let o=r??await tj(e,{progress_callback:t,config:r,cache_dir:s,local_files_only:n,revision:i});return new this(o)}}class tN{static async from_pretrained(...e){return t$.from_pretrained(...e)}}class tF extends h{constructor(){super(),this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,t){for(let r of t)this.processors.forEach(t=>t(e,r))}[Symbol.iterator](){return this.processors.values()}}class tD extends h{_call(e,t){throw Error("`_call` should be implemented in a subclass")}}class tq extends tD{constructor(e){super(),this.force_token_map=Object.fromEntries(e??[])}_call(e,t){let r=this.force_token_map[e.length];return null!=r&&(t.data.fill(-1/0),t.data[r]=0),t}}class tG extends tD{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}}class tW extends tD{constructor(e,t){super(),this.max_length=e,this.forced_eos_token_id=t}_call(e,t){}}class tH extends tD{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}}class tK extends tD{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){if(t.data[this.no_timestamps_token_id]=-1/0,e.length===this.begin_index-1)return t.data.fill(-1/0),t.data[this.timestamp_begin]=0,t;let r=e.slice(this.begin_index),s=r.length>=1&&r[r.length-1]>=this.timestamp_begin,n=r.length<2||r[r.length-2]>=this.timestamp_begin;if(s&&(n?t.data.subarray(this.timestamp_begin).fill(-1/0):t.data.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;t.data.subarray(e+1).fill(-1/0)}let i=function(e){let t=Y(e),r=t.map(e=>Math.log(e));return r}(t.data),o=Math.log(i.subarray(this.timestamp_begin).map(Math.exp).reduce((e,t)=>e+t)),a=Z(i.subarray(0,this.timestamp_begin))[0];return o>a&&t.data.subarray(0,this.timestamp_begin).fill(-1/0),t}}class tX extends tD{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){let t=e.length,r=[];for(let s=0;s0&&(s=s.map(e=>e/this.generation_config.temperature)),s}randomSelect(e){let t=Math.random()*e.reduce((e,t)=>e+t,0);for(let r=0;r1)return new t0(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 tZ(e)}}class tZ extends tJ{sample(e,t=-1){return[[Z(this.getLogits(e,t))[1],0]]}}class tQ extends tJ{sample(e,t=-1){let r=e.dims.at(-1);this.generation_config.top_k>0&&(r=Math.min(this.generation_config.top_k,r));let s=this.getLogits(e,t),n=J(s,r),i=Y(n.map(e=>e[1]));return Array.from({length:this.generation_config.num_beams},()=>{let e=this.randomSelect(i);return[n[e][0],Math.log(i[e])]})}}class t0 extends tJ{sample(e,t=-1){let r=e.dims.at(-1);this.generation_config.top_k>0&&(r=Math.min(this.generation_config.top_k,r));let s=this.getLogits(e,t),n=J(s,r),i=Y(n.map(e=>e[1]));return Array.from({length:this.generation_config.num_beams},(e,t)=>[n[t][0],Math.log(i[t])])}}let{InferenceSession:t1,Tensor:t2}=s,t3={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4},t6=new Map([["CLIPTextModelWithProjection",t3.EncoderOnly],["CLIPVisionModelWithProjection",t3.EncoderOnly]]);async function t4(e,t,r){let s=`onnx/${t}${r.quantized?"_quantized":""}.onnx`,n=await H(e,s,!0,r);try{return await t1.create(n,{executionProviders:E})}catch(e){if(1===E.length&&"wasm"===E[0])throw e;return console.warn(e),console.warn("Something went wrong during model construction (most likely a missing operation). Using `wasm` as a fallback. "),await t1.create(n,{executionProviders:["wasm"]})}}async function t8(e,t){let r={},s=[];for(let n of e.inputNames)void 0===t[n]?s.push(n):r[n]=t[n];if(s.length>0)throw Error(`An error occurred during model execution: "Missing the following inputs: ${s.join(", ")}.`);let n=Object.keys(t).length,i=e.inputNames.length;return n>i&&console.warn(`WARNING: Too many inputs were provided (${n} > ${i}). The following inputs will be ignored: "${Object.keys(t).filter(t=>!e.inputNames.includes(t)).join(", ")}".`),r}async function t5(e,t){let r=await t8(e,t);try{let t=await e.run(r);return t=function e(t){for(let r in t)t[r]instanceof t2?t[r]=new es(t[r]):"object"==typeof t[r]&&e(t[r]);return t}(t)}catch(e){throw console.error(`An error occurred during model execution: "${e}".`),console.error("Inputs given to model:",r),e}}function t9(e,t){let r=e.config.pad_token_id??null,s=e.config.eos_token_id??null;u(s)&&(s=[s]);let n=-1!==t.indexOf(r),i=null===s||!s.includes(r);if(!n||!i)return new es("int64",new BigInt64Array(t.data.length).fill(1n),t.dims);{let e=BigInt64Array.from(t.data.map(e=>e!=r));return new es("int64",e,t.dims)}}function t7(e){return new es("bool",[e],[1])}async function re(e,t){let r=e.add_decoder_pkv??!0,{encoder_outputs:s,past_key_values:n}=t;s||(s=(await rn(e,t)).last_hidden_state);let i={input_ids:t.decoder_input_ids,encoder_hidden_states:s,use_cache_branch:t7(!!n)};e.decoder_merged_session.inputNames.includes("encoder_attention_mask")&&(i.encoder_attention_mask=t.attention_mask),e.addPastKeyValues(i,n,r);let o=await t5(e.decoder_merged_session,i),a=o.logits;n=e.getPastKeyValues(o,n);let l=e.getAttentions(o);return new sp({logits:a,past_key_values:n,encoder_outputs:s,...l})}function rt(e,t,r){let s=[],n=0,i=e.requires_attention_mask??!0,o=e.config.decoder_start_token_id;for(let r of(Array.isArray(o)||(o=[o]),t)){r.dims=[1,...r.dims];let t={inputs:r,encoder_outputs:null,prev_model_outputs:null,output_token_ids:o,done:!1,score:0,id:n++};i&&(t.attention_mask=t9(e,r)),s.push(t)}return s}async function rr(e,t){let r=e.main_input_name,s={[r]:t.inputs,decoder_input_ids:function(e){if(e instanceof es)return e;if(0===e.length)throw Error("items must be non-empty");if(!Array.isArray(e[0]))return new es("int64",BigInt64Array.from(e.map(e=>BigInt(e))),[1,e.length]);if(e.some(t=>t.length!==e[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new es("int64",BigInt64Array.from(e.flat().map(e=>BigInt(e))),[e.length,e[0].length])}(t.output_token_ids.slice(-1)),encoder_outputs:t.encoder_outputs,past_key_values:t.prev_model_outputs?.past_key_values};t.attention_mask&&(s.attention_mask=t.attention_mask);let n=await e.forward(s);return t.prev_model_outputs=n,t.encoder_outputs=n.encoder_outputs,n}function rs(e,t){e.output_token_ids=[...e.output_token_ids,t]}async function rn(e,t){let r={};for(let s of e.session.inputNames)r[s]=t[s];return await t5(e.session,r)}async function ri(e,t){let{input_ids:r,past_key_values:s,attention_mask:n}=t,i={input_ids:r,attention_mask:n??t9(e,r),use_cache_branch:t7(!!s)};e.addPastKeyValues(i,s);let o=await t5(e.session,i);return{logits:o.logits,past_key_values:s=e.getPastKeyValues(o,s)}}function ro(e,t,r,s){let n=[],i=0;for(let o of t){let t,a=o.tolist().map(Number);o.dims=[1,...o.dims],s?(t=s[i]).dims=[1,...t.dims]:t=t9(e,o);let l={input:o,model_input_ids:o,attention_mask:t,prev_model_outputs:null,output_token_ids:a,num_output_tokens:r,done:!1,score:0,id:i++};n.push(l)}return n}async function ra(e,t){let r=new BigInt64Array(t.output_token_ids.length).fill(1n),s={input_ids:t.model_input_ids,attention_mask:new es("int64",r,[1,r.length]),past_key_values:t.prev_model_outputs?.past_key_values},n=await e.forward(s);return t.prev_model_outputs=n,n}function rl(e,t){e.output_token_ids=[...e.output_token_ids,t],e.model_input_ids=new es("int64",[BigInt(t)],[1,1])}class rh extends h{main_input_name="input_ids";constructor(e,t){super(),this.config=e,this.session=t;let r=this.constructor.name,s=t6.get(r);this.can_generate=!1,this._runBeam=null,this._getStartBeams=null,this._updateBeam=null,this._forward=null,s===t3.DecoderOnly?(this.can_generate=!0,this._runBeam=ra,this._getStartBeams=ro,this._updateBeam=rl,this._forward=ri):s===t3.Seq2Seq||s===t3.Vision2Seq?(this.can_generate=!0,this._runBeam=rr,this._getStartBeams=rt,this._updateBeam=rs,this._forward=re):(t3.EncoderDecoder,this._forward=rn)}async dispose(){let e=[];for(let t of Object.keys(this)){let r=this[t];r instanceof t1&&e.push(r.handler.dispose())}return await Promise.all(e)}static async from_pretrained(e,{quantized:t=!0,progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:i=!1,revision:o="main",model_file_name:a=null}={}){let l,h={quantized:t,progress_callback:r,config:s,cache_dir:n,local_files_only:i,revision:o,model_file_name:a},c=t6.get(this.name);return c===t3.DecoderOnly?l=await Promise.all([tN.from_pretrained(e,h),t4(e,h.model_file_name??"decoder_model_merged",h)]):c===t3.Seq2Seq||c===t3.Vision2Seq?l=await Promise.all([tN.from_pretrained(e,h),t4(e,"encoder_model",h),t4(e,"decoder_model_merged",h),K(e,"generation_config.json",!1,h)]):c===t3.EncoderDecoder?l=await Promise.all([tN.from_pretrained(e,h),t4(e,"encoder_model",h),t4(e,"decoder_model_merged",h)]):(c!==t3.EncoderOnly&&console.warn(`Model type for ${this.name} not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`),l=await Promise.all([tN.from_pretrained(e,h),t4(e,h.model_file_name??"model",h)])),new this(...l)}async _call(e){return await this.forward(e)}async forward(e){return await this._forward(this,e)}_get_logits_processor(e,t,r=null){let s=new tF;if(null!==e.repetition_penalty&&1!==e.repetition_penalty&&s.push(new tV(e.repetition_penalty)),null!==e.no_repeat_ngram_size&&e.no_repeat_ngram_size>0&&s.push(new tX(e.no_repeat_ngram_size)),null!==e.forced_bos_token_id&&s.push(new tG(e.forced_bos_token_id)),null!==e.forced_eos_token_id&&s.push(new tW(e.max_length,e.forced_eos_token_id)),null!==e.begin_suppress_tokens){let r=t>1||null===e.forced_bos_token_id?t:t+1;null!==e.forced_decoder_ids&&(r+=e.forced_decoder_ids[e.forced_decoder_ids.length-1][0]),s.push(new tH(e.begin_suppress_tokens,r))}return null!==e.forced_decoder_ids&&s.push(new tq(e.forced_decoder_ids)),null!==r&&s.extend(r),s}_get_generation_config(e){let t=new tY;return"generation_config"in this&&Object.assign(t,this.generation_config),null!==e&&Object.assign(t,e),t}async generate(e,t=null,r=null,{inputs_attention_mask:s=null}={}){let n;if(!this.can_generate){let e=se.get(this.config.model_type),t=`The current model class (${this.constructor.name}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw e&&(t+=` Please use one of the following classes instead: {'${e.constructor.name}'}`),Error(t)}if(!(e instanceof es)&&e?.prototype?.__proto__?.constructor?.name!=="TypedArray"&&!Array.isArray(e))throw Error(`\`inputs\` must be a Tensor, TypedArray, or Array, but is "${e.constructor.name}".`);if(this.config.is_encoder_decoder)n=0;else if(0===(n=e instanceof es?e.dims[0]:e.length))throw Error("Must supply a non-empty array of input token ids.");t=this._get_generation_config(t),r=r??new tF,r=this._get_logits_processor(t,n,r);let i=1,o=i+(t.max_new_tokens??1/0),a=Number.isInteger(t.max_length)&&(t.max_new_tokens??null)===null,l=tJ.getSampler(t),h=this.getStartBeams(e,i,s);for(;h.some(e=>!e.done)&&i=t.max_length){s.done=!0,e.push(s);continue}let n=await this.runBeam(s);t.output_attentions&&this.addAttentionsToBeam(s,n),t.output_scores;let i=n.logits.slice(null,-1,null);for(let[t,n]of(r(s.output_token_ids,i),l(i))){let r={...s};this.updateBeam(r,t),r.score+=n,t===this.config.eos_token_id&&(r.done=!0),e.push(r)}}++i,h=(e=this.groupBeams(e).map(e=>e.sort((e,t)=>t.score-e.score).slice(0,t.num_beams))).flat(),t.callback_function&&t.callback_function(h)}let c=this.groupBeams(h),u=e=>c.map(r=>t.num_return_sequences>1?r.slice(0,t.num_return_sequences).map(t=>t[e]):[r[0][e]]).flat(),d=u("output_token_ids");if(!t.return_dict_in_generate)return d;{let e=u("decoder_attentions"),t=u("cross_attentions");return{sequences:d,decoder_attentions:e,cross_attentions:t}}}addAttentionsToBeam(e,t){if(this.config.is_encoder_decoder){if(!t.cross_attentions||0===t.cross_attentions.length)throw Error("`output_attentions` is true, but the model did not produce cross-attentions. This is most likely because the model was not exported with `output_attentions=True`.");e.cross_attentions||(e.cross_attentions=[]),e.cross_attentions.push(t.cross_attentions)}if(!t.decoder_attentions||0===t.decoder_attentions.length)throw Error("`output_attentions` is true, but the model did not produce decoder-attentions. This is most likely because the model was not exported with `output_attentions=True`.");e.decoder_attentions||(e.decoder_attentions=[]),e.decoder_attentions.push(t.decoder_attentions)}groupBeams(e){let t=Object.create(null);for(let r of e)void 0===t[r.id]?t[r.id]=[r]:t[r.id].push(r);return Object.values(t)}getPastKeyValues(e,t){let r=Object.create(null);for(let s in e)if(s.startsWith("present")){let n=s.replace("present","past_key_values");t&&s.includes("encoder")?r[n]=t[n]:r[n]=e[s]}return r}getAttentions(e){let t=Object.create(null);for(let r of["cross_attentions","decoder_attentions"]){let s=[];for(let t in e)if(t.startsWith(r)){let r=t.split(".").pop();s[r]=e[t]}t[r]=s}return t}addPastKeyValues(e,t,r=!1){if(t)Object.assign(e,t);else if(r){let t=[1,this.num_encoder_heads,0,this.encoder_dim_kv];for(let r=0;r{let s=Array.from({length:this.config.decoder_layers},(t,r)=>eh(e.map(e=>e[r]),2)),i=function(e,t=0){return eh(e.map(e=>e.unsqueeze(t)),t)}(t.map(([e,t])=>r?s[e].slice(null,t,null,[0,r]):s[e].slice(null,t))),[o,a]=function(e,t=null,r=1,s=!1){if(null===t){let t=e.data.reduce((e,t)=>e+t,0),s=t/e.data.length,n=Math.sqrt(e.data.reduce((e,t)=>e+(t-s)**2,0)/(e.data.length-r)),i=new es(e.type,[s],[]),o=new es(e.type,[n],[]);return[o,i]}t=el(t,e.dims.length);let n=ec(e,t,s),i=e.dims.slice();i[t]=1;let o=new e.data.constructor(e.data.length/e.dims[t]);for(let r=0;r=0;--n){let r=e.dims[n];if(n!==t){let e=o%r;s+=e*a,a*=i[n]}o=Math.floor(o/r)}o[s]+=(e.data[r]-n.data[s])**2}for(let s=0;s0||a>0;){l.push(o-1),h.push(a-1);let e=i[o][a].item();switch(e){case 0:--o,--a;break;case 1:--o;break;case 2:--a;break;default:throw Error(`Internal error in dynamic time warping. Unexpected trace[${o}, ${a}]. Please file a bug report.`)}}return l.reverse(),h.reverse(),[l,h]}(t),o=f([1],Array.from({length:r.length-1},(e,t)=>r[t+1]-r[t])).map(e=>!!e),l=[];for(let e=0;e{if(!self.OffscreenCanvas)throw Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(e,t)},o=self.createImageBitmap,i=self.ImageData;else if(sb)o=async e=>{let t=await e.metadata(),r=t.channels,{data:s,info:n}=await e.raw().toBuffer({resolveWithObject:!0}),i=new sv(new Uint8ClampedArray(s),n.width,n.height,n.channels);return void 0!==r&&r!==n.channels&&i.convert(r),i};else throw Error("Unable to load image processing library.");let sk={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"};class sv{_CONTENT_TYPE_MAP={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"};constructor(e,t,r,s){this._update(e,t,r,s)}static async read(e){if(e instanceof sv)return e;if(c(e)||e instanceof URL)return await this.fromURL(e);throw Error(`Unsupported input type: ${typeof e}`)}static async fromURL(e){let t=await D(e);if(200!==t.status)throw Error(`Unable to read image from "${e}" (${t.status} ${t.statusText})`);let r=await t.blob();return this.fromBlob(r)}static async fromBlob(e){if(sx){let t=await o(e),r=n(t.width,t.height).getContext("2d");return r.drawImage(t,0,0),new this(r.getImageData(0,0,t.width,t.height).data,t.width,t.height,4)}{let t=sb(await e.arrayBuffer());return await o(t)}}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,r=0;t=0?l=r:c=-r,s>=0?h=s:u=-s,a.drawImage(o,l,h,e,t,c,u,e,t),new sv(a.getImageData(0,0,e,t).data,e,t,4).convert(i)}{let n=this.toSharp();if(r>=0&&s>=0)n=n.extract({left:Math.floor(r),top:Math.floor(s),width:e,height:t});else if(r<=0&&s<=0){let i=Math.floor(-s),o=Math.floor(-r);n=n.extend({top:i,left:o,right:e-this.width-o,bottom:t-this.height-i})}else{let i=[0,0],o=0;s<0?(i[0]=Math.floor(-s),i[1]=t-this.height-i[0]):o=Math.floor(s);let a=[0,0],l=0;r<0?(a[0]=Math.floor(-r),a[1]=e-this.width-a[0]):l=Math.floor(r),n=n.extend({top:i[0],bottom:i[1],left:a[0],right:a[1]}).extract({left:l,top:o,width:e,height:t})}return await o(n)}}toCanvas(){if(!sx)throw Error("toCanvas() is only supported in browser environments.");let e=this.clone().rgba(),t=n(e.width,e.height),r=new i(e.data,e.width,e.height);return t.getContext("2d").putImageData(r,0,0),t}_update(e,t,r,s=null){return this.data=e,this.width=t,this.height=r,null!==s&&(this.channels=s),this}clone(){return new sv(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}save(e){if(sx){let t=e.split(".").pop().toLowerCase(),r=this._CONTENT_TYPE_MAP[t]??"image/png",s=this.toCanvas(),n=s.toDataURL(r),i=document.createElement("a");i.href=n,i.download=e,i.click(),i.remove()}else if(L.useFS){let t=this.toSharp();t.toFile(e)}else throw Error("Unable to save the image because filesystem is disabled in this environment.")}toSharp(){if(sx)throw Error("toSharp() is only supported in server-side environments.");return sb(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}async function sA(e,t){let r;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 s=await (await D(e)).arrayBuffer(),n=new AudioContext({sampleRate:t});void 0===t&&console.warn(`No sampling rate provided, using default of ${n.sampleRate}Hz.`);let i=await n.decodeAudioData(s);if(2===i.numberOfChannels){let e=Math.sqrt(2),t=i.getChannelData(0),s=i.getChannelData(1);r=new Float32Array(t.length);for(let n=0;nt){let t=u[e].data;t=function([e,t,r,s]){return[e-r/2,t-s/2,e+r/2,t+s/2]}(t),null!==i&&(t=t.map((e,t)=>e*i[(t+1)%2])),h.boxes.push(t),h.classes.push(s),h.scores.push(n)}}l.push(h)}return l}class sz extends h{constructor(e){super(),this.config=e}}class sT extends sz{constructor(e){super(e),this.image_mean=this.config.image_mean,this.image_std=this.config.image_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.size=this.config.size,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.pad_size=this.config.pad_size,this.do_pad=(this.config.do_pad??!1)&&this.pad_size}async preprocess(e){this.do_convert_rgb&&(e=e.rgb());let t=e.width,r=e.height;if(this.do_resize){let s,n;if(Number.isInteger(this.size)?(s=this.size,n=this.config.max_size??s):(s=this.size.shortest_edge,n=this.size.longest_edge),void 0!==s||void 0!==n){let i=void 0===s?1:Math.max(s/t,s/r),o=t*i,a=r*i,l=void 0===n?1:Math.min(n/o,n/a),h=Math.floor(Number((o*l).toPrecision(3))),c=Math.floor(Number((a*l).toPrecision(3)));e=await e.resize(h,c,{resample:this.resample})}else if(void 0!==this.size.width&&void 0!==this.size.height)e=await e.resize(this.size.width,this.size.height,{resample:this.resample});else throw Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(this.size)}`)}if(this.do_center_crop){let t,r;Number.isInteger(this.crop_size)?(t=this.crop_size,r=this.crop_size):(t=this.crop_size.width,r=this.crop_size.height),e=await e.center_crop(t,r)}let s=[e.height,e.width];if(this.do_pad){let t=this.pad_size.width-e.width,r=this.pad_size.height-e.height;e=await e.pad([0,t,0,r])}let n=Float32Array.from(e.data);if(this.do_rescale)for(let e=0;ethis.preprocess(e)));return t.forEach(e=>e.pixel_values.dims=[1,...e.pixel_values.dims]),{pixel_values:eh(t.map(e=>e.pixel_values)),original_sizes:t.map(e=>e.original_size),reshaped_input_sizes:t.map(e=>e.reshaped_input_size)}}}class sS extends sT{}class sM extends sT{}class sI extends sT{}class sC extends sT{}class sB extends sT{}class sO extends sT{async _call(e){let t=await super._call(e),r=[t.pixel_values.dims[0],64,64];return t.pixel_mask=new es("int64",new BigInt64Array(r.reduce((e,t)=>e*t)).fill(1n),r),t}post_process_object_detection(...e){return sE(...e)}remove_low_and_no_objects(e,t,r,s){let n=[],i=[],o=[];for(let a=0;ar&&(n.push(h),i.push(u),o.push(c))}return[n,i,o]}check_segment_validity(e,t,r,s=.5,n=.8){let i=[],o=0,a=0;for(let n=0;n=s&&++a;let l=o>0&&a>0;return l&&(l=o/a>n),[l,i]}compute_segments(e,t,r,s,n,i=null,o=null){let[a,l]=o??e[0].dims,h=new es("int32",new Int32Array(a*l),[a,l]),c=[];if(null!==o)for(let t=0;td[t]&&(u[t]=r,d[t]=e[r].data[t])}let f=0;for(let i=0;iBigInt(Math.round(e)))),i)}}post_process_masks(e,t,r,{mask_threshold:s=0,binarize:n=!0,pad_size:i=null}={}){let o=[],a=[(i=i??this.pad_size).height,i.width];for(let i=0;ie>s),t.dims)),t.dims=[1,...t.dims],u.push(t)}let d=eh(u);o.push(d)}return o}}class sL extends sz{constructor(e){super(e),this.config.mel_filters??=function(e,t,r=128){r=Math.floor(r);let s=Math.floor(1+t/2),n=Array(r),i=function(e,t=1){if(!Number.isInteger(e))throw TypeError(`n should be an integer, but ${e} given.`);let r=1/(e*t),s=Math.floor(e/2)+1,n=Array(s);for(let e=0;e=h?l[e]=1e3*Math.exp(c*(t-h)):l[e]=0+a*t,u[e]=i.map(t=>l[e]-t)}let d=l.slice(1).map((e,t)=>1/(e-l[t]));for(let e=0;e>1;++e){let t=(e+1-r)**2/2,s=Math.sqrt(m**2+g**2)**t,n=t*Math.atan2(g,m),i=2*e;l[i]=s*Math.cos(n),l[i+1]=s*Math.sin(n),h[i]=l[i],h[i+1]=-l[i+1]}let y=l.subarray(s,n),w=new Q(i>>1);w.transform(d,h);for(let r=0;r>1,i=n[s]*t[s];c[e]=i*y[e],c[r]=i*y[r]}w.transform(f,c);for(let e=0;es?i-s:0,r=i>1,l=new Float32Array(o*a);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`.");let t=e.slice(0,this.config.n_samples),r=this._extract_fbank_features(t);return{input_features:new es("float32",r.data,[1,...r.dims])}}}class sR extends sz{_zero_mean_unit_var_norm(e){let t=e.reduce((e,t)=>e+t,0),r=t/e.length,s=e.reduce((e,t)=>e+(t-r)**2,0)/e.length;return e.map(e=>(e-r)/Math.sqrt(s+1e-7))}async _call(e){if(!(e instanceof Float32Array||e instanceof Float64Array))throw Error(`Wav2Vec2FeatureExtractor 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.`);e instanceof Float64Array&&(e=new Float32Array(e));let t=e;this.config.do_normalize&&(t=this._zero_mean_unit_var_norm(t));let r=[1,t.length];return{input_values:new es("float32",t,r),attention_mask:new es("int64",new BigInt64Array(t.length).fill(1n),r)}}}class sj extends h{constructor(e){super(),this.feature_extractor=e}async _call(e){return await this.feature_extractor(e)}}class s$ extends sj{async _call(e,t){return await this.feature_extractor(e,t)}post_process_masks(...e){return this.feature_extractor.post_process_masks(...e)}}class sN extends sj{async _call(e){return await this.feature_extractor(e)}}class sF extends sj{async _call(e){return await this.feature_extractor(e)}}class sD{static FEATURE_EXTRACTOR_CLASS_MAPPING={WhisperFeatureExtractor:sL,ViTFeatureExtractor:sM,MobileViTFeatureExtractor:sI,ConvNextFeatureExtractor:sS,BeitFeatureExtractor:sB,DeiTFeatureExtractor:sC,DetrFeatureExtractor:sO,YolosFeatureExtractor:sP,SamImageProcessor:sU,Wav2Vec2FeatureExtractor:sR};static PROCESSOR_CLASS_MAPPING={WhisperProcessor:sN,Wav2Vec2ProcessorWithLM:sF,SamProcessor:s$};static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:s=null,local_files_only:n=!1,revision:i="main"}={}){let o=r??await K(e,"preprocessor_config.json",!0,{progress_callback:t,config:r,cache_dir:s,local_files_only:n,revision:i}),a=o.feature_extractor_type??o.image_processor_type,l=this.FEATURE_EXTRACTOR_CLASS_MAPPING[a];if(!l){if(void 0!==o.size)console.warn("Feature extractor type not specified, assuming ImageFeatureExtractor due to size parameter in config."),l=sT;else throw Error(`Unknown Feature Extractor type: ${o.feature_extractor_type}`)}let h=this.PROCESSOR_CLASS_MAPPING[o.processor_class]??sj,c=new l(o);return new h(c)}}async function sq(e){return Array.isArray(e)||(e=[e]),e=await Promise.all(e.map(e=>sv.read(e)))}class sG extends h{constructor({task:e,model:t,tokenizer:r=null,processor:s=null}){super(),this.task=e,this.model=t,this.tokenizer=r,this.processor=s}async dispose(){await this.model.dispose()}async _call(e,...t){let r=this.tokenizer(e,{padding:!0,truncation:!0}),s=await this.model(r);return[r,s]}}class sW extends sG{_key=null;async _call(e,t={}){let r;Array.isArray(e)||(e=[e]),this.model.config.prefix&&(e=e.map(e=>this.model.config.prefix+e));let s=this.model.config.task_specific_params;s&&s[this.task]&&s[this.task].prefix&&(e=e.map(e=>s[this.task].prefix+e));let n={padding:!0,truncation:!0};r=this instanceof sH&&"_build_translation_inputs"in this.tokenizer?this.tokenizer._build_translation_inputs(e,n,t).input_ids:this.tokenizer(e,n).input_ids;let i=await this.model.generate(r,t),o=this.tokenizer.batch_decode(i,{skip_special_tokens:!0});return null!==this._key&&(o=o.map(e=>null===this._key?e:{[this._key]:e})),o}}class sH extends sW{_key="translation_text"}let sK={"text-classification":{tokenizer:tR,pipeline:class extends sG{async _call(e,{topk:t=1}={}){let r="multi_label_classification"===this.model.config.problem_type?e=>e.sigmoid().data:e=>Y(e.data),[s,n]=await super._call(e),i=this.model.config.id2label,o=[];for(let e of n.logits){let s=J(r(e),t).map(function(e){return{label:i[e[0]],score:e[1]}});1===t?o.push(...s):o.push(s)}return Array.isArray(e)||1===t?o:o[0]}},model:sd,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:tR,pipeline:class extends sG{async _call(e,{ignore_labels:t=["O"]}={}){let r=Array.isArray(e);r||(e=[e]);let s=this.tokenizer,[n,i]=await super._call(e),o=i.logits,a=this.model.config.id2label,l=[];for(let e=0;ee.flatMap(e=>t.map(t=>[e,t])))})(Array.from(Y(n.start_logits[e].data)).map((e,t)=>[e,t]).filter(e=>e[1]>o),Array.from(Y(n.end_logits[e].data)).map((e,t)=>[e,t]).filter(e=>e[1]>o)).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:n.model.vocab[e[0]],sequence:n.decode(t,{skip_special_tokens:!0})}}))}return Array.isArray(e)?i:i[0]}},model:class extends r3{static MODEL_CLASS_MAPPINGS=[st]},default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:tR,pipeline:class extends sW{_key="summary_text"},model:sf,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:tR,pipeline:sH,model:sf,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:tR,pipeline:sW,model:sf,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:tR,pipeline:class extends sG{async _call(e,t={}){let r="string"==typeof e||e instanceof String;r&&(e=[e]),this.tokenizer.padding_side="left";let s=this.tokenizer(e,{padding:!0,truncation:!0}),n=s.input_ids,i=s.attention_mask,o=await this.model.generate(n,t,null,{inputs_attention_mask:i}),a=this.tokenizer.batch_decode(o,{skip_special_tokens:!0}),l=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:r="This example is {}.",multi_label:s=!1}={}){let n=Array.isArray(e);n||(e=[e]),Array.isArray(t)||(t=[t]);let i=t.map(e=>r.replace("{}",e)),o=s||1===t.length,a=[];for(let r of e){let e=[];for(let t of i){let s=this.tokenizer(r,{text_pair:t,padding:!0,truncation:!0}),n=await this.model(s);o?e.push([n.logits.data[this.contradiction_id],n.logits.data[this.entailment_id]]):e.push(n.logits.data[this.entailment_id])}let s=(o?e.map(e=>Y(e)[1]):Y(e)).map((e,t)=>[e,t]).sort((e,t)=>t[0]-e[0]);a.push({sequence:r,labels:s.map(e=>t[e[1]]),scores:s.map(e=>e[0])})}return n?a:a[0]}},model:sd,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:class extends sG{constructor(e){super(e)}async _preprocess(e,t){return c(e)&&(e=await sA(e,t)),e}async _call(e,{topk:t=5}={}){let r=!Array.isArray(e);r&&(e=[e]);let s=this.model.config.id2label,n=this.processor.feature_extractor.config.sampling_rate,i=[];for(let r of e){r=await this._preprocess(r,n);let e=await this.processor(r),o=await this.model(e),a=o.logits[0],l=J(Y(a.data),t).map(function(e){return{label:s[e[0]],score:e[1]}});1===t?i.push(...l):i.push(l)}return r&&1!==t?i[0]:i}},model:class extends r3{static MODEL_CLASS_MAPPINGS=[sh]},processor:sD,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"automatic-speech-recognition":{tokenizer:tR,pipeline:class extends sG{constructor(e){super(e)}async _preprocess(e,t){return c(e)&&(e=await sA(e,t)),e}async _call(e,t={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(e,t);case"wav2vec2":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 r=!Array.isArray(e);r&&(e=[e]);let s=this.processor.feature_extractor.config.sampling_rate,n=[];for(let t of e){t=await this._preprocess(t,s);let e=await this.processor(t),r=await this.model(e),i=r.logits[0],o=[];for(let e of i)o.push(Z(e.data)[1]);let a=this.tokenizer.decode(o);n.push({text:a})}return r?n[0]:n}async _call_whisper(e,t={}){let r=t.return_timestamps??!1,s=t.chunk_length_s??0,n=t.stride_length_s??null,i=t.chunk_callback??null,o=t.force_full_sequences??!1;"word"===r&&(t.return_token_timestamps=!0);let a=d(t,"language",null),l=d(t,"task",null);if(a||l||r){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:a,task:l,no_timestamps:!r});e.length>0&&(t.forced_decoder_ids=e)}let h=!Array.isArray(e);h&&(e=[e]);let c=this.processor.feature_extractor.config.sampling_rate,u=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,f=this.processor.feature_extractor.config.hop_length,p=[];for(let a of e){a=await this._preprocess(a,c);let e=[];if(s>0){if(null===n)n=s/6;else if(s<=n)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");let t=c*s,r=c*n,i=t-2*r,o=0;for(;o=a.length;e.push({stride:[s.length,l?0:r,h?0:r],input_features:n.input_features,is_last:h}),o+=i}}else e=[{stride:[a.length,0,0],input_features:(await this.processor(a)).input_features,is_last:!0}];for(let s of e){t.num_frames=Math.floor(s.stride[0]/f);let e=await this.model.generate(s.input_features,t);"word"===r?(s.tokens=e.sequences[0],s.token_timestamps=e.token_timestamps.tolist()[0].map(e=>et(e,2))):s.tokens=e[0],s.stride=s.stride.map(e=>e/c),null!==i&&i(s)}let[l,h]=this.tokenizer._decode_asr(e,{time_precision:u,return_timestamps:r,force_full_sequences:o});p.push({text:l,...h})}return h?p[0]:p}},model:[sf,class extends r3{static MODEL_CLASS_MAPPINGS=[sl]}],processor:sD,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"image-to-text":{tokenizer:tR,pipeline:class extends sG{constructor(e){super(e)}async _call(e,t={}){let r=Array.isArray(e);e=await sq(e);let{pixel_values:s}=await this.processor(e),n=[];for(let e of s){e.dims=[1,...e.dims];let r=await this.model.generate(e,t),s=this.tokenizer.batch_decode(r,{skip_special_tokens:!0}).map(e=>({generated_text:e.trim()}));n.push(s)}return r?n:n[0]}},model:class extends r3{static MODEL_CLASS_MAPPINGS=[ss]},processor:sD,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:class extends sG{constructor(e){super(e)}async _call(e,{topk:t=1}={}){let r=Array.isArray(e);e=await sq(e);let{pixel_values:s}=await this.processor(e),n=await this.model({pixel_values:s}),i=this.model.config.id2label,o=[];for(let e of n.logits){let r=J(Y(e.data),t).map(function(e){return{label:i[e[0]],score:e[1]}});1===t?o.push(...r):o.push(r)}return r||1===t?o:o[0]}},model:class extends r3{static MODEL_CLASS_MAPPINGS=[sn]},processor:sD,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:class extends sG{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:r=.5,overlap_mask_area_threshold:s=.8,label_ids_to_fuse:n=null,target_sizes:i=null,subtask:o=null}={}){if(Array.isArray(e)&&1!==e.length)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");let a=(e=await sq(e)).map(e=>[e.height,e.width]),{pixel_values:l,pixel_mask:h}=await this.processor(e),c=await this.model({pixel_values:l,pixel_mask:h}),u=null;if(null!==o)u=this.subtasks_mapping[o];else for(let[e,t]of Object.entries(this.subtasks_mapping))if(t in this.processor.feature_extractor){u=this.processor.feature_extractor[t].bind(this.processor.feature_extractor),o=e;break}let d=[];if("panoptic"===o||"instance"===o){let e=u(c,t,r,s,n,i??a)[0],o=e.segmentation,l=this.model.config.id2label;for(let t of e.segments_info){let e=new Uint8ClampedArray(o.data.length);for(let r=0;rr.replace("{}",e)),i=this.tokenizer(n,{padding:!0,truncation:!0}),{pixel_values:o}=await this.processor(e),a=await this.model({...i,pixel_values:o}),l=[];for(let e of a.logits_per_image){let r=Y(e.data);l.push([...r].map((e,r)=>({score:e,label:t[r]})))}return s?l:l[0]}},model:su,processor:sD,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:class extends sG{constructor(e){super(e)}async _call(e,{threshold:t=.9,percentage:r=!1}={}){let s=Array.isArray(e);if(s&&1!==e.length)throw Error("Object detection pipeline currently only supports a batch size of 1.");e=await sq(e);let n=r?null:e.map(e=>[e.height,e.width]),{pixel_values:i,pixel_mask:o}=await this.processor(e),a=await this.model({pixel_values:i,pixel_mask:o}),l=this.processor.feature_extractor.post_process_object_detection(a,t,n),h=this.model.config.id2label,c=l.map(e=>e.boxes.map((t,s)=>({score:e.scores[s],label:h[e.classes[s]],box:this._get_bounding_box(t,!r)})));return s?c:c[0]}_get_bounding_box(e,t){t&&(e=e.map(e=>0|e));let[r,s,n,i]=e;return{xmin:r,ymin:s,xmax:n,ymax:i}}},model:class extends r3{static MODEL_CLASS_MAPPINGS=[si]},processor:sD,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"feature-extraction":{tokenizer:tR,pipeline:class extends sG{async _call(e,{pooling:t="none",normalize:r=!1}={}){let[s,n]=await super._call(e),i=n.last_hidden_state??n.logits;if("none"===t);else if("mean"===t)i=function(e,t){let r=[e.dims[0],e.dims[2]],s=new e.data.constructor(r[0]*r[1]),[n,i,o]=e.dims,a=0;for(let r=0;r{let n;for(let s of o)try{e(await s.from_pretrained(t,r));return}catch(e){n=e}s(n)}):o.from_pretrained(t,r),s[i]=e,n.push(e))}for(let[e,t]of(await Promise.all(n),Object.entries(s)))s[e]=await t;return s}}}]); \ No newline at end of file